feat(microblog): set and create categories

A piece's `category:` frontmatter line now travels to Micro.blog: a
first send carries the list beside title and content, and a re-send
replaces the post's categories with exactly the piece's list — only
when the piece has the line (opt-in by key; `[]` clears; no line
leaves the blog's). Naming a category Micro.blog doesn't know creates
it there, so there is no separate create step.

The publish sheet gains a Categories field: a comma list with the
system completion menu over the blog's own categories. The system
replaces the whole field text with a completion, so the completion is
the merge — a pick adds, a half-typed last word is replaced. The edit
lands on the piece at the send (a failed write refuses with nothing
on the wire); Publish with a pending edit applies it first and flips
the post that send touched.

The one-line codec lives in PostFrontmatter (line-bounded; backslashes
and quotes escaped; a Set de-duplicates). Import keeps an imported
`category:` line — the writer's classification, unlike the micropub
bookkeeping keys.

Reviewed twice (two-axis during the build, finish-audit after): the
stale pending baseline after a failed step, the backslash round-trip,
and the publish targeting the caller's possibly-stale URL were found
and fixed before this commit. 39 of the 40 new or changed pins were
watched fail on their own guard. Rail 791/791; SwiftFormat and
SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, the devlog, and the swift wiki (text
completion is a whole-text contract).

Closes #207
This commit is contained in:
AlexKucera committed 2026-12-05 08:09:57 +01:00
1 parent 6aa31a419a
commit 6db4cf8cf1
18 files changed
+1629 -67

No files matched your search

+4 -4
View File
@@ -31,8 +31,8 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu (#205: the shared hand-off fragment — #206 `MicroblogHandOffButton`, then #205 `FinderHandOffButtons` — between Move to Archive and Trash). Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Reveal in Finder/Copy Path/Open on Micro.blog (#206, published pieces)/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it. #206: the mono-11 micro-label shows the piece's Micro.blog status when it has one (`published <date>` / `draft on Micro.blog`) in origin's place — 178pt of row content cannot carry both — and VoiceOver reads both (`accessibilityText`); origin stays one hover away (the label's tooltip).
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` through the ONE trust gate (`Micropub.rememberedURL`, format-only — ownership is settled upstream: the import boundary drops the key, so only Museion or the writer's own hand writes one); #206 `micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape, read by the shared `parseStamp`) and the row label `micropubStatus` (`published <date>` / `draft on Micro.blog` / nil).
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`), `stampFormat` (the frontmatter timestamp shape both stamp writers and the reader share), and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win, and the Micro.blog bookkeeping dropped: `micropubKeys` — #206, a foreign file carries no post of this library), update-keys (`updating` — the in-place line-walk, every other line byte-identical; `dropping:` removes named keys' lines — the import and the 404 forget). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning and the Micro.blog bookkeeping dropped (#206: an imported `micropub_url` would aim the next send's content replace). Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter; a file the disk can't stat refuses as `missing`, never as a folder); `illustrationRef` is the one `![alt](assets/…)` builder. `stampMicropub` / `forgetMicropub` — the frontmatter-only micropub stamps (`micropub_url`, the #206 publish record `micropub_published`; on a 404 both lines are REMOVED — `forgetMicropub` throws when that write cannot land, so a failed clear refuses instead of claiming the link is gone), outside the write rail.
- `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. #207 the one-line `category:` list codec: `categories(in:)` reads the line (bracketed list, a bare scalar = ONE category, empty/absent = none) and `categoryValue(_:)` renders it — both over the unbracketed `categoryList`/`categoryListValue` and the one segment scanner `categorySegments` the publish sheet's field also speaks (ONE quote-aware comma-list parser: commas outside double quotes split, one pair of quotes stripped, `\\` and `\"` escaped on render and unescaped on read, empties dropped, first occurrence wins; newlines/control characters never reach the line-bounded sink).
- `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`, and #207 the `category:` line a sheet edit writes at the send — `[]` renders `category: []`; on a 404 the two micropub lines are REMOVED — `forgetMicropub` throws when that write cannot land, so a failed clear refuses instead of claiming the link is gone), outside the write rail.
- `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
- `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets).
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. `WritingLockAppDelegate` (same file) owns BOTH quit refusals: #162 asks once while a block holds; #200 gates quit-time document departure FIRST (never walk away from a block the quit then refuses to complete) — `quitReply(posts:)` is the pure decision (nil posts passes; the pins inject here), the one spoken refusal alert is hosted-guarded like the kiosk.
@@ -40,8 +40,8 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `DeslopLint.swift` — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). `Resources/deslop-lint.json` bundled default; `<home>/deslop-lint.json` override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; `emit` dedups against OPEN cards (closed never block, re-runs make progress).
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; #206 the remembered URL is also an OWNERSHIP question the format gate cannot answer — the import boundary drops both micropub keys (`PostFrontmatter.micropubKeys`), so a foreign file never aims a send at one of the writer's posts); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author; #206 an UNCHANGED image never uploads twice — `.museion-uploads.json` in the piece folder maps `sha256(bytes) → URL` (trust-gated on read-back, a symlinked memo never reads, written as each upload lands), so a re-send with untouched images is ONE request. The sheet owns every explicit click and opens on the piece's publish record (#206): Send as Draft → Publish for a never-sent piece, Update Draft for a draft, Update Live Post for a published one (status line + the live link; a remembered draft shows no link — its final URL answers Not Found until published; a publish stamp with no remembered link offers Send as Draft — there is no post to update). #206 a re-send never duplicates — a piece that remembers a post UPDATES it in place (`action=update` + `replace` name/content: same URL, no second post; a draft stays a draft, a live post edits live); a 404 means the post is gone there, so the piece forgets both stamps — their lines removed (`.forgotten`) — and the sheet is back to Send as Draft — a forget that cannot land refuses with the by-hand instruction instead; refusals inline with buttons kept; with a stored token in use it names it (the field's absence alone never said which token a send carries).
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`), (Home, ID) identity `PostsModelIdentity.swift` — `openSessionTargets` + #205 `fileURL(for:)`, the row menus' post.md path, a pure read) — the #146/#193 splits. **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSend` (#206; was `micropubSendDraft`) = flush-first, ONE disk read serves the wire fields and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update; `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), then stamps the publish record `micropub_published` and heals `micropub_url` in the same write; both share the (Home, ID) identity guard `openMicropubPiece`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubCategories.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; #207 the piece's `category:` list travels — a create carries `category` ONLY when non-empty, and naming a category Micro.blog doesn't know CREATES it there (no separate create call); 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; `queryRequest(_:token:)` is the one `GET <endpoint>?q=…` builder (config + the category list). Categories: `blogCategories(token:)` (`q=category`, `MicropubCategories.swift`) = the blog's own category names for the sheet's suggestions — the root `categories` strings, else `microblog-categories`'s `name` fields, trimmed, empties dropped; any failure or non-2xx is `[]` (no suggestions is not an error — the sheet stays silent, and a rejected token surfaces on the send itself). The sheet's Categories field (`MicropubPublishSheet.swift`) is a comma list in the codec's unbracketed form with the system completion menu over `blogCategories` (fetched on open; a failed fetch is silent — a typed new name creates the category at the send); the system REPLACES the whole field text with a completion, so `MicropubCategoryField.completion` IS the merge — a pick ADDS, a half-typed last word is replaced, a present name is never offered; the edit lands at the send via `micropubSend(categories:)` (Publish applies it first and flips the post that send touched — never the sheet's possibly-stale URL); the field syncs from disk over `openPieceCategories()` (the model's read of the open piece — never the scan snapshot) on open and after a forget, settles to the canonical text after a successful send, and after a failed step only its BASELINE re-syncs (the send writes the line before the wire, so a later clear of the field must still count as an edit). 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; #207 `replace` carries `category` ONLY when the piece has the `category:` line — opt-in by key, `[]` is sent and clears the post's categories, no line leaves the blog's); 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 Line truncated
- `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`) = guards → flush → (#207 a non-nil `categories:` edit lands as the piece's `category:` line FIRST — a failed write REFUSES the send with nothing on the wire) → ONE disk read serves the wire fields, the categories, and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update (`stampCategories` + `updateRememberedOrCreate` are its two steps); `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), #207 runs `micropubSend` FIRST when `categories:` is non-nil — the remembered post, or the fresh draft a create returned, is what gets published, and a failed send returns its outcome with NO publish (disk and blog never silently disagree) — then stamps the publish record `micropub_published` and heals `micropub_url` in the same write; both share the (Home, ID) identity guard `openMicropubPiece`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail.
- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), `documentsMayDepart` (#200: the departure gate's quit run — shutdown's flush half shared with `applicationShouldTerminate`; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive); document departure (new post/outline, select, open external, guest dismissal) rides the same gates through `sessionMayDepart`/`departOpenDocuments` — a navigation whose outgoing flush fails aborts with the dirty session retained (brief-25).
- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal` (`-> Bool` — false holds the departure)/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open — held by the departure gate when its flush fails (brief-25: the guest, its buffer, and its watcher stay live until the edits land)); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`).
+147 -42
View File
@@ -6,15 +6,19 @@
// Two-step publish (G2/G11): create with `post-status: draft`, review,
// then `action=update` flips the draft to published. Bearer app-token
// auth — no OAuth in v1; the token lives in the Keychain, entered
// once. Frontmatter `category:` is permitted but inert (v1 never
// sends it — the request carries name + content only).
// once. #207: the piece's `category:` list TRAVELS — a create carries
// it when non-empty (naming a category Micro.blog doesn't know
// creates it there), a re-send carries it in `replace` only when the
// piece has the line (`[]` clears; no line leaves the blog's). The
// blog's own list for the sheet's suggestions: MicropubCategories.swift.
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in
// MicropubMedia.swift, the orchestration in 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`),
// post; #207 adds `category` when the piece carries the line),
// 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.
@@ -78,7 +82,7 @@ nonisolated enum Micropub {
return request
}
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
static func makeDraftRequest(title: String, body: String, token: String, categories: [String] = []) -> URLRequest {
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
@@ -86,15 +90,17 @@ nonisolated enum Micropub {
// the WIRE (position and alt are the writer's; the piece on
// disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
jsonPost([
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
] as [String: Any],
], token: token)
// #207: the categories travel — naming one Micro.blog doesn't
// know creates it there; no list, no key.
var properties: [String: Any] = [
"name": [title],
"content": [body],
"post-status": ["draft"],
]
if !categories.isEmpty {
properties["category"] = categories
}
return jsonPost(["type": ["h-entry"], "properties": properties], token: token)
}
static func makePublishRequest(url: String, token: String) -> URLRequest {
@@ -109,14 +115,21 @@ nonisolated enum Micropub {
/// 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([
/// #207: `categories` opts the post's categories into `replace` —
/// a list (even empty: it clears them) is sent as written; nil
/// leaves whatever the post has.
static func makeUpdateRequest(url: String, title: String, body: String, token: String, categories: [String]? = nil) -> URLRequest {
var replace: [String: Any] = [
"name": [title],
"content": [body],
]
if let categories {
replace["category"] = categories
}
return jsonPost([
"action": "update",
"url": url,
"replace": [
"name": [title],
"content": [body],
],
"replace": replace,
], token: token)
}
@@ -124,14 +137,17 @@ nonisolated enum Micropub {
/// 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
/// illustrations already rewrote their refs in the body.
/// illustrations already rewrote their refs in the body. #207: the
/// categories ride as the entry's `category` (non-empty only).
static func sendDraft(
title: String,
body: String,
token: String,
categories: [String] = [],
transport: Transport = urlSessionTransport,
) async -> Outcome {
await run(makeDraftRequest(title: title, body: body, token: token), transport: transport, decodeDraftURL: true)
let request = makeDraftRequest(title: title, body: body, token: token, categories: categories)
return await run(request, transport: transport, decodeDraftURL: true)
}
/// Step 2: publish the draft — flip its post-status. Needs the
@@ -147,15 +163,18 @@ nonisolated enum Micropub {
/// #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.
/// review; a live post edited). Needs the remembered URL. #207:
/// `categories` non-nil also replaces the post's categories.
static func update(
url: String,
title: String,
body: String,
token: String,
categories: [String]? = nil,
transport: Transport = urlSessionTransport,
) async -> Outcome {
let outcome = await run(makeUpdateRequest(url: url, title: title, body: body, token: token), transport: transport, decodeDraftURL: false)
let request = makeUpdateRequest(url: url, title: title, body: body, token: token, categories: categories)
let outcome = await run(request, 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 {
@@ -326,20 +345,42 @@ extension PostsModel {
return (id, home)
}
/// #207: the open piece's categories as they are on DISK — what the
/// publish sheet's field syncs to (never the scan snapshot: the list
/// can lag the open piece). No open saved piece → none.
func openPieceCategories() -> [String] {
guard let piece = openMicropubPiece,
let file = PostStore.folder(of: piece.id, home: piece.home)?.appendingPathComponent("post.md"),
let raw = try? String(contentsOf: file, encoding: .utf8)
else { return [] }
return PostFrontmatter.categories(in: PostFrontmatter.parse(raw))
}
/// 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.
/// (name = Title, markdown content). runPass's guard set minus
/// the engine gates (no engine involved); flush-first so the wire
/// carries the editor's latest. #207: the piece's `category:` list
/// travels — a create carries it when non-empty; a re-send carries
/// `category` in `replace` only when the piece HAS the line
/// (opt-in by key — `[]` clears the post's categories, no line
/// leaves the blog's).
/// #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.
/// #207: `categories` (the sheet's edit) — nil = no edit, the
/// piece's line is used as written; non-nil = that list is written
/// to the piece FIRST (`[]` renders `category: []`), after the
/// flush and before the ONE disk read that feeds the wire, so disk
/// and blog never disagree. A category write that cannot land
/// REFUSES the send — nothing goes out.
/// #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,
categories: [String]? = nil,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
@@ -348,12 +389,15 @@ extension PostsModel {
guard flushOrAbort(piece.id) else {
return .refused(lastError ?? "Couldn't save the piece before sending.")
}
if let refused = stampCategories(categories, piece: piece) {
return refused
}
// Disk is the truth post-flush — ONE read serves the wire fields:
// Title (heading markers stripped — it publishes as the entry's
// name), the frontmatter-stripped body (the stamp is
// bookkeeping, never prose; the body itself is never stripped,
// GLOSSARY), and the remembered URL. No scan dependency: the
// list can lag the open piece.
// GLOSSARY), the remembered URL, and the categories. No scan
// dependency: the list can lag the open piece.
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
@@ -375,13 +419,61 @@ extension PostsModel {
return outcome
}
}
return await updateRememberedOrCreate(
raw: raw,
wireBody: wireBody,
piece: piece,
token: token,
transport: transport,
)
}
/// #207: the sheet's category edit lands on the piece HERE — after
/// the flush, before the ONE read that feeds the wire, so disk and
/// blog never disagree. nil is no edit. The refusal when the line
/// cannot land: the send stops here and nothing goes out.
private func stampCategories(_ categories: [String]?, piece: (id: String, home: URL)) -> Micropub.Outcome? {
guard let categories else { return nil }
do {
try PostStore.stampMicropub(piece.id, home: piece.home, [("category", PostFrontmatter.categoryValue(categories))])
} catch {
return .refused("Couldn't save this piece's categories — nothing was sent. (\(error.localizedDescription))")
}
return nil
}
/// The wire step over the disk's text (`raw` — the Title and the
/// frontmatter come from it) and the wire body. #206: a piece that
/// remembers its post UPDATES it 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); a piece that remembers none is CREATED as
/// a draft and remembers its URL. A stamp failure can't un-send
/// the draft; the sheet still holds the URL for this session — the
/// piece just loses the memory across a reopen (it would create a
/// second draft then). Kept quiet: the same disk accepted the
/// flush moments before.
/// #207: a create carries the categories when non-empty (never
/// `[]`); an update carries `category` only when the piece HAS the
/// line — opt-in by key, `[]` clears, no line leaves the blog's.
private func updateRememberedOrCreate(
raw: String,
wireBody: String,
piece: (id: String, home: URL),
token: String,
transport: Micropub.Transport,
) async -> Micropub.Outcome {
let matter = PostFrontmatter.parse(raw)
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 let remembered = Micropub.rememberedURL(matter) {
let outcome = await Micropub.update(
url: remembered,
title: title,
body: wireBody,
token: token,
categories: matter["category"] != nil ? PostFrontmatter.categories(in: matter) : nil,
transport: transport,
)
if case .requestFailed(404, _) = outcome {
return micropubPostGone(id: piece.id, home: piece.home)
}
@@ -391,15 +483,10 @@ extension PostsModel {
title: title,
body: wireBody,
token: token,
categories: PostFrontmatter.categories(in: matter),
transport: transport,
)
if case let .drafted(url, _) = outcome {
// Remember the draft's URL for the publish step and every
// later in-place update. A stamp failure can't un-send the
// draft; the sheet still holds the URL for this session —
// the piece just loses the memory across a reopen (it
// would create a second draft then). Kept quiet: the same
// disk accepted the flush moments before.
try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
}
return outcome
@@ -415,9 +502,16 @@ extension PostsModel {
/// 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.
/// #207: `categories` non-nil = pending edits — the piece is sent
/// FIRST (`micropubSend`, the edit landing on disk), then the post
/// that send leaves is published: the remembered one, or the fresh
/// draft a create returned — never the caller's URL, which the
/// sheet may hold stale against the disk. A failed send returns its
/// outcome with NO publish — disk and blog never silently disagree.
func micropubPublish(
url: String,
token: String,
categories: [String]? = nil,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
@@ -426,11 +520,22 @@ extension PostsModel {
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)
var target = url
if let categories {
switch await micropubSend(token: token, categories: categories, transport: transport) {
case let .updated(touched):
target = touched
case let .drafted(fresh, _):
target = fresh
case let other:
return other
}
}
let outcome = await Micropub.publish(url: target, token: token, transport: transport)
switch outcome {
case .published:
try? PostStore.stampMicropub(piece.id, home: piece.home, [
("micropub_url", url),
("micropub_url", target),
("micropub_published", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)),
])
case .requestFailed(404, _):
+48
View File
@@ -0,0 +1,48 @@
//
// MicropubCategories.swift
// Museion
//
// #207: the blog's own categories — the list the publish sheet
// offers as suggestions for the piece's `category:` line. One
// query, no writes: naming a category Micro.blog doesn't know
// CREATES it when the post is sent (the create/update carry the
// list — Micropub.swift and the codec in PostFrontmatter.swift),
// so there is no separate create call here.
//
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=category` answers the blog's categories as a
// root `categories` string array; some answers carry the richer
// `microblog-categories` objects (`name` + `url`) instead. A 2xx
// with neither is a blog without categories — no suggestions is
// not an error, and neither is any failure: the sheet stays silent
// (a typed new name still creates the category at the send, and a
// rejected token surfaces on the send itself).
//
import Foundation
nonisolated extension Micropub {
/// `GET <endpoint>?q=category` — the config query's shape.
static func makeCategoryListRequest(token: String) -> URLRequest {
queryRequest("category", token: token)
}
/// The blog's categories for the sheet's suggestions — trimmed,
/// empties dropped; `[]` on any failure or non-2xx (there is no
/// error to surface — see the header).
static func blogCategories(token: String, transport: Transport = urlSessionTransport) async -> [String] {
guard let (data, response) = try? await transport(makeCategoryListRequest(token: token)),
(200 ..< 300).contains(response.statusCode) else { return [] }
return categoryNames(in: data)
}
/// The root `categories` strings, else the `microblog-categories`
/// objects' `name` fields.
private static func categoryNames(in data: Data) -> [String] {
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
let names = (root["categories"] as? [String])
?? (root["microblog-categories"] as? [[String: Any]])?.compactMap { $0["name"] as? String }
?? []
return names.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
}
}
+7 -1
View File
@@ -108,8 +108,14 @@ nonisolated extension Micropub {
// MARK: q=config (hop 1)
static func makeConfigRequest(token: String) -> URLRequest {
queryRequest("config", token: token)
}
/// The one `GET <endpoint>?q=…` shape (#34's config query, #207's
/// category list): the fixed endpoint, Bearer token, 30 s.
static func queryRequest(_ q: String, token: String) -> URLRequest {
var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "q", value: "config")]
components.queryItems = [URLQueryItem(name: "q", value: q)]
var request = URLRequest(url: components.url!)
request.timeoutInterval = 30
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+191 -3
View File
@@ -15,10 +15,99 @@
// 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.
// #207: a Categories field — the piece's `category:` line as a
// comma list, edited with the system completion menu over the
// blog's own categories (`Micropub.blogCategories`, fetched on
// open; a failed fetch is silent). The system REPLACES the whole
// field text with a completion, so `MicropubCategoryField` (the
// enum above the view) carries the merge: a pick ADDS, a
// half-typed last word is replaced. The edit lands on disk AT THE
// SEND (the model's `categories:`), never before — Cancel/Done
// discard it and a refused send puts nothing on the wire; the field
// syncs from disk on open and after a forget, settles to the
// canonical text after a successful send, and after a failed step
// only its baseline re-syncs (the send writes the line before the
// wire — a later clear must still count as an edit).
//
import SwiftUI
/// #207: the publish sheet's Categories field — its pure rules over
/// the one-line category codec (`PostFrontmatter.categoryList` /
/// `categoryListValue`: the ONE quote-aware comma-list parser — the
/// field holds exactly the bracket-inner text). The system completion
/// menu REPLACES the whole field text with a completion, so a
/// completion IS the merge: a pick ADDS, a half-typed last word is
/// replaced, a present name is never offered.
nonisolated enum MicropubCategoryField {
/// The word being typed — the LAST comma segment (a comma inside
/// double quotes never splits), trimmed, one pair of quotes off
/// (the codec's own step: the field reads `Tech, "Tech, general"`
/// after that pick, and the word is the name). SwiftUI exposes no
/// caret, so the end of the text is the only place a writer can be
/// typing. "" when the text is empty or ends with a comma.
static func partial(_ text: String) -> String {
// The codec's own segment scanner splits (ONE quote-aware walk);
// its `categoryList` trims, unquotes and unescapes the segment.
PostFrontmatter.categoryList(PostFrontmatter.categorySegments(text).last ?? "").first ?? ""
}
/// The last thing typed is itself a known category — nothing is
/// half-typed.
static func finished(_ text: String, blog: [String]) -> Bool {
let word = partial(text)
return !word.isEmpty && blog.contains { same($0, word) }
}
/// The menu over the blog's categories, blog order kept: ALL of
/// them when nothing or a finished name is typed, else the names
/// starting with the half-typed word (case-insensitive); a name
/// already in the field is never offered.
static func suggestions(text: String, blog: [String]) -> [String] {
let word = partial(text)
let present = Set(PostFrontmatter.categoryList(text).map { $0.lowercased() })
let all = word.isEmpty || finished(text, blog: blog)
return blog.filter { name in
!present.contains(name.lowercased()) && (all || name.lowercased().hasPrefix(word.lowercased()))
}
}
/// What the WHOLE field becomes when `name` is picked: a
/// half-typed last word makes room (the pick extends it, and the
/// word is not itself a category), then `name` is appended unless
/// present — never a duplicate.
static func completion(text: String, picking name: String, blog: [String]) -> String {
var names = PostFrontmatter.categoryList(text)
let word = partial(text)
let halfTyped = !word.isEmpty && !finished(text, blog: blog) && same(names.last ?? "", word)
if halfTyped, !same(word, name), name.lowercased().hasPrefix(word.lowercased()) {
names.removeLast()
}
if !names.contains(where: { same($0, name) }) {
names.append(name)
}
return PostFrontmatter.categoryListValue(names)
}
/// The sheet's edit for the model: nil when the field's list IS the
/// settled one — LISTS, so a trailing comma is not an edit, and
/// equal empties stay nil (a piece without a line never gains an
/// empty key); else the field's list (`[]` = cleared — the model
/// writes `category: []`).
static func pendingCategories(field: String, settled: String) -> [String]? {
let list = PostFrontmatter.categoryList(field)
return list == PostFrontmatter.categoryList(settled) ? nil : list
}
/// ponytail: case-insensitive on purpose — the writer's spelling stays
/// in the field, the menu just never re-offers a name that's there in
/// any case; the codec's own dedup stays exact (it records what was
/// written, it never rewrites a spelling).
private static func same(_ a: String, _ b: String) -> Bool {
a.caseInsensitiveCompare(b) == .orderedSame
}
}
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
@@ -49,6 +138,15 @@ struct MicropubPublishSheet: View {
@State private var refusal: String?
@State private var tokenField = ""
@State private var reentry = false
/// #207: the Categories field as typed, the text it rests on (the
/// disk read on open, or a successful send's canonical form — the
/// pending-edit baseline), and the blog's categories the menu offers.
@State private var categoryField = ""
@State private var settledCategoryField = ""
@State private var blogCategories: [String] = []
/// Whether the blog's categories were ever fetched in this sheet
/// (a blog with none is not re-asked after every send).
@State private var suggestionsLoaded = false
/// Token entry shows when none is saved — or again after an auth
/// failure (the entered-once token can be replaced, never a dead end).
@@ -60,6 +158,11 @@ struct MicropubPublishSheet: View {
phase == .drafting || phase == .updating || phase == .publishing
}
/// #207: the field's edit for the send — nil when nothing changed.
private var pendingCategories: [String]? {
MicropubCategoryField.pendingCategories(field: categoryField, settled: settledCategoryField)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
@@ -73,6 +176,26 @@ struct MicropubPublishSheet: View {
.foregroundStyle(DesignTokens.muted)
}
// #207: the Categories field, in every phase — a send is possible in all of them.
VStack(alignment: .leading, spacing: 4) {
Text("Categories")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
TextField("Tech, Notes", text: $categoryField)
.textFieldStyle(.roundedBorder)
.font(.system(size: 12, design: DesignTokens.mono))
.disabled(busy)
.accessibilityLabel("Categories")
.textInputSuggestions {
ForEach(MicropubCategoryField.suggestions(text: categoryField, blog: blogCategories), id: \.self) { name in
Text(name).textInputCompletion(MicropubCategoryField.completion(text: categoryField, picking: name, blog: blogCategories))
}
}
Text("Comma-separated. A name Micro.blog doesn't know is created when the post is sent.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if showsTokenField {
SecureField("App token", text: $tokenField)
.textFieldStyle(.roundedBorder)
@@ -152,6 +275,8 @@ struct MicropubPublishSheet: View {
postURL = post.micropubURL
publishedAt = post.micropubPublished
phase = settledPhase
syncFieldFromDisk()
loadSuggestions()
}
}
@@ -222,13 +347,15 @@ struct MicropubPublishSheet: View {
/// 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).
/// entry — the entered-once token may be wrong). #207: the category
/// baseline follows the disk (the field keeps the text as typed).
private func fail(_ message: String, tokenRejected: Bool = false) {
if tokenRejected {
reentry = true
}
refusal = message
phase = settledPhase
syncSettledFromDisk()
}
/// Step 1 — the model decides create-vs-update by the piece's
@@ -242,14 +369,16 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = postURL == nil ? .drafting : .updating
Task {
switch await posts.micropubSend(token: token) {
switch await posts.micropubSend(token: token, categories: pendingCategories) {
case let .drafted(url, preview):
postURL = url
previewURL = preview
phase = .drafted
sendLanded()
case let .updated(url):
postURL = url
phase = .updated
sendLanded()
case let .authFailed(detail):
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
@@ -272,10 +401,11 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = .publishing
Task {
switch await posts.micropubPublish(url: url, token: token) {
switch await posts.micropubPublish(url: url, token: token, categories: pendingCategories) {
case .published:
publishedAt = Date()
phase = .published
settle()
case let .authFailed(detail):
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
@@ -299,5 +429,63 @@ struct MicropubPublishSheet: View {
publishedAt = nil
previewURL = nil
phase = .idle
// #207: the forget clears only the micropub keys — a category
// line the failed send already wrote stays on the piece, so the
// field re-syncs to it (no false pending state).
syncFieldFromDisk()
}
// MARK: Categories (#207)
/// The piece's `category:` line as it is on DISK (the model's read —
/// never the scan snapshot), in the codec's unbracketed form. No
/// open saved piece, or an unreadable file → "".
private var diskCategoryText: String {
PostFrontmatter.categoryListValue(posts.openPieceCategories())
}
/// The field AND its baseline take the disk's line (on open, after a
/// forget).
private func syncFieldFromDisk() {
categoryField = diskCategoryText
settledCategoryField = categoryField
}
/// Only the BASELINE follows the disk (a failed step). The send
/// writes the category line BEFORE the wire, so a refusal or a
/// failed publish may leave the edit on the piece; the pending test
/// must compare against what the piece really holds — a later clear
/// of the field has to count as an edit. The field keeps the text as
/// typed.
private func syncSettledFromDisk() {
settledCategoryField = diskCategoryText
}
/// The blog's categories for the menu, over the Keychain's token.
/// A failure is silent — no suggestions is a normal state (the
/// field still works: a typed new name creates the category).
private func loadSuggestions() {
guard let token = MicropubTokenStore.read() else { return }
Task {
blogCategories = await Micropub.blogCategories(token: token)
suggestionsLoaded = true
}
}
/// A send landed: the writer sees the canonical text, and the
/// edit is no longer pending. (A REFUSED send keeps the text as typed.)
private func settle() {
categoryField = PostFrontmatter.categoryListValue(PostFrontmatter.categoryList(categoryField))
settledCategoryField = categoryField
}
/// A successful send: the field settles, and a token first entered
/// in this sheet gets its suggestions now — once. A blog WITH no
/// categories is not asked again after every send.
private func sendLanded() {
settle()
if !suggestionsLoaded {
loadSuggestions()
}
}
}
+124
View File
@@ -12,6 +12,10 @@
// on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out
// of scope (#180); their dismiss stamp rides the generic update posture
// without redesigning its shape.
// #207: the one-line `category:` list — read (`categories(in:)`) and
// render (`categoryValue(_:)`) over the unbracketed pair the publish
// sheet's field also speaks (`categoryList`/`categoryListValue`): ONE
// parser serves the piece, the sheet, and the wire.
//
import Foundation
@@ -123,6 +127,126 @@ nonisolated enum PostFrontmatter {
return stamp.origin == .writer && stamp.type == .post && stamp.passState == .firstDraft
}
// MARK: - Category list (#207)
/// #207: the quote-aware comma-list parse the `category:` line and
/// the publish sheet's category FIELD share — ONE parser (the
/// field holds exactly the bracket-inner text). Splits on the
/// commas OUTSIDE double quotes, trims each item, strips ONE pair
/// of surrounding double quotes and unescapes `\\` and `\"`;
/// empties drop and the first occurrence of a name wins. Creation
/// is implicit on Micro.blog: naming a category that doesn't exist
/// creates it when the post is sent.
static func categoryList(_ inner: String) -> [String] {
var names: [String] = []
var seen: Set<String> = []
for item in categorySegments(inner) {
let trimmed = item.trimmingCharacters(in: .whitespaces)
var name = trimmed
// A quoted item carries its whitespace and its escapes
// (`\\` and `\"`) verbatim; a bare item is taken as written.
if trimmed.hasPrefix("\""), trimmed.hasSuffix("\""), trimmed.count >= 2 {
name = categoryUnescaped(String(trimmed.dropFirst().dropLast()))
}
guard !name.isEmpty, seen.insert(name).inserted else { continue }
names.append(name)
}
return names
}
/// `categoryListValue`'s escape, undone: `\\` is a backslash, `\"` a
/// quote. Any other escaped character keeps its backslash (a
/// hand-typed `\n` stays the two characters it is), and a trailing
/// lone backslash stays.
private static func categoryUnescaped(_ text: String) -> String {
var out = ""
var escaped = false
for char in text {
if escaped {
if char != "\\", char != "\"" {
out.append("\\")
}
out.append(char)
escaped = false
} else if char == "\\" {
escaped = true
} else {
out.append(char)
}
}
if escaped {
out.append("\\")
}
return out
}
/// The unbracketed render `categoryList` reads back — a name
/// holding `,` `[` `]` `"` or `\` rides double-quoted with its
/// backslashes and quotes escaped. Newlines and control characters
/// strip from every name first (the frontmatter sink is
/// line-bounded) and names left empty drop.
static func categoryListValue(_ names: [String]) -> String {
names.compactMap { name -> String? in
let cleaned = String(name.trimmingCharacters(in: .whitespaces).unicodeScalars.filter {
!CharacterSet.newlines.contains($0) && !CharacterSet.controlCharacters.contains($0)
})
guard !cleaned.isEmpty else { return nil }
guard cleaned.contains(where: { ",[]\"\\".contains($0) }) else { return cleaned }
let slashed = cleaned.replacingOccurrences(of: "\\", with: "\\\\")
return "\"" + slashed.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}.joined(separator: ", ")
}
/// The list items, split on the commas outside double quotes (an
/// escaped quote inside a quoted item never toggles the quote
/// state — `["say \"hi\", Notes]` is two items).
/// The ONE segment scanner behind `categoryList` and the publish
/// sheet's `partial` — the raw (untrimmed, still-quoted) items.
static func categorySegments(_ text: String) -> [String] {
var items: [String] = []
var current = ""
var quoted = false
var escaped = false
for char in text {
if escaped {
current.append(char)
escaped = false
} else if char == "\\" {
current.append(char)
escaped = true
} else if char == "\"" {
current.append(char)
quoted.toggle()
} else if char == ",", !quoted {
items.append(current)
current = ""
} else {
current.append(char)
}
}
items.append(current)
return items
}
/// #207: the piece's categories from its `category:` line — ONE
/// line by construction (the read is line-bounded, #33), so a
/// value can never carry a newline. Shapes: `[Tech, Notes]` (the
/// bracketed list, read through `categoryList`), a bare scalar
/// (`Essays` — YAML's plain string) = ONE category, and empty /
/// absent = none.
static func categories(in matter: [String: String]) -> [String] {
guard let raw = matter["category"]?.trimmingCharacters(in: .whitespaces), !raw.isEmpty else { return [] }
let listShaped = raw.hasPrefix("[") && raw.hasSuffix("]") && raw.count >= 2
return listShaped ? categoryList(String(raw.dropFirst().dropLast())) : [raw]
}
/// #207: the one-line `category:` value `categories(in:)` reads
/// back — the bracketed `categoryListValue`. `[]` is the empty
/// list, the value a re-send's clear carries.
static func categoryValue(_ names: [String]) -> String {
"[" + categoryListValue(names) + "]"
}
// MARK: - Write postures
/// The known-key table: Museion's three owned keys in stamp order —
+2 -1
View File
@@ -680,7 +680,8 @@ nonisolated extension PostStore {
// MARK: #33 (S6.1) / #206 — the remembered Micro.blog post
/// Stamp micropub keys in place (`micropub_url`, the publish record
/// `micropub_published`) — a frontmatter-only change: the body and
/// `micropub_published`, and #207 the `category:` line) — a
/// frontmatter-only change: the body and
/// every other key stay byte-identical, so the open session's
/// readBody-based echo check never fires, and every later editor
/// save re-reads the block (the stamps survive it). A vanished piece