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
+1145 -219

No files matched your search

+4 -1
View File
@@ -154,6 +154,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162) - A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162)
- Two FSEvent-burst rescans can double-count one shared `PostScanCache` miss (both snapshot the count before either stamps it) → `contentRevision` double-bumps, benign over-invalidation — tests pinning settled-state revision must quiesce the burst (stability loop ≥ the 0.5 s FSEvents latency) before snapshotting (#197) - Two FSEvent-burst rescans can double-count one shared `PostScanCache` miss (both snapshot the count before either stamps it) → `contentRevision` double-bumps, benign over-invalidation — tests pinning settled-state revision must quiesce the burst (stability loop ≥ the 0.5 s FSEvents latency) before snapshotting (#197)
- A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178) - A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178)
- A subscript after a count expectation (`log.requests[2]` after `#expect(count == 3)`) traps the hosted runner — every queued test reports `Crash:` too; read elements through an optional accessor (#206)
- Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33) - Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33)
- An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151) - An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151)
- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134) - When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134)
@@ -165,10 +166,12 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147) - A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147)
- One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180) - One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180)
- A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181) - A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181)
- `value of type 'X' has no member` while the emitted module DOES carry the symbol is a spelling drift between targets, not a stale build — grep the exact name across app AND tests before hunting binaries: a fresh test file's `microblogStatus` against the code's `micropubStatus` reads exactly like the stale-binary signature above and cost a DerivedData dive (#206)
### Trust boundaries ### Trust boundaries
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6) - A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34) - A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
- The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33) - The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33)
- A format gate is not an ownership gate — when a change raises a sink's stakes (status flip → content replace), re-ask who may write the value, not merely whether it is well-formed (#206)
## Session Logs ## Session Logs
@@ -177,6 +180,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start --> <!-- write-log: window-start -->
| Date | Log | | Date | Log |
|------|-----| |------|-----|
| 2026-12-04 | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) |
| 2026-12-04 | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) | | 2026-12-04 | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) |
| 2026-12-03 | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) | | 2026-12-03 | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) |
| 2026-12-03 | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) | | 2026-12-03 | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) |
@@ -186,5 +190,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) | | 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) |
| 2026-11-30 | [20261130-external-watch-compares-unnormalized-text_log.md](20261130-external-watch-compares-unnormalized-text_log.md) | | 2026-11-30 | [20261130-external-watch-compares-unnormalized-text_log.md](20261130-external-watch-compares-unnormalized-text_log.md) |
| 2026-11-23 | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) | | 2026-11-23 | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) |
| 2026-11-19 | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) |
<!-- write-log: window-end --> <!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added ### Added
- **publish:** the library shows where each piece stands on Micro.blog (#206) — a published piece's row reads `published <date>` and its menu opens the live post; a sent-but-unpublished one reads `draft on Micro.blog`. Publish is remembered now (`micropub_published` stamped in the piece's frontmatter — the sheet used to flip the draft and forget, so nothing on disk ever said a piece was out). Sending a piece again no longer duplicates it: a piece that remembers its post updates that post in place (same URL — a draft refreshes for review, a published piece edits live via **Update Live Post**), and an image whose bytes haven't changed rides its earlier upload instead of uploading a second copy (a per-piece `.museion-uploads.json` memo keyed by content hash). When Micro.blog answers 404 — the post was deleted there — the piece forgets the dead link and the sheet offers a fresh draft instead of failing forever. A file brought in by Import carries no Micro.blog memory: its `micropub_url`/`micropub_published` lines are dropped at the boundary, so a file from someone else can never aim a send at one of your existing posts. Pieces published before this build read as drafts until their next Publish (or the `micropub_published` key is added to the frontmatter by hand — `yyyy-MM-dd'T'HH:mm:ss`, local time). The row's micro-label shows the status in origin's place (the 178pt row cannot hold both); VoiceOver reads both.
- **settings:** **Micro.blog** page in Settings — the app token's home (unticketed; owner report 2026-12-04) — the token could only be entered in the publish sheet, and that field came back only after a 401/403, so a saved token had no standing way to be replaced or removed (a 503 left the writer stuck with whatever was stored). The new sidebar destination, after Provider Keys, writes the SAME login-keychain slot the sheet reads (`MicropubTokenStore`): a status row under the field (✓ Token saved in your Keychain / No token saved), a Save field that replaces the stored token, and a Remove button while one is stored. `saved` is read back from the Keychain after every write instead of assumed — a locked keychain fails the save and the status row says so rather than claiming "stored". The publish sheet picks up a Settings-saved token unchanged, and names it when it sends with the stored one (the field's absence alone never said which token a send carried). No new pins (a view over the already-pinned token store; the repo pins pure seams, not SwiftUI). Suite 736 - **settings:** **Micro.blog** page in Settings — the app token's home (unticketed; owner report 2026-12-04) — the token could only be entered in the publish sheet, and that field came back only after a 401/403, so a saved token had no standing way to be replaced or removed (a 503 left the writer stuck with whatever was stored). The new sidebar destination, after Provider Keys, writes the SAME login-keychain slot the sheet reads (`MicropubTokenStore`): a status row under the field (✓ Token saved in your Keychain / No token saved), a Save field that replaces the stored token, and a Remove button while one is stored. `saved` is read back from the Keychain after every write instead of assumed — a locked keychain fails the save and the status row says so rather than claiming "stored". The publish sheet picks up a Settings-saved token unchanged, and names it when it sends with the stored one (the field's absence alone never said which token a send carried). No new pins (a view over the already-pinned token store; the repo pins pure seams, not SwiftUI). Suite 736
- **library:** **Reveal in Finder** and **Copy Path** on every piece row — the library column's menu and the Archive pane's (#205) — one shared `FinderHandOffButtons` fragment in the workspace chrome over a model-resolved path: `PostsModel.fileURL(for:)` answers the piece's `post.md` through the one `PostStore.folder(of:home:)` resolver against the watched Home (never the scan snapshot), and a vanished piece answers nil so both entries no-op instead of revealing a stale path. Reveal selects the file in Finder; Copy Path puts the POSIX path on the pasteboard (Finder's own form; the pasteboard is cleared first). Library placement sits between Move to Archive and the destructive Trash behind a divider; the Archive menu appends after Convert. +3 tests (projects/ resolve, archive/ resolve, vanished → nil), flip-verified — bypassing the resolver reddens exactly the vanished and archive pins. Suite 735 - **library:** **Reveal in Finder** and **Copy Path** on every piece row — the library column's menu and the Archive pane's (#205) — one shared `FinderHandOffButtons` fragment in the workspace chrome over a model-resolved path: `PostsModel.fileURL(for:)` answers the piece's `post.md` through the one `PostStore.folder(of:home:)` resolver against the watched Home (never the scan snapshot), and a vanished piece answers nil so both entries no-op instead of revealing a stale path. Reveal selects the file in Finder; Copy Path puts the POSIX path on the pasteboard (Finder's own form; the pasteboard is cleared first). Library placement sits between Move to Archive and the destructive Trash behind a divider; the Archive menu appends after Convert. +3 tests (projects/ resolve, archive/ resolve, vanished → nil), flip-verified — bypassing the resolver reddens exactly the vanished and archive pins. Suite 735
+12
View File
@@ -156,3 +156,15 @@ _Avoid_: permission mode
**Provenance**: **Provenance**:
The origin record carried by a Fix Card or Learning (piece, date, engine). The origin record carried by a Fix Card or Learning (piece, date, engine).
_Avoid_: metadata _Avoid_: metadata
## Discovered Terms
<!-- distill-learnings: discovered-terms -->
### Publish Record
What a Piece remembers about Micro.blog in its frontmatter: `micropub_url` (the post it was sent to) and, once Publish succeeded from here, `micropub_published` (the stamp, local time). Museion bookkeeping — written only by the app or the writer's own hand; Import drops both keys. A remembered URL without the stamp is a draft on Micro.blog.
_Avoid_: publish state (it is a record on disk, never a live query), status (that is Pass State)
### Upload Memo
The per-Piece sidecar `.museion-uploads.json` mapping an illustration's bytes (`sha256`) to the URL Micro.blog returned, so an unchanged image uploads once. Finder-invisible, dies with the Piece folder, never trusted from outside — a symlinked memo or an untrustworthy entry is no memory.
_Avoid_: upload cache (it is Piece-local bookkeeping, not a shared cache)
+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`. - `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`. - 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. - 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`. - Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in `Assets.xcassets/AppIcon.appiconset`.
## Workspace shell ## 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). - `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). - `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). - `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. - `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. - `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/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it. - `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` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil. - `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`) 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. - `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. 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. - `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). - `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). - `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. - `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). - `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). - `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. - `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). - 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). `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. - `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. - `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). - `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`). - `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() Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: post) FinderHandOffButtons(model: model, post: post)
} }
} }
+20 -4
View File
@@ -9,8 +9,10 @@
import SwiftUI import SwiftUI
/// One post row per the export: title + origin-only mono-11 meta (the Pass /// One post row per the export: title + a mono-11 meta line — origin, or
/// State rides the uppercase group label above; it stays in the a11y label). /// (#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 /// #108 (variant B): 2px accent edge bar on the leading side when selected
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`, /// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the /// 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). // group label above (it stays in the accessibility label).
// r7: the status micro-label sits INSIDE the row's content // r7: the status micro-label sits INSIDE the row's content
// padding — same x as the title, never flush with the edge. // 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)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.help(post.origin.rawValue)
} }
.padding(.horizontal, 12) .padding(.horizontal, 12)
.padding(.vertical, 10) .padding(.vertical, 10)
@@ -89,6 +95,16 @@ struct LibraryPostRow: View {
// help sits on the row — the ✳ span isn't individually hoverable in // help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star). // SwiftUI (prototype: `title="outline"` on the star).
.help(post.type == .outline ? "\(post.title) — outline" : post.title) .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 // #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the // PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in // 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, // Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the // 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 /// header, body url as fallback) — what `publish` targets and
/// what the piece remembers. /// what the piece remembers.
case drafted(url: String, preview: String?) 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 case published
/// No open saved piece (model guard) — nothing went out. /// No open saved piece (model guard) — nothing went out.
case refused(String) 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 authFailed(String)
case requestFailed(status: Int, detail: String) case requestFailed(status: Int, detail: String)
case unreachable(String) case unreachable(String)
@@ -52,12 +66,19 @@ nonisolated enum Micropub {
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic) // 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) var request = URLRequest(url: endpoint)
request.httpMethod = "POST" request.httpMethod = "POST"
request.timeoutInterval = 30 request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") 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 // h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim // Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped) — the one carve-out is #34's asset // (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 // disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01). // wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1. // category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [ jsonPost([
"type": ["h-entry"], "type": ["h-entry"],
"properties": [ "properties": [
"name": [title], "name": [title],
"content": [body], "content": [body],
"post-status": ["draft"], "post-status": ["draft"],
] as [String: Any], ] as [String: Any],
], options: [.sortedKeys]) ], token: token)
return request
} }
static func makePublishRequest(url: String, token: String) -> URLRequest { static func makePublishRequest(url: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint) jsonPost([
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", "action": "update",
"url": url, "url": url,
"replace": ["post-status": ["published"]], "replace": ["post-status": ["published"]],
], options: [.sortedKeys]) ], token: token)
return request
} }
// 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 /// 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 /// 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) 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 /// One POST + the honest decode: 2xx → drafted/published (drafts
/// need a URL — Location header first, body `url` second; the /// need a URL — Location header first, body `url` second; the
/// preview link is display-only, never the publish target; a create /// 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 /// the frontmatter block on the next parse and re-parse as BODY
/// (arbitrary markdown in the writer's piece, shipped under their /// (arbitrary markdown in the writer's piece, shipped under their
/// token by the next send). Applied at both ends: the decode above /// token by the next send). Applied at both ends: the decode above
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim). /// and `Post.scan`'s read-back. Format-only by design — ownership is
/// Format-only by design — ponytail: a well-formed foreign URL still /// settled upstream, not here: the import boundary drops the micropub
/// passes (the label shows its full text); host-allowlist when v2's /// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place
/// q=config surface names the blog's real domains. /// 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 { static func trustworthyURL(_ string: String) -> Bool {
guard !string.isEmpty, guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil, string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
@@ -166,6 +216,21 @@ nonisolated enum Micropub {
return true 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 /// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it. /// 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 /// 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 { extension PostsModel {
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog /// The OPEN saved library piece as the micropub pair (id, Home) —
/// as a draft (h=entry, name = Title, markdown content, post-status /// the identity guard both publish steps share. brief-28: the open
/// draft — category frontmatter never travels). runPass's guard set /// session must target THIS library's selected piece; the wire and
/// minus the engine gates (no engine involved); flush-first so the /// every stamp below act on the piece actually sent (Home, ID),
/// wire carries the editor's latest. On success the piece remembers /// never the current Home's same-slug file. Nil = nothing to send.
/// the draft URL (`micropub_url` stamp) — a stamp failure never private var openMicropubPiece: (id: String, home: URL)? {
/// 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.
guard let session, guard let session,
let id = session.postID, let id = session.postID,
let home = watchedHome, let home = watchedHome,
@@ -271,18 +322,39 @@ extension PostsModel {
draft == nil, draft == nil,
externalSession == nil, externalSession == nil,
outlineGuardPieceID == 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.") 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.") 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 // 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, // bookkeeping, never prose; the body itself is never stripped,
// GLOSSARY). No scan dependency: the list can lag the open piece. // GLOSSARY), and the remembered URL. No scan dependency: the
guard let dir = PostStore.folder(of: id, home: home), // 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) let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { else {
return .refused("Couldn't read the piece before sending.") return .refused("Couldn't read the piece before sending.")
@@ -303,25 +375,91 @@ extension PostsModel {
return outcome 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( let outcome = await Micropub.sendDraft(
title: Post.title(of: raw), title: title,
body: wireBody, body: wireBody,
token: token, token: token,
transport: transport, transport: transport,
) )
if case let .drafted(url, _) = outcome { if case let .drafted(url, _) = outcome {
// Remember the draft URL for the publish step. A stamp // Remember the draft's URL for the publish step and every
// failure can't un-send the draft; the sheet still holds // later in-place update. A stamp failure can't un-send the
// the URL for this session — the piece just loses the // draft; the sheet still holds the URL for this session —
// memory across a reopen (re-send the draft then). Kept // the piece just loses the memory across a reopen (it
// quiet: lastError's setter stays PostsModel-file-private, // would create a second draft then). Kept quiet: the same
// and the same disk accepted the flush moments before. // disk accepted the flush moments before.
try? PostStore.stampMicropubURL(id: id, url: url, home: home) try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
} }
return outcome 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 /// FLOOR first (G12): a photo without alt text never ships, and
/// nothing touches the wire until every illustration clears it — /// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref, /// 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 // `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one // first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL. // destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/" let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = [] var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) { 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)) payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
} }
// ponytail: a re-send re-uploads (Micro.blog keeps both return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport)
// copies) — dedup via q=source listing is v2's call. }
/// 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 let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) { switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named): case let .url(named):
@@ -378,8 +539,9 @@ extension PostsModel {
case let .failed(outcome): case let .failed(outcome):
return .blocked(outcome) return .blocked(outcome)
} }
var uploaded: [String: String] = [:] // The `where` skips a later payload with the same bytes as one
for payload in payloads { // uploaded earlier in this batch.
for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil {
let outcome = await Micropub.uploadMedia( let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint, mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent, filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
@@ -390,11 +552,26 @@ extension PostsModel {
) )
switch outcome { switch outcome {
case let .url(url): 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): case let .failed(failure):
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece 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): // Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=config` carries `media-endpoint`; // `GET /micropub?q=config` carries `media-endpoint`;
// `POST <media-endpoint>` multipart → 202 + Location = upload URL. // `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 import Foundation
nonisolated extension Micropub { 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 /// The one illustration-ref pattern both passes share (the parse
/// and the rewrite can never drift). The alt class is single-line /// and the rewrite can never drift). The alt class is single-line
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT /// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
+138 -53
View File
@@ -11,6 +11,10 @@
// lives in the Keychain (G11; re-offered only on an auth failure — // lives in the Keychain (G11; re-offered only on an auth failure —
// Settings → Micro.blog is the standing manager). Refusals show // Settings → Micro.blog is the standing manager). Refusals show
// inline with the buttons kept (ApplyAskSheet posture). // 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 import SwiftUI
@@ -21,17 +25,26 @@ struct MicropubPublishSheet: View {
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
private enum Phase: Equatable { private enum Phase: Equatable {
/// Never sent — nothing on Micro.blog yet.
case idle case idle
case drafting case drafting
/// A draft is on Micro.blog, not published (fresh or remembered).
case drafted case drafted
case updating
case updated
case publishing case publishing
/// The publish record — this session's Publish, or the piece's stamp.
case published case published
} }
@State private var phase: Phase = .idle @State private var phase: Phase = .idle
/// The draft URL this sheet knows: fresh from a send, or the piece's /// The post URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (a draft sent in an earlier session). /// remembered `micropub_url` (sent in an earlier session) — a draft's
@State private var draftURL: String? /// 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 previewURL: String?
@State private var refusal: String? @State private var refusal: String?
@State private var tokenField = "" @State private var tokenField = ""
@@ -43,16 +56,22 @@ struct MicropubPublishSheet: View {
reentry || MicropubTokenStore.read() == nil reentry || MicropubTokenStore.read() == nil
} }
private var busy: Bool {
phase == .drafting || phase == .updating || phase == .publishing
}
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 12) { VStack(alignment: .leading, spacing: 12) {
Text("Publish to Micro.blog?") Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
.font(.headline) .font(.headline)
Text(pieceTitle) Text(pieceTitle)
.font(.callout.weight(.semibold)) .font(.callout.weight(.semibold))
.lineLimit(2) .lineLimit(2)
if phase == .idle {
Text("Museion sends it as a draft first — nothing goes out until you publish.") Text("Museion sends it as a draft first — nothing goes out until you publish.")
.font(.callout) .font(.callout)
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
}
if showsTokenField { if showsTokenField {
SecureField("App token", text: $tokenField) SecureField("App token", text: $tokenField)
@@ -69,18 +88,18 @@ struct MicropubPublishSheet: View {
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
} }
if phase == .drafting || phase == .publishing { if busy {
ProgressView() ProgressView()
} }
if let url = statusURL { if let label = statusLabel {
// The draft lives on Micro.blog — the preview link goes // A published piece's link is the post itself; a draft's
// there for review; once published it's the post itself. // is its review page.
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Text(phase == .published ? "Published" : "Draft on Micro.blog") Text(label)
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
if let link = URL(string: phase == .published ? url : (previewURL ?? url)) { if let link = statusLink {
Link(destination: link) { Link(destination: link) {
Text(link.absoluteString) Text(link.absoluteString)
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
@@ -97,24 +116,25 @@ struct MicropubPublishSheet: View {
} }
HStack(spacing: 8) { 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() } Button("Done") { dismiss() }
.buttonStyle(.borderedProminent) .buttonStyle(.borderedProminent)
} else { } else {
Button("Publish") { publish() } Button("Publish") { publish() }
.buttonStyle(.borderedProminent) .buttonStyle(.borderedProminent)
.disabled(draftURL == nil || phase == .drafting || phase == .publishing) .disabled(postURL == nil || busy)
if draftURL != nil { // The piece changed since the draft — a re-send
// The piece changed since the draft — a fresh send // updates that same draft (never a second post).
// replaces it (and the remembered URL). Button(postURL == nil ? "Send as Draft" : "Update Draft") { send() }
Button("Send Again") { sendDraft() }
.buttonStyle(.bordered) .buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing) .disabled(busy)
} else {
Button("Send as Draft") { sendDraft() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
}
Button("Cancel") { dismiss() } Button("Cancel") { dismiss() }
.buttonStyle(.bordered) .buttonStyle(.bordered)
} }
@@ -124,17 +144,18 @@ struct MicropubPublishSheet: View {
.padding(16) .padding(16)
.frame(width: 340, alignment: .leading) .frame(width: 340, alignment: .leading)
.onAppear { .onAppear {
// A draft sent in an earlier session is still publishable: // A piece sent in an earlier session still has its record:
// the piece remembers its URL. // the remembered URL, and (#206) its publish stamp.
if draftURL == nil, let id = posts.session?.postID { guard postURL == nil, let id = posts.session?.postID,
if let remembered = posts.posts.first(where: { $0.id == id })?.micropubURL { let post = posts.posts.first(where: { $0.id == id })
draftURL = remembered 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 /// The open piece's Title (the sheet is only reachable with a piece
/// open; the id is the honest fallback). /// open; the id is the honest fallback).
@@ -142,9 +163,48 @@ struct MicropubPublishSheet: View {
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece" posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
} }
private var statusURL: String? { private var statusLabel: String? {
phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil 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 /// Resolve the token: a freshly entered one is saved ONCE (rotation
/// replaces); otherwise the Keychain's. Nil → the inline ask, never /// replaces); otherwise the Keychain's. Nil → the inline ask, never
@@ -160,29 +220,44 @@ struct MicropubPublishSheet: View {
return saved 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 { guard let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first." refusal = "Paste your Micro.blog app token first."
return return
} }
refusal = nil refusal = nil
phase = .drafting phase = postURL == nil ? .drafting : .updating
Task { Task {
switch await posts.micropubSendDraft(token: token) { switch await posts.micropubSend(token: token) {
case let .drafted(url, preview): case let .drafted(url, preview):
draftURL = url postURL = url
previewURL = preview previewURL = preview
phase = .drafted phase = .drafted
case let .updated(url):
postURL = url
phase = .updated
case let .authFailed(detail): case let .authFailed(detail):
reentry = true // the entered-once token may be wrong fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
refusal = "Micro.blog rejected the token: \(detail)"
phase = draftURL == nil ? .idle : .drafted
case let .refused(reason), let .unreachable(reason): case let .refused(reason), let .unreachable(reason):
refusal = reason fail(reason)
phase = draftURL == nil ? .idle : .drafted
case let .requestFailed(status, detail): case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)" fail("Micro.blog said \(status): \(detail)")
phase = draftURL == nil ? .idle : .drafted case let .forgotten(reason):
forgot(reason)
case .published: case .published:
break break
} }
@@ -190,29 +265,39 @@ struct MicropubPublishSheet: View {
} }
private func publish() { 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." refusal = "Paste your Micro.blog app token first."
return return
} }
refusal = nil refusal = nil
phase = .publishing phase = .publishing
Task { Task {
switch await Micropub.publish(url: url, token: token) { switch await posts.micropubPublish(url: url, token: token) {
case .published: case .published:
publishedAt = Date()
phase = .published phase = .published
case let .authFailed(detail): case let .authFailed(detail):
reentry = true fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
refusal = "Micro.blog rejected the token: \(detail)"
phase = .drafted
case let .refused(reason), let .unreachable(reason): case let .refused(reason), let .unreachable(reason):
refusal = reason fail(reason)
phase = .drafted
case let .requestFailed(status, detail): case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)" fail("Micro.blog said \(status): \(detail)")
phase = .drafted case let .forgotten(reason):
case .drafted: forgot(reason)
case .drafted, .updated:
break 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
}
} }
+42 -11
View File
@@ -24,7 +24,9 @@ import Foundation
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file /// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
/// normalization on save/advance, convert. Replaces any existing block. /// normalization on save/advance, convert. Replaces any existing block.
/// - **merge-import** (`mergingImport`) — an external block kept verbatim /// - **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: /// - **update-keys** (`updating`) — the surgical in-place key stamp:
/// every other line byte-identical (editor save, pass advance, stats /// every other line byte-identical (editor save, pass advance, stats
/// capture, micropub URL, learnings dismiss). /// capture, micropub URL, learnings dismiss).
@@ -33,6 +35,19 @@ import Foundation
/// `origin`) are ONE rule shared by every posture: absent owned keys /// `origin`) are ONE rule shared by every posture: absent owned keys
/// insert before the closing `---` in that order. /// insert before the closing `---` in that order.
nonisolated enum PostFrontmatter { 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` /// The leniently-decoded identity triple — one home for the `?? default`
/// reads scan, the write paths, and the eligibility predicates share /// reads scan, the write paths, and the eligibility predicates share
/// (the extraction the #31 capture's ponytail note deferred until this /// (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 /// order), preserve every other line verbatim (leading hand-edit lines
/// above the opening `---` included, #27 review), keep the block's /// above the opening `---` included, #27 review), keep the block's
/// trailing newline. No block at all → prepend a fresh one with the /// trailing newline. No block at all → prepend a fresh one with the
/// pairs. /// pairs. `dropping` removes those keys' lines outright, first (#206:
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String { /// 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) let (block, body) = split(text)
guard !block.isEmpty else { guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
@@ -159,18 +175,16 @@ nonisolated enum PostFrontmatter {
// the lenient flat reader never claimed nested support (posture // the lenient flat reader never claimed nested support (posture
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk // inherited verbatim, #180 audit INFO-1). Indentation-aware walk
// if nested frontmatter ever matters. // 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 }) let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>() var seen = Set<String>()
for (index, line) in lines.enumerated() { for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r. guard let key = key(ofLine: line), let value = oursByKey[key] else { continue }
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)" lines[index] = "\(key): \(value)"
seen.insert(key) seen.insert(key)
} }
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" } 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 { if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close) lines.insert(contentsOf: insertions, at: close)
@@ -181,13 +195,30 @@ nonisolated enum PostFrontmatter {
/// Posture 2 — merge-import: external frontmatter rides verbatim; /// Posture 2 — merge-import: external frontmatter rides verbatim;
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win /// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports /// (#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: /// #180 divergence from the absorbed mergedFrontmatter, deliberate:
/// hand-edit lines above the opening `---` now survive import (the old /// hand-edit lines above the opening `---` now survive import (the old
/// split-first shape silently dropped them) — lossless through every /// split-first shape silently dropped them) — lossless through every
/// posture is the ticket's contract. /// posture is the ticket's contract.
static func mergingImport(text: String, origin: Post.Origin) -> String { 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 var project: String
/// True when the piece lives under archive/ (#107). /// True when the piece lives under archive/ (#107).
var isArchived: Bool var isArchived: Bool
/// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter /// #33 (S6.1): the remembered Micro.blog post URL (frontmatter
/// `micropub_url`) — set when a draft was sent, the target the /// `micropub_url`) — set when a draft was sent; the target the
/// publish step updates. Inert to everything else. /// 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? 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 /// #32 (S5.2): the captured first-draft stats — present ONLY when
/// `captureFirstDraftStats` stamped the piece at a pass invocation /// `captureFirstDraftStats` stamped the piece at a pass invocation
/// (writer origin, First Draft, post type, decided there against the /// (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. /// keys, and non-writer or outline pieces never render them.
var firstDraftStats: FirstDraftStats? 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). /// New pieces land here when no project is selected (#107).
static let defaultProject = "posts" static let defaultProject = "posts"
@@ -58,7 +75,7 @@ nonisolated struct Post: Identifiable, Equatable {
/// reads "steady" in the verdict (finish-audit #32). /// reads "steady" in the verdict (finish-audit #32).
init?(frontmatter: [String: String]) { init?(frontmatter: [String: String]) {
guard 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 burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite),
let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite), let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite),
let sentenceVariation = frontmatter["stats_sentence_variation"].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 /// Frontmatter is external data (hand-edits, imports): reject the
/// non-finite doubles Swift's `Double(String)` happily parses. /// non-finite doubles Swift's `Double(String)` happily parses.
private static func finite(_ raw: String) -> Double? { private static func finite(_ raw: String) -> Double? {
@@ -189,15 +197,12 @@ nonisolated struct Post: Identifiable, Equatable {
type: stamp.type, type: stamp.type,
project: project, project: project,
isArchived: isArchived, isArchived: isArchived,
// #33: the remembered Micro.blog draft URL — // #33: the remembered Micro.blog URL — one flat key
// one flat key, read leniently like the rest. // through the ONE trust gate (an import drops the key,
// #33 audit: imported frontmatter rides // #206, so a hostile value never pre-arms the publish
// verbatim, so the read-back gates on the same // sheet); #206: the publish stamp beside it.
// format guard the decode applies — a hostile micropubURL: Micropub.rememberedURL(frontmatter),
// value never pre-arms the publish sheet. micropubPublished: frontmatter["micropub_published"].flatMap(parseStamp),
micropubURL: frontmatter["micropub_url"].flatMap {
Micropub.trustworthyURL($0) ? $0 : nil
},
// #32/#180 read-back gate: the named immutable pair // #32/#180 read-back gate: the named immutable pair
// (origin writer, type post) — NOT pass_state, which // (origin writer, type post) — NOT pass_state, which
// legitimately advances after the capture. `stats_*` // 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, /// The Post's Title: first non-empty line after any frontmatter block,
/// `#` heading markers stripped; `untitled` when nothing readable remains. /// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String { 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 /// #22/#94/#95: import one external markdown file as a Post — copy, never
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept /// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
/// verbatim with `type: post`, `pass_state: First Draft` and /// 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, /// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
/// no mtime preservation (#96). /// no mtime preservation (#96).
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post { 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 } guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let stats = DraftStats.compute(body: body) let stats = DraftStats.compute(body: body)
let stamped = PostFrontmatter.updating(text: text, with: [ 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_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)), ("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)), ("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
@@ -675,22 +677,35 @@ nonisolated extension PostStore {
return true 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 /// Stamp micropub keys in place (`micropub_url`, the publish record
/// publish step's target (a frontmatter-only change: the body and /// `micropub_published`) — a frontmatter-only change: the body and
/// every other key stay byte-identical, so the open session's /// every other key stay byte-identical, so the open session's
/// readBody-based echo check never fires). A vanished piece throws /// readBody-based echo check never fires, and every later editor
/// (write-never-resurrects, `writeNew` is the only creator). /// save re-reads the block (the stamps survive it). A vanished piece
static func stampMicropubURL(id: String, url: String, home: URL) throws { /// 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 { guard let dir = folder(of: id, home: home) else {
throw CocoaError(.fileReadNoSuchFile) throw CocoaError(.fileReadNoSuchFile)
} }
let file = dir.appendingPathComponent("post.md") let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8) 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) .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) // MARK: Cursor-state sidecar (#66)
+1
View File
@@ -219,6 +219,7 @@ struct PostsLibraryColumn: View {
model.archivePost(post) model.archivePost(post)
} }
Divider() Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: post) FinderHandOffButtons(model: model, post: post)
Button("Move to Trash", role: .destructive) { Button("Move to Trash", role: .destructive) {
model.trash(post) model.trash(post)
+18 -1
View File
@@ -5,7 +5,7 @@
// #193: the shared workspace chrome, moved from WorkspaceView.swift // #193: the shared workspace chrome, moved from WorkspaceView.swift
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle, // (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
// PaneHeader; every pane reuses them, code unchanged. #205 adds // PaneHeader; every pane reuses them, code unchanged. #205 adds
// FinderHandOffButtons (born here). // FinderHandOffButtons, #206 MicroblogHandOffButton (both born here).
// //
import AppKit 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)
}
}
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts. - `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded. - `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded.
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap). - `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface. - `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests` — publish wire contract, model flow, media/illustration surface; #206 `MicropubStatusTests` — the publish record (the stamp, the link heal when the send's stamp could not land, the row label; an imported file brings NO Micro.blog memory; publish refuses an unclean URL), the in-place re-send, the upload memo (unchanged bytes ride, a changed one re-uploads, an untrustworthy or symlinked memo is no memory), the 404 forget (a clear that cannot land refuses). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared. Recorded requests are read through `MicropubRequestLog.request(_:)`, never `requests[index]` — a short log fails its own pin instead of trapping the runner.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay. - `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does). - `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load). - `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
+22 -37
View File
@@ -23,7 +23,7 @@ struct MicropubModelTests {
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft( let outcome = await model.micropubSend(
token: "tok", token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log), transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
) )
@@ -42,7 +42,7 @@ struct MicropubModelTests {
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws { @Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
let (model, _) = try makeModelHome() let (model, _) = try makeModelHome()
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft( let outcome = await model.micropubSend(
token: "tok", token: "tok",
transport: micropubCanned(201, body: "{}", log: log), transport: micropubCanned(201, body: "{}", log: log),
) )
@@ -57,7 +57,7 @@ struct MicropubModelTests {
let (model, _) = try makeModelHome() let (model, _) = try makeModelHome()
model.newPost() // staged draft — no folder, no session model.newPost() // staged draft — no folder, no session
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft( let outcome = await model.micropubSend(
token: "tok", token: "tok",
transport: micropubCanned(201, body: "{}", log: log), transport: micropubCanned(201, body: "{}", log: log),
) )
@@ -76,7 +76,7 @@ struct MicropubModelTests {
model.select(post.id) model.select(post.id)
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft( let outcome = await model.micropubSend(
token: "tok", token: "tok",
transport: micropubCanned(201, body: "{}", log: log), transport: micropubCanned(201, body: "{}", log: log),
) )
@@ -99,7 +99,7 @@ struct MicropubModelTests {
.write(to: fileURL, atomically: true, encoding: .utf8) .write(to: fileURL, atomically: true, encoding: .utf8)
let log = MicropubRequestLog() let log = MicropubRequestLog()
_ = await model.micropubSendDraft( _ = await model.micropubSend(
token: "tok", token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log), transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
) )
@@ -116,7 +116,7 @@ struct MicropubModelTests {
model.select(post.id) model.select(post.id)
let log = MicropubRequestLog() let log = MicropubRequestLog()
_ = await model.micropubSendDraft( _ = await model.micropubSend(
token: "tok", token: "tok",
transport: micropubCanned(500, body: "{}", log: log), transport: micropubCanned(500, body: "{}", log: log),
) )
@@ -124,28 +124,11 @@ struct MicropubModelTests {
#expect(Post.scan(home: home).first?.micropubURL == nil) #expect(Post.scan(home: home).first?.micropubURL == nil)
} }
@Test @MainActor func `re-drafting overwrites the remembered url`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log),
)
_ = await model.micropubSendDraft(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log),
)
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second")
}
// MARK: #34 (S6.2) — illustrations travel with it // MARK: #34 (S6.2) — illustrations travel with it
/// Plants a PNG beside the piece; returns the piece's post.md URL. /// Plants a PNG beside the piece; returns the piece's post.md URL.
@MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL { /// Shared with `MicropubStatusTests` (shared-helper convention).
@MainActor func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
let post = try PostStore.writeNew(body: body, home: home) let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id) model.select(post.id)
let dir = try #require(PostStore.folder(of: post.id, home: home)) let dir = try #require(PostStore.folder(of: post.id, home: home))
@@ -162,20 +145,21 @@ struct MicropubModelTests {
) )
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil)) #expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// The three hops, in order: q=config → upload → create. // The three hops, in order: q=config → upload → create.
#expect(log.requests.count == 3) #expect(log.requests.count == 3)
let config = URLComponents(url: log.requests[0].url ?? Micropub.endpoint, resolvingAgainstBaseURL: false) let config = URLComponents(url: log.request(0)?.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
#expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true) #expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
#expect(log.requests[1].url?.absoluteString == "https://micro.blog/micropub/media") #expect(log.request(1)?.url?.absoluteString == "https://micro.blog/micropub/media")
#expect(log.requests[1].httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart #expect(log.request(1)?.httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
// The create: the ref REWRITTEN in place with its uploaded URL // The create: the ref REWRITTEN in place with its uploaded URL
// — exactly where the writer placed it (2026-11-01: the photo // — exactly where the writer placed it (2026-11-01: the photo
// PROPERTY rendered at the bottom, position lost), alt in the // PROPERTY rendered at the bottom, position lost), alt in the
// markdown, NO photo property keys. // markdown, NO photo property keys.
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any]) let create = try #require(log.request(2))
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
let expected = "# Inked\n\nProse before.\n\n![A winding path.](https://micro.blog/uploads/2026/ink.png)\n\nProse after." let expected = "# Inked\n\nProse before.\n\n![A winding path.](https://micro.blog/uploads/2026/ink.png)\n\nProse after."
#expect(props["content"] as? [String] == [expected]) #expect(props["content"] as? [String] == [expected])
#expect(props["photo"] == nil) #expect(props["photo"] == nil)
@@ -197,7 +181,7 @@ struct MicropubModelTests {
) )
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else { guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)") Issue.record("expected refused, got \(outcome)")
@@ -228,7 +212,7 @@ struct MicropubModelTests {
) )
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else { guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)") Issue.record("expected refused, got \(outcome)")
@@ -246,13 +230,14 @@ struct MicropubModelTests {
) )
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil)) #expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// config + ONE upload + create — the FILE uploads once, not once per ref. // config + ONE upload + create — the FILE uploads once, not once per ref.
#expect(log.requests.count == 3) #expect(log.requests.count == 3)
#expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1) #expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1)
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any]) let create = try #require(log.request(2))
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
let content = try #require((props["content"] as? [String])?.first) let content = try #require((props["content"] as? [String])?.first)
// Both refs share the one uploaded URL. // Both refs share the one uploaded URL.
#expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3) #expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3)
@@ -266,7 +251,7 @@ struct MicropubModelTests {
) // path.png planted, ghost.png never ) // path.png planted, ghost.png never
let log = MicropubRequestLog() let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
guard case .refused = outcome else { guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)") Issue.record("expected refused, got \(outcome)")
@@ -281,10 +266,10 @@ struct MicropubModelTests {
model.select(post.id) model.select(post.id)
let log = MicropubRequestLog() let log = MicropubRequestLog()
_ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
// The #33 path unchanged: no config round-trip, straight to the create. // The #33 path unchanged: no config round-trip, straight to the create.
#expect(log.requests.count == 1) #expect(log.requests.count == 1)
#expect(log.requests[0].url == Micropub.endpoint) #expect(log.request(0)?.url == Micropub.endpoint)
} }
} }
+423
View File
@@ -0,0 +1,423 @@
//
// MicropubStatusTests.swift
// MuseionTests
//
// #206: the Micro.blog publish record. Scenario:
//
// Given a saved Post the writer sent to Micro.blog (the piece
// remembers its post URL)
// When the writer publishes it, sends it again, or Micro.blog has
// lost the post
// Then the piece remembers the publish (frontmatter
// `micropub_published`, healing a link the send could not stamp)
// and the library row can say
// "published <date>"; a re-send UPDATES the remembered post in
// place — same URL, no second post, no second upload for an
// unchanged image — and leaves the publish date alone; a 404 (the
// post deleted on Micro.blog) clears the link so the piece can go
// out as a fresh draft. Nothing is stamped on any failure, and a forget that
// cannot land says so — never a "cleared" the disk contradicts.
//
// Wire facts (microblog.dev/api/posting, 2026-12-04):
// `action=update` with `replace` sets name and content; updates
// answer 200 with an empty body and 404 when `url` is not on the
// blog. The media listing carries no content hash, so upload dedup
// is a local memo keyed by the asset's bytes.
//
// A file from outside brings none of this: the import boundary drops
// Museion's micropub keys, so a foreign `micropub_url` can never aim
// a send at one of the writer's posts.
//
import Foundation
@testable import Museion
import Testing
@Suite("MicropubStatusTests")
struct MicropubStatusTests {
/// A fresh piece with extra frontmatter lines planted after the
/// owned keys; returns its id.
private func piece(_ home: URL, frontmatter: String = "") throws -> String {
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
if !frontmatter.isEmpty {
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
let raw = try String(contentsOf: fileURL, encoding: .utf8)
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
.write(to: fileURL, atomically: true, encoding: .utf8)
}
return post.id
}
// MARK: The record on disk
@Test func `row status reads nil draft or published from the frontmatter`() throws {
let home = try storeHome()
defer { try? FileManager.default.removeItem(at: home) }
let live = try piece(
home,
frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2026-12-04T15:02:00\n",
)
let draft = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/draft\n")
let untouched = try piece(home)
// A stamp that isn't the stamp shape never reads as a publish.
let broken = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/broken\nmicropub_published: yesterday\n")
let posts = Post.scan(home: home)
#expect(posts.first { $0.id == live }?.micropubStatus == "published Dec 4, 2026")
#expect(posts.first { $0.id == draft }?.micropubStatus == "draft on Micro.blog")
#expect(posts.first { $0.id == untouched }?.micropubStatus == nil)
#expect(posts.first { $0.id == broken }?.micropubStatus == "draft on Micro.blog")
}
@Test func `an imported piece brings no micro.blog memory`() throws {
let home = try storeHome()
defer { try? FileManager.default.removeItem(at: home) }
let source = home.appendingPathComponent("guest.md")
try """
---
title: Guest
micropub_url: https://example.micro.blog/someone-elses-live-post
micropub_published: 2026-01-01T00:00:00
---
# Guest
Body.
""".write(to: source, atomically: true, encoding: .utf8)
// A foreign file's remembered URL would aim the next send's
// content replace at whatever post it names, under the writer's
// token — so Museion's bookkeeping is ours to set, never theirs
// to carry in (the way a foreign `origin` loses).
let post = try PostStore.importFile(at: source, origin: .writer, home: home)
let scanned = try #require(Post.scan(home: home).first { $0.id == post.id })
#expect(scanned.micropubURL == nil)
#expect(scanned.micropubPublished == nil)
#expect(scanned.micropubStatus == nil)
let matter = try PostFrontmatter.parse(readPost(home, post.id))
#expect(matter["title"] == "Guest") // every other external key still rides verbatim
#expect(matter["micropub_url"] == nil) // the line is gone, not merely emptied
}
@Test @MainActor func `publish remembers the date on the piece`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Stamped\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/stamped"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
#expect(Post.scan(home: home).first?.micropubPublished == nil) // a draft is not a publish
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
#expect(outcome == .published)
let scanned = try #require(Post.scan(home: home).first)
let published = try #require(scanned.micropubPublished)
#expect(abs(published.timeIntervalSinceNow) < 60) // stamped now, local time
#expect(scanned.micropubURL == url)
#expect(scanned.micropubStatus?.hasPrefix("published ") == true)
}
@Test @MainActor func `publish remembers a post whose send could not stamp it`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Unstamped\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/unstamped"
// The send lands, but its stamp cannot: the piece folder is
// read-only for the moment (the sheet still holds the URL for
// this session; the piece remembers nothing on disk).
let dir = try #require(PostStore.folder(of: post.id, home: home))
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
let sent = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
#expect(sent == .drafted(url: url, preview: nil))
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
#expect(Post.scan(home: home).first?.micropubURL == nil)
// Publish writes the record AND heals the link the send couldn't.
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.micropubURL == url)
#expect(scanned.micropubPublished != nil)
}
@Test @MainActor func `a failed publish stamps nothing`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Refused\n\nBody.", home: home)
model.select(post.id)
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/refused",
token: "tok",
transport: micropubCanned(500, log: MicropubRequestLog()),
)
guard case let .requestFailed(status, _) = outcome else {
Issue.record("expected requestFailed, got \(outcome)")
return
}
#expect(status == 500)
#expect(Post.scan(home: home).first?.micropubPublished == nil)
}
@Test @MainActor func `publish refuses a post address that is not a clean url`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Injected\n\nBody.", home: home)
model.select(post.id)
let log = MicropubRequestLog()
// A newline in the address would close the frontmatter block on
// the heal write — so nothing travels and nothing is remembered.
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/live\nmicropub_published: 2020-01-01T00:00:00",
token: "tok",
transport: micropubCanned(200, log: log),
)
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.micropubURL == nil)
#expect(scanned.micropubPublished == nil)
}
// MARK: A re-send updates the remembered post in place
@Test func `update request is the in-place replace against the remembered url`() {
let request = Micropub.makeUpdateRequest(
url: "https://example.micro.blog/hello.html",
title: "The Title",
body: "The body.",
token: "tok",
)
#expect(request.url == Micropub.endpoint)
#expect(request.httpMethod == "POST")
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
let root = micropubJSON(request)
#expect(root["action"] as? String == "update")
#expect(root["url"] as? String == "https://example.micro.blog/hello.html")
let replace = root["replace"] as? [String: Any]
#expect(replace?["name"] as? [String] == ["The Title"])
#expect(replace?["content"] as? [String] == ["The body."])
// Never a status flip — a draft stays a draft, a live post stays live.
#expect(replace?["post-status"] == nil)
}
@Test @MainActor func `a re-send updates the remembered post and never creates a second`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Again\n\nFirst body.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/again"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
model.session?.edit("# Again\n\nSecond body.")
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
#expect(outcome == .updated(url: url))
let request = try #require(log.requests.first)
let root = micropubJSON(request)
#expect(root["action"] as? String == "update") // the create's `type`/`properties` never ride
#expect(root["type"] == nil)
#expect(root["url"] as? String == url)
let replace = try #require(root["replace"] as? [String: Any])
#expect(replace["content"] as? [String] == ["# Again\n\nSecond body."])
#expect(Post.scan(home: home).first?.micropubURL == url) // the remembered URL never moves
}
@Test @MainActor func `a live update leaves the publish date alone`() async throws {
let (model, home) = try makeModelHome()
let live = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2025-01-15T08:00:00\n")
model.select(live)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
#expect(outcome == .updated(url: "https://example.micro.blog/live"))
#expect(Post.scan(home: home).first?.micropubStatus == "published Jan 15, 2025")
}
// MARK: A re-send never re-uploads an unchanged image
/// An illustrated piece, opened in the model; returns its folder
/// (`MicropubModelTests` owns the planting — shared-helper convention).
@MainActor private func illustratedPiece(_ model: PostsModel, _ home: URL) throws -> URL {
try MicropubModelTests()
.plantIllustratedPiece(model, home, body: "# Inked\n\n![A winding path.](assets/path.png)\n\nProse.")
.deletingLastPathComponent()
}
@Test @MainActor func `an unchanged illustration rides its earlier upload`() async throws {
let (model, home) = try makeModelHome()
_ = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // config + upload + create
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
// ONE request — the in-place update. No q=config, no upload.
#expect(outcome == .updated(url: "https://example.micro.blog/inked"))
#expect(log.requests.count == 1)
let resent = try #require(log.request(0))
let replace = try #require(micropubJSON(resent)["replace"] as? [String: Any])
#expect((replace["content"] as? [String])?.first?.contains("![A winding path.](https://micro.blog/uploads/2026/ink.png)") == true)
}
@Test @MainActor func `a changed illustration uploads again`() async throws {
let (model, home) = try makeModelHome()
let dir = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
// The writer replaces the image — same name, new bytes.
let fresh = micropubPNG() + Data([0x7F])
try fresh.write(to: dir.appendingPathComponent("assets/path.png"))
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
// config → upload → update, and the upload carries the NEW bytes.
#expect(log.requests.count == 3)
#expect(log.request(1)?.httpBody?.firstRange(of: fresh) != nil)
}
@Test @MainActor func `an untrustworthy memo url never rides the wire`() async throws {
let (model, home) = try makeModelHome()
let dir = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
// The sidecar is disk, so external data: a planted http URL is
// no memory at all.
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
var memo = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: memoURL))
let key = try #require(memo.keys.first)
memo[key] = "http://evil.example/swap.png"
try JSONEncoder().encode(memo).write(to: memoURL, options: .atomic)
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(log.requests.count == 3) // re-uploaded rather than trusted
let last = try #require(log.request(2))
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
let content = try #require((replace["content"] as? [String])?.first)
#expect(!content.contains("evil.example"))
#expect(content.contains("https://micro.blog/uploads/2026/ink.png"))
}
@Test @MainActor func `a symlinked upload memo is no memory at all`() async throws {
let (model, home) = try makeModelHome()
let dir = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // the real memo lands
// Planted: the sidecar becomes a link to a memo OUTSIDE the piece
// that names this image's bytes with an attacker-chosen URL.
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
try FileManager.default.removeItem(at: memoURL)
let outside = home.appendingPathComponent("planted-memo.json")
let planted = [Micropub.uploadKey(micropubPNG()): "https://micro.blog/uploads/2026/planted.png"]
try JSONEncoder().encode(planted).write(to: outside, options: .atomic)
try FileManager.default.createSymbolicLink(at: memoURL, withDestinationURL: outside)
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(log.requests.count == 3) // config → a fresh upload → the update
let last = try #require(log.request(2))
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
let content = try #require((replace["content"] as? [String])?.first)
#expect(!content.contains("planted.png"))
}
// MARK: A post Micro.blog lost
@Test @MainActor func `a post micro.blog lost is forgotten named and sendable again`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Gone\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/gone"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
// The writer deleted the draft on Micro.blog; the next send hears 404.
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
guard case let .forgotten(reason) = outcome else {
Issue.record("expected forgotten, got \(outcome)")
return
}
#expect(reason.contains("deleted"))
let forgotten = try #require(Post.scan(home: home).first)
#expect(forgotten.micropubURL == nil) // no dead link left on the piece
#expect(forgotten.micropubStatus == nil)
// Recovery: with nothing remembered, the next send is a fresh draft.
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: log))
let created = try #require(log.request(0))
#expect(micropubJSON(created)["action"] == nil) // a create, not an update
#expect(Post.scan(home: home).first?.micropubURL == url)
}
@Test @MainActor func `a lost live post takes the publish record with it`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Vanish\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/vanish"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
#expect(Post.scan(home: home).first?.micropubPublished != nil) // the record exists
// The post is deleted on Micro.blog; the next word there is 404.
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
guard case .forgotten = outcome else {
Issue.record("expected forgotten, got \(outcome)")
return
}
#expect(Post.scan(home: home).first?.micropubURL == nil)
#expect(Post.scan(home: home).first?.micropubPublished == nil)
}
@Test @MainActor func `publish refuses a piece that is not the open one`() async throws {
let (model, home) = try makeModelHome()
_ = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never selected
let log = MicropubRequestLog()
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/unopened",
token: "tok",
transport: micropubCanned(200, log: log),
)
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty) // nothing went out
#expect(Post.scan(home: home).first?.micropubPublished == nil) // and nothing was remembered for it
}
@Test @MainActor func `a forget that cannot write says so instead of claiming the link is cleared`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Stuck\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/stuck"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
// The piece folder goes read-only: the forget cannot land.
let dir = try #require(PostStore.folder(of: post.id, home: home))
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(reason.contains("couldn't be cleared"))
#expect(Post.scan(home: home).first?.micropubURL == url) // still on the piece — and said to be
}
}
+16 -4
View File
@@ -43,6 +43,18 @@ final class MicropubRequestLog: @unchecked Sendable {
defer { lock.unlock() } defer { lock.unlock() }
return items return items
} }
/// The request at `index`, nil when fewer traveled. Read recorded
/// requests through here, never `requests[index]`: an out-of-range
/// subscript TRAPS, one trap kills the hosted runner, and every
/// queued test reports `Crash:` beside it (#206 flip cycle). A nil
/// here fails the pin's OWN expectation — `#require` it when the
/// value feeds a non-optional parameter.
func request(_ index: Int) -> URLRequest? {
lock.lock()
defer { lock.unlock() }
return index < items.count ? items[index] : nil
}
} }
nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse { nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse {
@@ -266,7 +278,7 @@ struct MicropubTests {
// MARK: The stamp + scan (the remembered draft URL) // MARK: The stamp + scan (the remembered draft URL)
@Test func `stampMicropubURL stamps in place and scan reads it back`() throws { @Test func `stampMicropub stamps in place and scan reads it back`() throws {
let home = FileManager.default.temporaryDirectory let home = FileManager.default.temporaryDirectory
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true) .appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
@@ -292,7 +304,7 @@ struct MicropubTests {
].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8) ].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8)
let before = try String(contentsOf: fileURL, encoding: .utf8) let before = try String(contentsOf: fileURL, encoding: .utf8)
try PostStore.stampMicropubURL(id: post.id, url: "https://example.micro.blog/hello.html", home: home) try PostStore.stampMicropub(post.id, home: home, [("micropub_url", "https://example.micro.blog/hello.html")])
let after = try String(contentsOf: fileURL, encoding: .utf8) let after = try String(contentsOf: fileURL, encoding: .utf8)
#expect(after.contains("micropub_url: https://example.micro.blog/hello.html")) #expect(after.contains("micropub_url: https://example.micro.blog/hello.html"))
@@ -305,11 +317,11 @@ struct MicropubTests {
#expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else #expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else
} }
@Test func `stampMicropubURL throws on a vanished piece`() throws { @Test func `stampMicropub throws on a vanished piece`() throws {
let home = FileManager.default.temporaryDirectory let home = FileManager.default.temporaryDirectory
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true) .appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
#expect(throws: (any Error).self) { #expect(throws: (any Error).self) {
try PostStore.stampMicropubURL(id: "ghost", url: "https://x.example/", home: home) try PostStore.stampMicropub("ghost", home: home, [("micropub_url", "https://x.example/")])
} }
} }
+1 -1
View File
@@ -49,7 +49,7 @@ Running a pass on an unaided first draft captures four style metrics — burstin
### Publishing ### Publishing
**[Micro.blog](https://micro.blog) via Micropub:** Publish ▸ **Send as Draft** ▸ review on Micro.blog ▸ **Publish**. The app token lives in your login keychain. Illustrations upload first and ride inline where you placed them; a picture without alt text never ships. The piece on disk never changes. **[Micro.blog](https://micro.blog) via Micropub:** Publish ▸ **Send as Draft** ▸ review on Micro.blog ▸ **Publish**. The app token lives in your login keychain. Illustrations upload first and ride inline where you placed them; a picture without alt text never ships. The piece on disk never changes. The library row shows where each piece stands — `draft on Micro.blog` or `published <date>` — and its menu opens the live post. Sending again updates the same post in place (never a second post) and reuses images that haven't changed.
### Rails ### Rails
@@ -0,0 +1,89 @@
# Micro.blog: the publish is remembered and shown (#206)
> **Date:** 2026-12-04
> **Type:** issue
> **Reference:** [#206 — Display Micro.blog published status](https://git.babylondreams.de/AlexKucera/museion/issues/206) ("Right now it is unclear when a post was published.")
## Goal
Make the library say where each piece stands on Micro.blog. The publish sheet flipped a draft live and remembered nothing, so nothing on disk ever said a piece was out — the row could not show it, and sending a piece again created a second post.
## What Was Done
- Grilling first (13 questions, every one owner-answered in session). The agreed design, built as one cohesive slice: a local publish record, the row label, the in-place re-send, the upload memo, a model-owned Publish, 404 recovery, the sheet's three open-states, the row-menu item.
- `PostLibrary.swift` — `Post.micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape) and the pure row label `micropubStatus` (`published <MMM d, yyyy>` / `draft on Micro.blog` / nil). `parseStamp` now serves both stamps; `Micropub.rememberedURL` moved to the client as the one trust-gate read.
- `Micropub.swift` — `Outcome.updated(url:)` and `.forgotten(String)`; `jsonPost` (the one JSON request builder); `makeUpdateRequest` + `Micropub.update` (`action=update` + `replace` name/content against the remembered URL — never a status flip, so Micro.blog-side categories stay untouched); `micropubSend` (was `micropubSendDraft`: no remembered URL → create + stamp `micropub_url`; a remembered one → the in-place update; a 404 → the piece forgets); `micropubPublish` (model-owned now: trust-gates its URL, flips the status, stamps the publish record, and heals `micropub_url` in the same write should the send's stamp have failed); `micropubPostGone` (a clear that cannot land refuses with the by-hand instruction); the illustration rail split into `uploadIllustrations` (floor + pre-flight) and `uploadRemembered` (memo-aware upload).
- `MicropubMedia.swift` — the upload memo: `.museion-uploads.json` in the piece folder maps `sha256(bytes)` → uploaded URL. Read back through the trust gate; a symlinked memo never reads; written as each upload lands.
- `PostFrontmatter.swift` — `stampFormat` (the one home for the stamp shape); `micropubKeys`; `updating(dropping:)` removes named keys' lines; `mergingImport` drops the micropub keys.
- `PostStore.swift` — `stampMicropub(_:home:_:dropping:)` (was `stampMicropubURL`); `forgetMicropub` throws, and removes both lines rather than emptying them.
- UI — `LibraryPostRow`: the mono-11 micro-label shows the status in origin's place on a sent piece (VoiceOver reads both; origin stays in the tooltip). `WorkspaceChrome`: `MicroblogHandOffButton` (Open on Micro.blog, published pieces only) mounted in the library and Archive menus. `MicropubPublishSheet` rewritten around the piece's record: Send as Draft → Publish / Update Draft / Update Live Post (status line + the live link).
- Tests — new `MicropubStatusTests` (17 pins); `MicropubTests`/`MicropubModelTests` follow the renames; the old "re-drafting overwrites the url" pin is retired (its premise is void under the in-place design); `MicropubRequestLog.request(_:)` replaces 11 index-after-count subscripts (4 new, 7 pre-existing).
- Owner sign-off in session: origin hidden on sent rows; drafts get no link and no menu item (he tested it — a draft's URL answers "Not Found" until published); the stamp is Museion's publish-click time in local time. His one legacy published post was hand-stamped from the blog's feed (`micropub_published: 2026-12-04T14:08:11` — one frontmatter line, +40 bytes, nothing sent to Micro.blog).
- Reviews — two-axis during the build (standards + spec: 0 hard violations, 7 of 8 judgement calls fixed, 1 rejected), then finish-audit (ponytail + security + general; see Decisions).
- DOX: `CHANGELOG.md` `[Unreleased]`, the README publishing paragraph, root `AGENTS.md` (three learnings), `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`.
**Verification (finish-up gates, each decided by its own exit code):** `swiftformat --lint .` — 0/154 files require formatting, exit 0. `swiftlint lint --strict --quiet` — 0 violations, exit 0. `./scripts/full-test.sh` — **752 executed / 752 passed / 0 failed** (run dir `_build/full-test/20261204T163814Z-Museion`; 736 at session start → +17 new pins, −1 retired).
**Flip cycle:** six assert-anchored batches on the uncommitted tree (pristine copies + `cmp` on restore, byte-exact every time). All 17 new pins were watched fail — each on its own guard, nothing else red except where predicted: update branch, publish stamp, publish identity guard, row label (10 red — the update branch's flip also reddens the three pins whose third request becomes a create); memo lookup + both 404 sites (4); memo trust gate + the honest-forget catch (2); the link heal (1); import drop + publish URL gate + memo symlink guard (3); stamp-on-failure + the update request's literal + the bytes-keyed memo (4 — the literal's flip also reddens the re-send pin that asserts the same `action`).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| The publish is a local frontmatter stamp (`micropub_published`, local time), not a live query | The ticket asks what the writer published from here. A live status query needs a token on every list render and still cannot say "from this machine". Owner-approved, including that the date is Museion's publish-click time. |
| The row's micro-label shows the status in origin's place on a sent piece | 178pt of row content cannot hold both. Origin stays in the accessibility label and the tooltip. Owner-approved. |
| A re-send updates the remembered post in place (`action=update` + `replace` name/content) | Before: a second post every time. `replace` names only those two properties, so categories and everything else set on Micro.blog survive (the owner's explicit worry). |
| Publish stays a status flip and becomes model-owned | No content travels on publish. The sheet used to call the client directly, which is exactly why nothing was ever remembered. |
| An unchanged image rides its earlier upload via a per-piece memo keyed by `sha256(bytes)` | Micro.blog's media listing carries no content hash to match against, so the memory has to be local. Ceilings are ponytail comments: no liveness probe (a deleted upload stays memoized), memo URLs pass the format gate only (blogs use custom domains). |
| A 404 means the post is gone there: the piece forgets both keys, and a clear that cannot land refuses | Before: the piece failed forever against a dead URL. Emptying the keys left a dangling `micropub_published:` line — the lines are removed instead. A swallowed write must not be reported as "cleared". |
| Drafts show no link and no Open on Micro.blog item | Owner-verified: a draft's final URL answers "Not Found" until the post is published. |
| No typed status enum | Two consumers (row, sheet) of a computed label. Rejected as speculative by the standards review. |
| **The import boundary drops `micropub_url` and `micropub_published`** | Finish-audit security finding. An imported `micropub_url` passes the format gate, and since the in-place update it would aim a content replace — under the writer's token — at any post on their blog; a crafted guest post would open the sheet reading "Published" with one **Update Live Post** button. These keys are Museion's bookkeeping, so they are treated like `origin`: ours to set, never a foreign file's to carry in. One codec parameter (`updating(dropping:)`) serves the import and the forget. Side effect: re-importing one's own exported piece loses the link (next send = a new draft); moving the library is a Home repoint, not an import. |
| `micropubPublish` trust-gates its URL before anything travels | Security and general reviewers converged. Every current caller passes a gated value, but the URL lands in frontmatter on the heal, and the repo's rule is to gate at the sink. |
| Pins read recorded requests through `MicropubRequestLog.request(_:)` | An out-of-range subscript traps the hosted runner (first Gotcha). A nil from the accessor fails the pin's own expectation. |
| Ponytail cuts accepted | `statusHome()` duplicated the shared `storeHome()`; `illustratedPiece` duplicated `plantIllustratedPiece` line for line; `Micropub.update`'s empty-URL guard was unreachable (its only caller passes the trust gate's output). |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| A flip run reported 9 failures with no assertion text anywhere | The test host had trapped: `log.requests[2]` after a failed `#expect(log.requests.count == 3)`. An out-of-range subscript kills the hosted runner, and every queued test reports `Crash:` beside it (the crash report: `Array._checkSubscript` under `Runner._applyScopingTraits`). A real regression of the memo gate would have turned one red pin into nine | `MicropubRequestLog.request(_:)` at all 11 sites, `#require` where the value feeds a non-optional parameter. Read `summary.json` `testFailures` for a shared `Crash:` signature before reading a red count as a verdict. |
| `micropubStatus` compiled in the app but read "no member" from a fresh test file | Spelling drift between targets (`microblogStatus` in the test), not a stale binary | Grep the exact name across app AND tests before hunting binaries. |
| The patch tool re-indented `ArchivePaneView`'s closing braces | A replaced region that starts on a closing-brace run is re-indented to the anchor's scope | Restored from HEAD by a scripted splice; recorded as the code-editing skill's rule 9. |
| A scripted flip's anchor missed twice (count 0) | I typed the `do`/`try`/`catch` lines one tab short of the file | The assert fired before anything flipped. Anchors are now written from `repr()` of the real bytes. |
| swiftformat reflowed the multi-line `updating(...)` call after the edits | A formatter pass between edit and flip | Read anchors back after formatting; file-mutating tools run before the suite, never after. |
| The terminal's grep wrapper returned 0 matches for a parenthesised pattern that exists in the file | The wrapper's regex dialect | `search_files` for source reads; the terminal only for build logs. |
| The xcresult summary's `passedTests` reads total + 1 on green runs | Pre-existing rail quirk | Counts come from the rail's own line, never from the summary's passed figure. |
| "Update Live Post" on a stamp with no remembered link would have created a second post (audit) | The sheet branched on the stamp alone | The button reads "Send as Draft" when nothing is remembered — there is no post to update. |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/Micropub.swift` | Update request + client step; `micropubSend` (create-or-update, 404 forget), model-owned `micropubPublish` with the URL gate, `micropubPostGone`, the memo-aware upload rail, `rememberedURL`, `shortDate` |
| `Museion/MicropubMedia.swift` | The upload memo: key, trust-gated read, symlink refusal, atomic write |
| `Museion/MicropubPublishSheet.swift` | Opens on the piece's record; the three open-states; honest button labels |
| `Museion/PostLibrary.swift` | `micropubPublished`, `micropubStatus`, the shared `parseStamp` |
| `Museion/PostFrontmatter.swift` | `stampFormat`, `micropubKeys`, `updating(dropping:)`, import drops the micropub keys |
| `Museion/PostStore.swift` | `stampMicropub(dropping:)`, `forgetMicropub` throws and removes the lines |
| `Museion/LibraryPostRow.swift` | Status in the micro-label, composite accessibility label, origin tooltip |
| `Museion/WorkspaceChrome.swift` | `MicroblogHandOffButton` |
| `Museion/PostsLibraryColumn.swift`, `Museion/ArchivePaneView.swift` | Mount the menu item |
| `MuseionTests/MicropubStatusTests.swift` | New — 17 pins: the record, the heal, the import drop, the URL gate, the in-place re-send, the memo, the 404 forget |
| `MuseionTests/MicropubTests.swift` | `MicropubRequestLog.request(_:)`; renames |
| `MuseionTests/MicropubModelTests.swift` | Renames; safe request reads; `plantIllustratedPiece` shared |
| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass: contracts, suite map, three learnings |
| `CHANGELOG.md`, `README.md` | The feature, the import rule, the by-hand legacy key |
| `docs/devlog/` | This log; `INDEX.md` row; the `AGENTS.md` window |
## Open Items & Next Steps
- [ ] Owner to confirm the audit default: Import drops a file's Micro.blog memory (re-importing one's own exported piece loses the link; the next send creates a new draft).
- [ ] Ticket candidate: the `preview` URL from Micro.blog feeds a `Link` without the URL gate — the same posture at HEAD, outside this diff.
- [ ] Ticket candidate: Convert to Post rebuilds the frontmatter block and drops every foreign key, the micropub memory included (#114 posture; reachable only for a sent outline).
- [ ] Named ceiling, no action: a TLS-intercepting proxy answering 404 would clear a live post's record.
- [ ] Pieces published before this build read as drafts until Publish is clicked once (or the key is added by hand — one was).
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index --> <!-- write-log: full-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 2026-12-04 | issue | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) | Micro.blog publish is remembered and shown: row status, in-place re-send, upload memo, 404 forget; Import drops micropub keys (rail 752/752) |
| 2026-12-04 | generic | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) | Micro.blog publish: a 5xx names their outage instead of `HTTP 503`, and the app token gains a Settings page (rail 736/736) | | 2026-12-04 | generic | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) | Micro.blog publish: a 5xx names their outage instead of `HTTP 503`, and the app token gains a Settings page (rail 736/736) |
| 2026-12-03 | issue | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) | Reveal in Finder / Copy Path on library and Archive rows: one shared menu fragment over the model-resolved post.md path, three pins, rail 735/735 | | 2026-12-03 | issue | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) | Reveal in Finder / Copy Path on library and Archive rows: one shared menu fragment over the model-resolved post.md path, three pins, rail 735/735 |
| 2026-12-03 | issue | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) | Fix Cards gain Jump: the anchor span selected in the editor, the main window keyed, over the #71 caret rail | | 2026-12-03 | issue | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) | Fix Cards gain Jump: the anchor span selected in the editor, the main window keyed, over the #71 caret rail |