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

+5 -1
View File
@@ -146,6 +146,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- A bash function invoked before its definition no-ops (`command not found`) under `set -uo` without `-e` — hoist definitions above first use and guard rig verdicts by executed-check count, never the banner (#190)
- GitNexus `detect-changes` in this machine's multi-repo registry needs `--repo /absolute/path` — it aborts on ambiguity but rejects the `name (path)` label form it prints (#193)
- When splitting a file, re-derive each side's imports from symbol usage, never copy the old import block — Swift has no unused-import warning, so a stranded import (PostsPaneView's AppKit) survives lint and only a diff review catches it (#193)
- A wedged TUI shell plus `execute_code` blocked in an unattended turn still leaves a child's terminal — delegate the rail or flip run to it (detached subprocesses as fallback) (#207)
### Testing
- Gate-running rules are encoded in `scripts/full-test.sh` (#190) — run `./scripts/full-test.sh start` + `status` polling (`summary` for the finished counts), never hand-rolled xcodebuild/xcresult incantations. The rest of this section is authoring rules the script cannot encode.
@@ -167,11 +168,14 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- 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)
- `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)
- A flip proves a guard only when it SOLELY causes a red pin — two flips on one pin mask each other (split-off hid dedupe; never-append hid `finished`); re-flip masked guards alone (#207)
### 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 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)
- 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)
- Escape the escape character first (`\\` before `\"`) — a renderer that escapes only its delimiter breaks once the scanner honors a generic escape: a trailing backslash swallows the separator (#207)
- A later step targets what the earlier step touched, never the caller's copy — publishing the sheet's stale URL would stamp a dead address over the real memory (#207)
## Session Logs
@@ -180,6 +184,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-12-04 | [20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md](20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md) |
| 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-03 | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) |
@@ -189,5 +194,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-12-03 | [20261203-release-011-apex-refresh-is-step-one_log.md](20261203-release-011-apex-refresh-is-step-one_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-23 | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) |
<!-- 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
- **publish:** Micro.blog categories travel (#207) — the piece's `category:` frontmatter line rides the send (one line, `category: [Tech, Notes]`; a bare `category: Essays` is one category). A first send carries the list beside the title and content; a re-send replaces the post's categories with exactly the piece's list — but only when the piece has the line at all (no line leaves whatever the blog has; an empty `category: []` clears them). Naming a category Micro.blog doesn't know creates it there, so there is no separate create step. The publish sheet has a **Categories** field: comma-separated, with the system completion menu over your blog's existing categories (fetched when the sheet opens; a failed fetch stays silent and a typed new name still works). Clicking any number of categories adds them all — the menu stays open — a half-typed word is replaced by the pick, and a name already in the field is never offered again. The edit lands on the piece when you send (Cancel/Done discard it); Publish with a pending category edit applies it first — to the post the piece remembers, never a stale address — and never publishes after a failed update. +39 tests (the wire contract, the codec incl. its backslash escaping, the model's write-then-send order and the sanitized name, the blog's category list, publish-applies-first and targeting the post the send touched, the sheet field's picks-add completion and menu, the import keeping the line), each seen red first. Suite 791
- **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
+4
View File
@@ -168,3 +168,7 @@ _Avoid_: publish state (it is a record on disk, never a live query), status (tha
### 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)
### Category
A Micro.blog classification carried as the Piece's one-line `category:` frontmatter list (`category: [Tech, Notes]`; a bare scalar is one category, `[]` is explicitly none). Travels with every send; a name Micro.blog does not know is created there at the send. Import keeps it — the writer's classification, unlike the Publish Record keys — and a re-send replaces the post's categories only when the line exists.
_Avoid_: type (that is Content Type), tag
+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
+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.
- `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).
- `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.
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests` — 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); #207 `MicropubCategoryTests` — categories travel (a create carries the list when non-empty; a re-send opt-in by key, `[]` clears), the codec list incl. the unbracketed primitives, apply-at-send with the failed-write refusal, the blog's `q=category` list, publish-applies-first (a failed update never publishes — the request count is pinned; the flip targets the post the send touched, never a stale caller URL), the sanitized name on disk and wire, the model's `openPieceCategories()` read, the import keeps a category line, + the sheet field's pure rules (pending edit, picks-add completion, the menu). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared; `plantedPiece` (a saved `# Titled` piece with planted frontmatter) lives in `MicropubTests.swift` beside the other shared helpers. 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.
- `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).
+547
View File
@@ -0,0 +1,547 @@
//
// MicropubCategoryTests.swift
// MuseionTests
//
// #207: Micro.blog categories travel. Scenario:
//
// Given a saved Post whose frontmatter carries a one-line
// `category:` list (`[Tech, Notes]`, a bare scalar `Essays`, or
// empty — the codec is line-bounded)
// When the writer sends it to Micro.blog, re-sends it over the
// remembered post, or publishes with a category edit made in the
// sheet
// Then a CREATE carries `properties.category` (only when the list
// is non-empty — naming a category that doesn't exist CREATES it on
// Micro.blog, no separate call); a RE-SEND carries `category` in
// `replace` ONLY when the piece has the line (opt-in by key — `[]`
// is sent and clears the post's categories; no line → `replace`
// names exactly name + content, the blog keeps whatever it has); a
// sheet edit (`categories:` non-nil) lands on disk AT THE SEND —
// flush → category line → ONE disk read feeds the wire — and a
// failed category write REFUSES the send with nothing on the wire;
// Publish with pending edits runs the update FIRST and never
// publishes after a failed update (disk and blog never silently
// disagree); the blog's own categories list through `q=category`
// (no suggestions is not an error). Import keeps an imported
// `category:` key (external keys ride verbatim). The sheet's
// Categories FIELD is a comma list in the codec's unbracketed form
// over the blog's categories (the system completion menu REPLACES
// the whole field text, so a completion IS the merge): its pure
// rules — the pending-edit test, picks add / a half-typed word is
// replaced, the menu — are pinned here; the view itself is not.
//
// Pins: S1 categories travel on create · S2 re-send replaces,
// opt-in by key (builders + model) · S3 the codec (read + render,
// round-trip incl. backslashes) · S4 the edit lands at the send
// (sanitized, readable through the model; + the refusal, + the
// import keeps the line) · S5 the blog's categories · S6 publish
// applies pending edits first and targets the post the send
// touched · S7 the field's pending-edit rule · S8 picks add (the
// whole-text completion) + the menu.
//
import Foundation
@testable import Museion
import Testing
@Suite("MicropubCategoryTests")
struct MicropubCategoryTests {
/// A saved piece opened in the model, with `frontmatter` planted
/// after the owned keys (before the session loads it); returns its id.
@MainActor private func openPiece(_ model: PostsModel, _ home: URL, frontmatter: String = "") throws -> String {
let id = try plantedPiece(home, frontmatter: frontmatter)
model.select(id)
return id
}
/// A recorded create's `properties` — a short log fails the pin's
/// own requirement instead of trapping (#206: `request(_:)`, never a subscript).
private nonisolated func createProperties(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
let request = try #require(log.request(index))
return try #require(micropubJSON(request)["properties"] as? [String: Any])
}
/// A recorded update's `replace`.
private nonisolated func updateReplace(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
let request = try #require(log.request(index))
return try #require(micropubJSON(request)["replace"] as? [String: Any])
}
/// The writer's blog categories the S8 pins pick against (blog
/// order is the wire's).
private static let blog = ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"]
// MARK: S3 — the codec reads and renders the one-line list (pure)
@Test func `category read is the list the bare scalar or empty`() {
#expect(PostFrontmatter.categories(in: ["category": "[Tech, Notes]"]) == ["Tech", "Notes"])
#expect(PostFrontmatter.categories(in: ["category": "[\"Tech, general\", Notes]"]) == ["Tech, general", "Notes"])
#expect(PostFrontmatter.categories(in: ["category": "Essays"]) == ["Essays"])
#expect(PostFrontmatter.categories(in: ["category": "[ Tech , Notes,, Tech ]"]) == ["Tech", "Notes"])
#expect(PostFrontmatter.categories(in: ["category": ""]) == [])
#expect(PostFrontmatter.categories(in: ["category": "[]"]) == [])
#expect(PostFrontmatter.categories(in: [:]) == [])
// A hand-quoted scalar is one category (parse strips the quotes).
#expect(PostFrontmatter.categories(in: PostFrontmatter.parse("---\ncategory: \"Tech, general\"\n---\n")) == ["Tech, general"])
}
@Test func `category value renders one line that round-trips through parse`() {
let value = PostFrontmatter.categoryValue(["Tech", "Tech, general", "say \"hi\""])
#expect(!value.contains("\n")) // the frontmatter sink is line-bounded
let matter = PostFrontmatter.parse("---\ncategory: \(value)\n---\n")
#expect(PostFrontmatter.categories(in: matter) == ["Tech", "Tech, general", "say \"hi\""])
// Backslashes escape too — a name ending in one, or holding `\"`,
// reads back as itself (never one junk name swallowing the next).
let slashed = ["a\\", "x\\\"y", "Notes"]
let slashedValue = PostFrontmatter.categoryValue(slashed)
#expect(PostFrontmatter.categories(in: PostFrontmatter.parse("---\ncategory: \(slashedValue)\n---\n")) == slashed)
// Line/control characters strip before the sink; empties drop.
#expect(PostFrontmatter.categoryValue(["a\nb", "", " "]) == "[ab]")
#expect(PostFrontmatter.categoryValue([]) == "[]")
}
@Test func `category list primitives are the unbracketed parse and render`() {
#expect(PostFrontmatter.categoryList("Tech, No") == ["Tech", "No"])
#expect(PostFrontmatter.categoryListValue(["Tech", "Tech, general"]) == "Tech, \"Tech, general\"")
let names = ["Tech", "Tech, general", "say \"hi\""]
#expect(PostFrontmatter.categoryList(PostFrontmatter.categoryListValue(names)) == names)
}
// MARK: S2 — the wire contract (pure builders)
@Test func `draft request carries category only when the list is non-empty`() throws {
let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", categories: ["Tech", "Notes"])
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
#expect(props["category"] as? [String] == ["Tech", "Notes"])
#expect(props["name"] as? [String] == ["T"])
#expect(props["content"] as? [String] == ["B"])
#expect(props["post-status"] as? [String] == ["draft"])
// No categories → no key at all (a create never carries an empty list).
let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any])
#expect(bare["category"] == nil)
}
@Test func `update request carries category in replace only when a list is given`() throws {
let url = "https://example.micro.blog/hello.html"
let listedRequest = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok", categories: ["Tech", "Notes"])
let listed = try #require(micropubJSON(listedRequest)["replace"] as? [String: Any])
#expect(listed["category"] as? [String] == ["Tech", "Notes"])
#expect(listed["name"] as? [String] == ["T"])
#expect(listed["content"] as? [String] == ["B"])
// An empty list IS sent — it clears the post's categories.
let clearedRequest = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok", categories: [])
let cleared = try #require(micropubJSON(clearedRequest)["replace"] as? [String: Any])
#expect(cleared["category"] as? [String] == [])
// nil → the opt-out: replace names exactly name + content, the
// bytes the #206 request carried (JSONSerialization escapes `/`).
let kept = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok")
let replace = try #require(micropubJSON(kept)["replace"] as? [String: Any])
#expect(Set(replace.keys) == ["name", "content"])
let expected = #"{"action":"update","replace":{"content":["B"],"name":["T"]},"url":"https:\/\/example.micro.blog\/hello.html"}"#
#expect(kept.httpBody == Data(expected.utf8))
}
// MARK: S1 — categories travel (create)
@Test @MainActor func `create carries the piece's category list and no key when there is none`() async throws {
let (model, home) = try makeModelHome()
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/categorized"], log: log)
_ = try openPiece(model, home, frontmatter: "category: [Tech, Notes]\n")
let listed = await model.micropubSend(token: "tok", transport: transport)
#expect(listed == .drafted(url: "https://example.micro.blog/categorized", preview: nil))
let props = try createProperties(log, 0)
#expect(props["category"] as? [String] == ["Tech", "Notes"])
#expect(props["name"] as? [String] == ["Titled"])
#expect(props["content"] as? [String] == ["# Titled\n\nBody."])
#expect(props["post-status"] as? [String] == ["draft"])
// No line at all → no key; an empty line → no key either.
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: transport)
let bare = try createProperties(log, 1)
#expect(bare["category"] == nil)
_ = try openPiece(model, home, frontmatter: "category:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let emptyLine = try createProperties(log, 2)
#expect(emptyLine["category"] == nil)
}
// MARK: S2 — a re-send replaces, opt-in by key (the model)
@Test @MainActor func `a re-send carries the line's list in replace and clears on an empty list`() async throws {
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
let transport = micropubCanned(200, log: log)
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: [Tech, Notes]\n")
let listed = await model.micropubSend(token: "tok", transport: transport)
#expect(listed == .updated(url: url))
let replace = try updateReplace(log, 0)
#expect(replace["category"] as? [String] == ["Tech", "Notes"])
#expect(replace["name"] as? [String] == ["Titled"])
// An empty list IS sent — it clears the post's categories.
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: []\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let cleared = try updateReplace(log, 1)
#expect(cleared["category"] as? [String] == [])
// No line → replace names exactly name + content: the blog keeps whatever it has.
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let kept = try updateReplace(log, 2)
#expect(Set(kept.keys) == ["name", "content"])
}
// MARK: S4 — the edit lands at the send
@Test @MainActor func `a category edit lands on the piece before the wire`() async throws {
let (model, home) = try makeModelHome()
let id = try openPiece(model, home) // no category line yet
let before = try PostFrontmatter.split(readPost(home, id)).body
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/edited"], log: log)
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: transport)
#expect(outcome == .drafted(url: "https://example.micro.blog/edited", preview: nil))
let after = try readPost(home, id)
// The line is a line of the block (inserted before the closing
// `---` — the send's own `micropub_url` stamp lands after it);
// the body is byte-identical.
#expect(PostFrontmatter.split(after).block.contains("\ncategory: [Essays]\n"))
#expect(PostFrontmatter.split(after).body == before)
let props = try createProperties(log, 0)
#expect(props["category"] as? [String] == ["Essays"])
}
@Test @MainActor func `clearing as an empty list writes category empty and sends it in replace`() async throws {
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: [Tech]\n")
let outcome = await model.micropubSend(token: "tok", categories: [], transport: micropubCanned(200, log: log))
#expect(outcome == .updated(url: url))
let disk = try readPost(home, id)
#expect(disk.contains("category: []\n"))
let replace = try updateReplace(log, 0)
#expect(replace["category"] as? [String] == [])
}
@Test @MainActor func `a refused send with a category edit writes nothing`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never opened
let before = try readPost(home, post.id)
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: micropubCanned(201, log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
let after = try readPost(home, post.id)
#expect(after == before) // the edit never reached the disk
}
@Test @MainActor func `a category write that cannot land refuses the send with nothing on the wire`() async throws {
let (model, home) = try makeModelHome()
let id = try openPiece(model, home)
// The piece folder goes read-only: the category line cannot land
// (the #206 stamp-failure injection).
let dir = try #require(PostStore.folder(of: id, home: home))
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: micropubCanned(201, log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(reason.hasPrefix("Couldn't save this piece's categories — nothing was sent."))
#expect(log.requests.isEmpty)
let disk = try readPost(home, id)
#expect(!disk.contains("category:"))
}
@Test @MainActor func `a category name is sanitized before it lands on the piece and the wire`() async throws {
let (model, home) = try makeModelHome()
let log = MicropubRequestLog()
let id = try openPiece(model, home)
_ = await model.micropubSend(
token: "tok",
categories: ["a\nb", " "],
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/clean"], log: log),
)
// The newline never reaches the line-bounded sink and the blank
// name drops; the wire's names come from that sanitized disk line.
#expect(try PostFrontmatter.parse(readPost(home, id))["category"] == "[ab]")
#expect(try createProperties(log, 0)["category"] as? [String] == ["ab"])
}
@Test @MainActor func `the sheet's disk read is the open piece's category line`() async throws {
let (model, home) = try makeModelHome()
#expect(model.openPieceCategories() == []) // nothing open
_ = try openPiece(model, home)
#expect(model.openPieceCategories() == []) // no line yet
let log = MicropubRequestLog()
_ = await model.micropubSend(
token: "tok",
categories: ["Essays"],
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: log),
)
#expect(model.openPieceCategories() == ["Essays"]) // read from disk, never a snapshot
}
@Test func `an imported category line rides through import`() throws {
let home = try storeHome()
// A foreign file carries its own classification — only Museion's
// bookkeeping drops at the boundary (#206); the category line is
// the writer's, so it stays (#207).
let ext = FileManager.default.temporaryDirectory.appendingPathComponent("categorized-\(UUID().uuidString).md")
try "---\ncategory: [Tech]\nmicropub_url: https://example.micro.blog/x\n---\n\n# Outside\n\nBody.\n"
.write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
let matter = try PostFrontmatter.parse(readPost(home, post.id))
#expect(PostFrontmatter.categories(in: matter) == ["Tech"])
#expect(matter["micropub_url"] == nil) // the bookkeeping still drops
}
// MARK: S5 — the blog's own categories (q=category)
@Test func `blog categories ride a get to q=category with the bearer token and come from the categories array`() async throws {
let log = MicropubRequestLog()
let body = #"{"categories": ["Travel", " Photos ", ""], "microblog-categories": [{"name": "Ignored"}]}"#
let listed = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: body, log: log))
#expect(listed == ["Travel", "Photos"])
let request = try #require(log.request(0))
let target = URLComponents(url: request.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
#expect(target?.queryItems == [URLQueryItem(name: "q", value: "category")])
#expect(request.httpMethod == "GET")
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
#expect(request.httpBody == nil)
}
@Test func `blog categories fall back to the detailed list and a bare 2xx is no suggestions`() async {
let log = MicropubRequestLog()
let detailed = #"{"microblog-categories": [{"name": "Travel"}, {"name": " "}, {"url": "https://micro.blog/c/x", "name": "Photos"}]}"#
let fallback = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: detailed, log: log))
#expect(fallback == ["Travel", "Photos"])
let bare = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: "{}", log: log))
#expect(bare == [])
}
@Test func `a 401 and a transport throw are no suggestions never an error`() async {
let log = MicropubRequestLog()
let deniedBody = #"{"error":"forbidden","error_description":"token not authorized"}"#
let denied = await Micropub.blogCategories(token: "tok", transport: micropubCanned(401, body: deniedBody, log: log))
#expect(denied == []) // a rejected token surfaces on the send itself
let dead: Micropub.Transport = { _ in throw URLError(.notConnectedToInternet) }
let unreachable = await Micropub.blogCategories(token: "tok", transport: dead)
#expect(unreachable == [])
}
// MARK: S6 — publish applies pending edits first
@Test @MainActor func `publish with a category edit updates first then flips the status`() async throws {
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/drafted"
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
let log = MicropubRequestLog()
let transport = micropubCanned(200, log: log)
let outcome = await model.micropubPublish(url: url, token: "tok", categories: ["Essays"], transport: transport)
#expect(outcome == .published)
// TWO requests, in order: the update carrying the edit, THEN the post-status publish.
#expect(log.requests.count == 2)
let replace = try updateReplace(log, 0)
#expect(replace["category"] as? [String] == ["Essays"])
let publish = try #require(log.request(1))
let flip = try #require(micropubJSON(publish)["replace"] as? [String: Any])
#expect(flip["post-status"] as? [String] == ["published"])
#expect(flip["category"] == nil)
let disk = try readPost(home, id)
#expect(PostFrontmatter.parse(disk)["category"] == "[Essays]")
}
@Test @MainActor func `a failed update half never publishes`() async throws {
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/gone"
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
let log = MicropubRequestLog()
// Micro.blog answers 404 to the update: the post is gone there.
let outcome = await model.micropubPublish(url: url, token: "tok", categories: ["Essays"], transport: micropubCanned(404, log: log))
// The update's own outcome (#206: the piece forgot the dead link).
guard case .forgotten = outcome else {
Issue.record("expected forgotten, got \(outcome)")
return
}
// ONE request — the update half; the publish never went out (the
// count says so: a publish that leaked would still answer 404).
#expect(log.requests.count == 1)
let only = try #require(log.request(0))
let replace = try #require(micropubJSON(only)["replace"] as? [String: Any])
#expect(replace["category"] as? [String] == ["Essays"])
#expect(replace["post-status"] == nil)
let forgotten = try #require(Post.scan(home: home).first)
#expect(forgotten.micropubURL == nil)
// The edit stayed on the piece: the next send (a fresh draft) carries it.
let disk = try readPost(home, id)
#expect(PostFrontmatter.parse(disk)["category"] == "[Essays]")
}
@Test @MainActor func `publish targets the post the send updated never the caller's stale url`() async throws {
// The sheet's URL comes from the scan at open; the piece on disk
// remembers another (edited by hand meanwhile). The edit and the
// status flip must land on the SAME post — the one the send touched.
let (model, home) = try makeModelHome()
let id = try openPiece(model, home, frontmatter: "micropub_url: https://example.micro.blog/live\n")
let log = MicropubRequestLog()
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/stale", token: "tok", categories: ["Essays"], transport: micropubCanned(200, log: log),
)
#expect(outcome == .published)
let flip = try #require(log.request(1))
#expect(micropubJSON(flip)["url"] as? String == "https://example.micro.blog/live")
// And the stamp never overwrites the real memory with the stale address.
#expect(try PostFrontmatter.parse(readPost(home, id))["micropub_url"] == "https://example.micro.blog/live")
}
@Test @MainActor func `publish follows a fresh draft when the send had to create one`() async throws {
// No remembered post on disk (an earlier stamp failed), so the send
// creates a draft; the publish flips THAT post, and the piece remembers it.
let (model, home) = try makeModelHome()
let id = try openPiece(model, home)
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/fresh"], log: log)
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/stale", token: "tok", categories: ["Essays"], transport: transport,
)
#expect(outcome == .published)
let flip = try #require(log.request(1))
#expect(micropubJSON(flip)["url"] as? String == "https://example.micro.blog/fresh")
#expect(try PostFrontmatter.parse(readPost(home, id))["micropub_url"] == "https://example.micro.blog/fresh")
}
// MARK: S7 — the sheet field's pending-edit rule (pure)
@Test func `a category edit is pending only when the field's list differs from the settled one`() {
#expect(MicropubCategoryField.pendingCategories(field: "Tech, Notes", settled: "Tech, Notes") == nil)
// A trailing comma is not an edit.
#expect(MicropubCategoryField.pendingCategories(field: "Tech, Notes,", settled: "Tech, Notes") == nil)
// Clearing a piece that had a line sends `category: []`.
#expect(MicropubCategoryField.pendingCategories(field: "", settled: "Tech") == [])
#expect(MicropubCategoryField.pendingCategories(field: "Tech", settled: "") == ["Tech"])
// A piece without a line never gains an empty key.
#expect(MicropubCategoryField.pendingCategories(field: "", settled: "") == nil)
}
// MARK: S8 — picks add (the whole-text completion IS the merge) + the menu (pure)
@Test func `the partial word is the last comma segment with its quotes off`() {
#expect(MicropubCategoryField.partial("Tech, ") == "")
// A quoted comma is not a separator — the segment is the one name.
#expect(MicropubCategoryField.partial("Tech, \"Tech, general\"") == "Tech, general")
}
@Test func `the menu lists the whole blog for an empty field in blog order`() {
#expect(MicropubCategoryField.suggestions(text: "", blog: Self.blog)
== ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"])
}
@Test func `the menu narrows to the case-insensitive prefix of the half-typed word`() {
#expect(MicropubCategoryField.suggestions(text: "te", blog: Self.blog) == ["Tech", "Tech, general"])
#expect(MicropubCategoryField.suggestions(text: "Tech, Te", blog: Self.blog) == ["Tech, general"])
}
@Test func `the menu offers everything else once the last word is a finished category`() {
#expect(MicropubCategoryField.suggestions(text: "Tech", blog: Self.blog)
== ["Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"])
}
@Test func `the menu never offers a name already in the field`() {
#expect(MicropubCategoryField.suggestions(text: "notes, swift", blog: Self.blog)
== ["Tech", "Essays", "Fieldwork", "Tech, general", "SwiftUI"])
}
@Test func `the menu stays open after a pick of a comma-containing name`() {
// The field reads `Tech, "Tech, general"` — the quoted last word is the finished name, so everything else is offered.
#expect(MicropubCategoryField.suggestions(text: "Tech, \"Tech, general\"", blog: Self.blog)
== ["Notes", "Essays", "Fieldwork", "Swift", "SwiftUI"])
}
@Test func `a pick into an empty field is the name`() {
#expect(MicropubCategoryField.completion(text: "", picking: "Tech", blog: Self.blog) == "Tech")
}
@Test func `a pick adds after a finished name`() {
#expect(MicropubCategoryField.completion(text: "Tech", picking: "Notes", blog: Self.blog) == "Tech, Notes")
}
@Test func `a pick adds after a quoted name and keeps its quotes`() {
#expect(MicropubCategoryField.completion(text: "Tech, \"Tech, general\"", picking: "Notes", blog: Self.blog)
== "Tech, \"Tech, general\", Notes")
}
@Test func `any number of picks keep adding`() {
#expect(MicropubCategoryField.completion(text: "Tech, Notes", picking: "Essays", blog: Self.blog) == "Tech, Notes, Essays")
}
@Test func `a pick replaces the half-typed word`() {
#expect(MicropubCategoryField.completion(text: "Te", picking: "Tech", blog: Self.blog) == "Tech")
}
@Test func `a pick replaces the half-typed word after a comma`() {
#expect(MicropubCategoryField.completion(text: "Tech, No", picking: "Notes", blog: Self.blog) == "Tech, Notes")
}
@Test func `a finished name stays when the pick only extends it`() {
#expect(MicropubCategoryField.completion(text: "Tech", picking: "Tech, general", blog: Self.blog) == "Tech, \"Tech, general\"")
}
@Test func `a pick replaces a half-typed shared prefix`() {
#expect(MicropubCategoryField.completion(text: "Sw", picking: "SwiftUI", blog: Self.blog) == "SwiftUI")
}
@Test func `a pick never adds a present name twice`() {
#expect(MicropubCategoryField.completion(text: "Tech, Notes", picking: "Notes", blog: Self.blog) == "Tech, Notes")
}
@Test func `a half-typed duplicate of an earlier name collapses to it`() {
#expect(MicropubCategoryField.completion(text: "Notes, No", picking: "Notes", blog: Self.blog) == "Notes")
}
@Test func `a custom name stays when a known one is picked`() {
#expect(MicropubCategoryField.completion(text: "MyNewCat", picking: "Notes", blog: Self.blog) == "MyNewCat, Notes")
}
}
+6 -11
View File
@@ -88,15 +88,11 @@ struct MicropubModelTests {
#expect(Post.scan(home: home).first?.micropubURL == nil)
}
@Test @MainActor func `frontmatter category never travels`() async throws {
@Test @MainActor func `frontmatter category travels`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home)
model.select(post.id)
// The writer's own category frontmatter — permitted, inert.
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\ncategory: Essays\n")
.write(to: fileURL, atomically: true, encoding: .utf8)
// The writer's own category frontmatter — #207: a bare scalar
// is ONE category, and it rides the create as `category`.
try model.select(plantedPiece(home, frontmatter: "category: Essays\n"))
let log = MicropubRequestLog()
_ = await model.micropubSend(
@@ -105,9 +101,8 @@ struct MicropubModelTests {
)
let request = try #require(log.requests.first)
let wire = String(bytes: request.httpBody ?? Data(), encoding: .utf8) ?? ""
#expect(!wire.lowercased().contains("category"))
#expect(!wire.contains("Essays"))
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
#expect(props["category"] as? [String] == ["Essays"])
}
@Test @MainActor func `a failed draft stamps nothing`() async throws {
+16 -2
View File
@@ -10,8 +10,9 @@
// confirms publish
// Then Micro.blog receives an h=entry create (markdown content, name,
// post-status=draft) followed by an update flipping post-status to
// published — the piece's frontmatter `category:` never travels, and
// the draft URL is remembered on the piece.
// published; #207: the piece's `category:` list rides the create (its
// own pins: MicropubCategoryTests) — and the draft URL is remembered
// on the piece.
//
// Wire facts live-verified against microblog.dev/api/posting and
// Micro.blog's Micropub docs (2026-10-31): JSON create reads
@@ -85,6 +86,19 @@ nonisolated func micropubJSON(_ request: URLRequest) -> [String: Any] {
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
}
/// A saved `# Titled` piece carrying `frontmatter` planted after the
/// owned keys (a `category:` or `micropub_url:` line) — its id. The
/// anchor is `origin: writer`, the last key `writeNew` stamps.
nonisolated func plantedPiece(_ home: URL, frontmatter: String = "") throws -> String {
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
guard !frontmatter.isEmpty else { return post.id }
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
try String(contentsOf: fileURL, encoding: .utf8)
.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
.write(to: fileURL, atomically: true, encoding: .utf8)
return post.id
}
@Suite("MicropubTests")
struct MicropubTests {
// MARK: Request shapes (the wire contract)
+1 -1
View File
@@ -119,7 +119,7 @@ From the 2026-08-28 sessions (Sudowrite/Muse learnings; issues #9, #10). None of
### Publish path (M6)
- **S6.1 — Draft then publish.** As the writer, I send a post to Micro.blog as a draft first, then publish. *AC:* `POST /micropub` with `h=entry`, markdown `content`, `name` for the title, `post-status=draft` → publish; Bearer app-token auth — token in Keychain, entered once; no OAuth in v1; frontmatter `category:` is permitted but inert in v1 (never sent) — v2 fetches existing categories and allows creating new.
- **S6.1 — Draft then publish.** As the writer, I send a post to Micro.blog as a draft first, then publish. *AC:* `POST /micropub` with `h=entry`, markdown `content`, `name` for the title, `post-status=draft` → publish; Bearer app-token auth — token in Keychain, entered once; no OAuth in v1; frontmatter `category:` travels since #207 — the publish sheet's Categories field offers the blog's existing categories (fetched), and a name Micro.blog doesn't know is created when the post is sent.
- **S6.2 — Illustrations travel with it.** As the writer, illustrations upload and attach with alt text. *AC:* `q=config` → media-endpoint → multipart PNG upload → `202` + `Location` URL → attached as `photo` with `mp-photo-alt`; publish never sends a photo without alt text — the only floor, style judgment stays with the author.
### Research & library-light (M5)
@@ -0,0 +1,92 @@
# Micro.blog categories travel with the piece (#207)
> **Date:** 2026-12-04
> **Type:** issue
> **Reference:** [#207 — Allow setting and creating Micro.blog categories](https://git.babylondreams.de/AlexKucera/museion/issues/207) (a title-only ticket — the spec was grilled in session: eight decisions, D1–D8)
## Goal
A piece could carry no Micro.blog categories: the send left the post unclassified and the writer had to file it on the web. Make the piece's categories part of the piece — set and created from the publish sheet — and let them travel with every send.
## What Was Done
- Grilling first (two rounds, every question owner-answered in session) → eight decisions (D1–D8, below). A throwaway prototype of three controls (`prototypes/MicropubCategoriesPrototype.swift`, kept beside the other prototypes) settled the control live: the owner ruled variant B while clicking it.
- `PostFrontmatter.swift` — the one-line `category:` list codec: `categorySegments` (the ONE quote-aware comma-list scanner), `categoryList` / `categoryListValue` (the unbracketed read and render), `categories(in:)` / `categoryValue` (the bracketed frontmatter forms). Line-bounded: newlines and control characters strip before the sink; names holding `, [ ] " \` ride quoted with backslashes and quotes escaped; empties drop; the first occurrence wins (a `Set`).
- `MicropubCategories.swift` (new) — `GET /micropub?q=category`: `makeCategoryListRequest`, `blogCategories(token:transport:) async -> [String]` (the root `categories` strings, else the `microblog-categories` objects' `name` fields; trimmed; any failure or non-2xx is `[]`).
- `Micropub.swift` — the wire: `makeDraftRequest(title:body:token:categories:)` carries `category` only when non-empty; `makeUpdateRequest(…, categories: [String]? = nil)` — nil is the #206 body byte for byte, `[]` is sent and clears; `sendDraft(categories:)`, `update(categories:)`. The model: `micropubSend(token:categories:…)` lands a pending edit as the piece's line FIRST (a failed write refuses with nothing on the wire), then one disk read feeds the wire; `updateRememberedOrCreate` (opt-in by key); `stampCategories`; `micropubPublish(url:token:categories:…)` runs the send first and flips the post that send touched; `openPieceCategories()` (the sheet's read of the open piece, never the scan snapshot).
- `MicropubMedia.swift` — `queryRequest(_:token:)` is the one `GET <endpoint>?q=…` builder (config and the category list).
- `PostStore.swift` — doc only: `stampMicropub` now also stamps the `category:` line (`[]` renders `category: []`); on a 404 the micropub lines still go.
- `MicropubPublishSheet.swift` — the **Categories** field: a comma list in the codec's unbracketed form with the system completion menu over the blog's categories (fetched when the sheet opens; a failed fetch is silent). The pure rules live in `MicropubCategoryField`: `pendingCategories` (the pending-edit test), `partial`, `finished`, `suggestions`, `completion`. The view: 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 (`syncSettledFromDisk`).
- Tests — new `MicropubCategoryTests` (39 pins, S1–S8: create, re-send opt-in, the codec, apply-at-send + the refusal + the import, the blog list, publish-applies-first + the publish target, the field's pending rule, picks-add + the menu). `MicropubModelTests`: the old "frontmatter category never travels" pin flipped to `frontmatter category travels`. `MicropubTests`: header; the shared `plantedPiece` helper (a saved `# Titled` piece with planted frontmatter).
- Reviews — two-axis during the build (standards + spec: one real defect and six judgement calls fixed), then finish-audit (ponytail + security + general; see Decisions and Gotchas).
- DOX: `CHANGELOG.md` `[Unreleased]`, `PRD.md` S6.1, root `AGENTS.md` (learnings), `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `GLOSSARY.md` (Category).
**Verification (finish-up gates, each decided by its own exit code):** `swiftformat . --lint` — 0/157 files require formatting, exit 0. `swiftlint . --strict` — 0 violations in 146 files, exit 0. `./scripts/full-test.sh` — **791 executed / 791 passed / 0 failed** (run dir `_build/full-test/20261205T070414Z-Museion`; 752 at session start → +39 new pins, one existing pin flipped).
**Flip cycle:** eight batches on the uncommitted tree (pristine copies + `cmp` on restore, byte-exact every time). Before the reviewer fanout: A the codec (split, dedupe, bare scalar, quoting, control-char strip) · B create/opt-in/stamp/blog list (six guards) · C update builder/publish/create-eager · D–F the sheet field (partial, dup, half-typed, pending; present/finished/prefix/never-append; the two-mechanism empty-field pin) · G the three guards the earlier batches had masked. After the audit fixes: H (backslash escape, touched target, fresh target, sanitize strip, disk read, bare scalar). **39 of 40 pins were watched fail on their own guard**, nothing else red except where predicted. The hold-out is `a refused send with a category edit writes nothing` — an ordering pin whose guard also supplies the data the write would need, so no flip can redden it.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Creation is implicit on Micro.blog — no separate create call or UI (D1) | Naming a category Micro.blog does not know in the create/update creates it there. A second step would be a second click for the same outcome. |
| The control is variant B: a comma-separated field plus the native completion menu (`textInputSuggestions` / `textInputCompletion`, macOS 15+) (D2) | Three controls were prototyped live. A visible chip row does not scale to the owner's many categories; an NSTokenField fights the completion system. The owner ruled B while clicking it. |
| A pick ADDS; a half-typed last word is replaced; a present name is never offered again | The system REPLACES the whole field text with a completion — so the completion IS the merge. A prototype finding; owner-ruled. |
| `finished` means the last word equals a known blog category; the field compares case-insensitively, the codec exactly | SwiftUI exposes no caret, so the end of the text is the only place a writer can be typing. Case-insensitivity keeps the menu from re-offering `notes` when `Notes` is present; the codec's de-duplication stays exact — ponytail-noted. |
| `partial` strips one pair of surrounding quotes | A just-picked comma-containing name (`"Tech, general"`) must read as finished, or the menu narrows to nothing. |
| One line, `category: [Tech, Notes]`; a bare scalar is one; `[]` is an explicit empty; the codec is line-bounded | The frontmatter sink is line-bounded (#33). Names with commas, brackets, quotes or backslashes ride quoted — the audit closed the backslash gap. |
| Re-sends are opt-in by key (D5) | A piece WITH the line replaces the post's categories with exactly its list (`[]` clears); a piece without one leaves whatever the blog has — the #206 posture survives for every piece that never got a line. |
| The edit lands at the send: guards → flush → category write → ONE disk read → wire; a failed write refuses (D6) | Never a half-state: the wire's names always come from the line on disk. Cancel/Done discard the edit; an unrelated later refusal may leave the line on the piece — documented, and the sheet re-baselines from disk. |
| Publish with a pending edit runs the update first, then flips the post that send touched (D7) | A failed update returns its outcome with NO publish — disk and blog never disagree. The audit made the target the touched post: the sheet's URL can be stale against the disk, and flipping it would also have stamped the stale address over the real memory. |
| After any failed step only the pending BASELINE re-syncs from disk; the field keeps its text | The send writes before the wire, so a later clear of the field must still count as an edit (the first review's stale-baseline defect). |
| Import keeps an imported `category:` line (D8) | It is the writer's classification, not Museion's bookkeeping — only the micropub keys drop. The writer sees the list in the field before any send. |
| `blogCategories` returns `[String]`; `[]` on any failure | Finish-audit ponytail: the `.failed` payload had no consumer. The sheet is silent by decision; a rejected token surfaces on the send itself. |
| `[String]?` carries nil = no edit versus `[]` = clear; `stampMicropub` keeps its name | Two states with different wire meanings, documented on the parameter; a named enum was deferred. No drive-by rename. |
| De-duplication through a `Set` | Finish-audit security: a hostile 600 KB imported `category:` line cost 16 s on the main actor — at sheet open and on every keystroke. |
| The test plant is one shared helper (`plantedPiece`) | Finish-audit ponytail: four copies of the `origin: writer` anchor would have to change together. The two pre-existing copies outside this diff stay until touched. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| After a failed publish-with-edit, a later CLEAR of the field read as "no edit" and was silently dropped | The pending baseline was captured at sheet open; the failed send had already written the line | `fail()` → `syncSettledFromDisk()` (baseline only; the typed text stays). Found by the first review, pinned by the clearing pins. |
| A name ending in a backslash, or holding `\"`, re-parsed as ONE junk name and swallowed the next | The renderer escaped only `"`, while the scanner honored every `\` as an escape | Escape `\` before `"`; unescape both; a backslash triggers quoting. Audit — security and general converged, probe-confirmed; pinned by the round-trip. |
| `micropubPublish` flipped the CALLER's URL, not the post the update touched | `case .updated: break` discarded the URL the send returned | `target = touched`. Audit — two angles; two pins (the stale-URL case and the fresh-draft case). |
| Three guards were unproven after their first flip batch | Two flips in one batch reddened the same pins for a different reason: the splitter switched off hid the dedupe; never-append hid the `finished` oracle and the prefix rule | An isolated closing batch per masked guard. A guard is proven only when it is the SOLE explanation of a red pin. |
| Two of the listed flip edits did not compile (`filter { true }`; `if let x = x ?? []`) | Closure argument lists cannot be implicitly ignored; a conditional binding needs an Optional | Compile-equivalent forms: `{ _ in true }`, `as [String]?`. |
| The TUI shell wedged mid-session (every command timed out, `echo` included) and `execute_code` was blocked in delegation-triggered turns | — | The rail and the flip runs were delegated to children with their own terminals; one child's shell wedged too and fell back to detached subprocesses from its `execute_code` kernel. `read_file` / `search_files` never failed. |
| `swift-test-results.py` died with `NameError: sys` | The skill script never imported `sys` | The one-line import was added to the skill. |
| The xcresult summary's device-level `passedTests` reads total + 1 | The dynamic-parameter statistic (pre-existing) | The top-level `totalTestCount` and the rail's own line are authoritative. |
| A stub proves less than a flip | The sheet pins' first red came against a constant stub — that only proves a pin reads the function, not that each rule discriminates | The field's interaction pins were proven guard by guard in batches D–G. |
| A child's first attempt to read the suite log undercounted by one (50 rows for 51 tests) | An xcodebuild progress line split one status line | Bundle counts, never log-line tallies. |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/PostFrontmatter.swift` | The one-line `category:` codec: `categorySegments`, `categoryList`, `categoryListValue`, `categories(in:)`, `categoryValue`, the unescape helper |
| `Museion/MicropubCategories.swift` | New — `GET /micropub?q=category`, `blogCategories(token:)` |
| `Museion/Micropub.swift` | Category on the create/update builders; `micropubSend(categories:)`, `micropubPublish(categories:)`, `openPieceCategories()`, `stampCategories`, `updateRememberedOrCreate` |
| `Museion/MicropubMedia.swift` | `queryRequest(_:token:)` — the one `GET ?q=` builder |
| `Museion/MicropubPublishSheet.swift` | The Categories field (`MicropubCategoryField` + the view wiring) |
| `Museion/PostStore.swift` | Doc: `stampMicropub` stamps the `category:` line |
| `MuseionTests/MicropubCategoryTests.swift` | New — 39 pins, S1–S8 |
| `MuseionTests/MicropubModelTests.swift` | The "category travels" pin flipped; rides `plantedPiece` |
| `MuseionTests/MicropubTests.swift` | Header; the shared `plantedPiece` helper |
| `prototypes/MicropubCategoriesPrototype.swift` | New — the throwaway three-control prototype (`--selftest`, `PROTO_MANY=1`) |
| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass: contracts, suite map, learnings |
| `CHANGELOG.md`, `PRD.md`, `GLOSSARY.md` | The feature; S6.1; the Category term |
| `docs/devlog/` | This log; `INDEX.md` row; the `AGENTS.md` window |
## Open Items & Next Steps
- [ ] Owner to try the live completion menu in the app — hosted tests cannot exercise the SwiftUI wiring: open a saved post → Publish → Categories.
- [ ] Ticket candidate: a pick rewrites the field from its end (SwiftUI exposes no caret) — a visible-chips v2 if caret-mid-text bites.
- [ ] Ticket candidate: Convert to Post rebuilds the frontmatter block and drops every foreign key, a piece's `category:` line included (#114 posture; the same class as the #206 note).
- [ ] Unverified wire fact: the `microblog-categories` fallback shape is cited from Micro.blog's docs, never observed on the wire.
- [ ] Named ceilings, no action: blog-side duplicate names in the suggestions (`ForEach(id: \.self)`); an imported empty `category:` line makes later re-sends clear the blog's categories (opt-in by key).
- [ ] The two pre-existing plant copies in `MicropubStatusTests` / `MicropubTests` can ride `plantedPiece` when next touched.
---
*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 -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-12-04 | issue | [20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md](20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md) | Micro.blog categories travel with the piece; comma field with native completion; publish targets the post the send touched (rail 791/791) |
| 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-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 |
@@ -0,0 +1,431 @@
// PROTOTYPE — #207 "Allow setting and creating Micro.blog categories". THROWAWAY; not part of the app target.
// Build: swiftc -O -parse-as-library prototypes/MicropubCategoriesPrototype.swift -o /tmp/micropub_categories_proto
// Run: copy the binary into /tmp/MicropubCategoriesProto.app/Contents/MacOS/ (Info.plist: CFBundleExecutable=
// micropub_categories_proto, CFBundlePackageType=APPL) and `open` that bundle — a bare binary never gets
// real keyboard activation. `<binary> --selftest` runs the field-text ↔ list contract checks and exits.
// Under test: which control carries the publish sheet's editable "Categories" field (suggestions = the blog's
// existing categories). ONE binary, THREE windows around the SAME mock of MicropubPublishSheet — only the
// control differs:
// A — comma field + a visible "On your blog:" row of link-styled category buttons
// B — comma field + the native completion menu (.textInputSuggestions)
// C — AppKit NSTokenField (Mail-style tokens + the delegate completion menu)
// Each window's mono state line is exactly what the control would write to the piece's frontmatter (contract
// below). Launch env PROTO_SEED=1 pre-fills all three with every dummy category, PROTO_B_TEXT=Te pre-types and
// focuses B's field, PROTO_MANY=1 swaps in ~40 categories (screenshot scenarios); default is empty/five.
import AppKit
import SwiftUI
// MARK: - Tokens (inlined from Museion/DesignTokens.swift)
enum Tok {
static let background = Color(red: 0xFA / 255, green: 0xF9 / 255, blue: 0xF3 / 255)
static let muted = Color(red: 0x6B / 255, green: 0x69 / 255, blue: 0x64 / 255)
static let accent = Color(red: 0xC9 / 255, green: 0x64 / 255, blue: 0x42 / 255)
/// The sheet's label/note face and its field face (MicropubPublishSheet).
static let monoNote = Font.system(size: 11, design: .monospaced)
static let monoField = Font.system(size: 12, design: .monospaced)
}
// MARK: - #207 contract: field text ↔ list ↔ frontmatter
/// Quote-aware comma split — the field's elements (a comma inside double quotes does not split).
func commaSplit(_ text: String) -> [String] {
var parts: [String] = []
var current = ""
var quoted = false
for char in text {
if char == ",", !quoted {
parts.append(current)
current = ""
} else {
if char == "\"" {
quoted.toggle()
}
current.append(char)
}
}
parts.append(current)
return parts
}
/// Field text → list: split on commas OUTSIDE double quotes, trim, strip one surrounding quote pair, drop
/// empties, de-duplicate (first occurrence wins).
func parseCategories(_ text: String) -> [String] {
var seen = Set<String>()
return commaSplit(text).compactMap { part in
var name = part.trimmingCharacters(in: .whitespacesAndNewlines)
if name.count >= 2, name.hasPrefix("\""), name.hasSuffix("\"") {
name = String(name.dropFirst().dropLast())
}
guard !name.isEmpty, seen.insert(name).inserted else { return nil }
return name
}
}
/// List → frontmatter line: a name carrying `,` `[` `]` or `"` is wrapped in double quotes, inner `"` escaped.
func frontmatterLine(_ names: [String]) -> String {
let cells = names.map { name in
name.contains(where: { ",[]\"".contains($0) }) ? "\"" + name.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : name
}
return "category: [" + cells.joined(separator: ", ") + "]"
}
func stateLine(_ names: [String]) -> String {
names.isEmpty ? "No categories → category: []" : "Travels as → " + frontmatterLine(names)
}
/// A name as written into the comma FIELD (A/B): quoted when it carries a comma, so the parser reads it back.
func fieldForm(_ name: String) -> String {
name.contains(",") ? "\"\(name)\"" : name
}
/// The word being typed: the last element of the quote-aware split, trimmed and quote-stripped like a
/// parsed name ("" when the field is empty or ends with a comma).
func partial(_ text: String) -> String {
let last = commaSplit(text).last?.trimmingCharacters(in: .whitespaces) ?? ""
guard last.count >= 2, last.hasPrefix("\""), last.hasSuffix("\"") else { return last }
return String(last.dropFirst().dropLast())
}
func sameName(_ a: String, _ b: String) -> Bool {
a.caseInsensitiveCompare(b) == .orderedSame
}
/// The last thing typed is itself a known category → nothing is half-typed.
func finished(_ text: String, blog: [String]) -> Bool {
blog.contains { sameName($0, partial(text)) }
}
/// B's menu: every category while nothing is typed or the last word is a finished category, else the
/// prefix matches (blog order kept); present names are never offered.
func suggestions(text: String, blog: [String]) -> [String] {
let names = parseCategories(text)
let p = partial(text)
let candidates = (p.isEmpty || finished(text, blog: blog)) ? blog : blog.filter { $0.lowercased().hasPrefix(p.lowercased()) }
return candidates.filter { name in !names.contains { sameName($0, name) } }
}
/// B — what the field becomes when `name` is picked. The system replaces the WHOLE text with the
/// completion, so the completion IS the merge: a pick ADDS (never duplicates); a half-typed word goes.
/// Pure (field text, picked name, blog) → String; ported into the real sheet and unit-tested there.
func completion(text: String, picking name: String, blog: [String]) -> String {
var names = parseCategories(text)
let p = partial(text)
let halfTyped = !p.isEmpty && !finished(text, blog: blog) && name.lowercased().hasPrefix(p.lowercased()) && !sameName(p, name)
if halfTyped, let last = names.last, sameName(last, p) {
names.removeLast()
}
if !names.contains(where: { sameName($0, name) }) {
names.append(name)
}
return names.map(fieldForm).joined(separator: ", ")
}
/// `--selftest`: the contract above, run for real (asserts are compiled out under -O).
func contractSelfCheck() -> Never {
let blog = ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general"]
let swiftBlog = ["Swift", "SwiftUI"]
let others = ["Notes", "Essays", "Fieldwork", "Tech, general"]
let quotedPick = "Tech, \"Tech, general\""
let checks: [(String, Bool)] = [
("bare text", parseCategories(" Tech, Notes,, tech ") == ["Tech", "Notes", "tech"]),
("quoted comma", parseCategories("\"Tech, general\", Tech") == ["Tech, general", "Tech"]),
("dedupe first wins", parseCategories("Notes, \"Notes\"") == ["Notes"]),
("empties dropped", parseCategories(" \"\" , ") == []),
("line", frontmatterLine(["Tech", "Notes"]) == "category: [Tech, Notes]"),
("quoted line", frontmatterLine(["Tech, general", "a\"b"]) == "category: [\"Tech, general\", \"a\\\"b\"]"),
("empty state", stateLine([]) == "No categories → category: []"),
("state", stateLine(parseCategories("Tech, Notes")) == "Travels as → category: [Tech, Notes]"),
("pick on empty field", completion(text: "", picking: "Tech", blog: blog) == "Tech"),
("pick adds: Tech + Notes", completion(text: "Tech", picking: "Notes", blog: blog) == "Tech, Notes"),
("pick adds again: any number of clicks", completion(text: "Tech, Notes", picking: "Essays", blog: blog) == "Tech, Notes, Essays"),
("pick replaces the half-typed word", completion(text: "Te", picking: "Tech", blog: blog) == "Tech"),
("pick after a comma", completion(text: "Tech, No", picking: "Notes", blog: blog) == "Tech, Notes"),
("pick keeps both Tech and Tech, general", completion(text: "Tech", picking: "Tech, general", blog: blog) == "Tech, \"Tech, general\""),
("pick exact over prefix: Sw + SwiftUI", completion(text: "Sw", picking: "SwiftUI", blog: swiftBlog) == "SwiftUI"),
("pick present name: unchanged", completion(text: "Tech, Notes", picking: "Notes", blog: blog) == "Tech, Notes"),
("pick present name drops the half-typed word", completion(text: "Notes, No", picking: "Notes", blog: blog) == "Notes"),
("pick keeps a new name", completion(text: "MyNewCat", picking: "Notes", blog: blog) == "MyNewCat, Notes"),
("suggestions: empty → all", suggestions(text: "", blog: blog) == blog),
("suggestions: prefix, case-insensitive", suggestions(text: "te", blog: blog) == ["Tech", "Tech, general"]),
("suggestions: finished → every other category", suggestions(text: "Tech", blog: blog) == others),
("suggestions: after a comma only the prefix", suggestions(text: "Tech, Te", blog: blog) == ["Tech, general"]),
("suggestions: a present name is never offered", !suggestions(text: "Notes", blog: blog).contains("Notes")),
("suggestions: after a quoted pick, every other category", suggestions(text: quotedPick, blog: blog) == Array(others.prefix(3))),
]
for check in checks where !check.1 {
print("FAIL: \(check.0)")
}
let failed = checks.filter { !$0.1 }.count
print(failed == 0 ? "contract OK (\(checks.count) checks)" : "contract FAILED (\(failed))")
exit(failed == 0 ? 0 : 1)
}
// MARK: - Mock sheet (mirrors MicropubPublishSheet's idle state; only `control` differs)
enum Variant: String, CaseIterable {
case a, b, c
var id: String {
rawValue.uppercased()
}
var title: String {
switch self {
case .a: "A — comma field + visible row"
case .b: "B — comma field + completion menu"
case .c: "C — token field"
}
}
}
struct SheetMock: View {
let variant: Variant
@Environment(\.openWindow) private var openWindow
@State private var text = "" // A, B
@State private var tokens: [String] = [] // C
/// The writer's existing blog categories — every variant's suggestion source.
static let blogCategories: [String] = isMany ? manyCategories : ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general"]
private static let isMany = ProcessInfo.processInfo.environment["PROTO_MANY"] != nil
/// PROTO_MANY=1: ~40 names at a real blog's scale — shared prefixes (Swift…), two with commas.
private static let manyCategories = [
"Tech", "Notes", "Essays", "Fieldwork", "Tech, general",
"Swift", "SwiftUI", "Swift Testing", "Swift Format", "Swift Concurrency",
"Xcode", "AppKit", "Metal", "macOS", "iOS", "Toolchain", "Builds",
"Design", "Typography", "Accessibility", "Hugo", "Static Sites", "Web",
"Indie Business", "Pricing", "Marketing", "App Store", "Support, email", "Privacy",
"Photography", "Film", "Books", "Reading Notes", "Travel", "Field Notes, abroad",
"Coffee", "Cooking", "Music", "Synths", "Keyboards",
]
/// Suggestions for a partial word (case-insensitive prefix); empty → all five.
static func matches(_ partial: String) -> [String] {
blogCategories.filter { $0.lowercased().hasPrefix(partial.lowercased()) }
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Publish to Micro.blog?")
.font(.headline)
Text("The expected value of showing")
.font(.callout.weight(.semibold))
.lineLimit(2)
Text("Museion sends it as a draft first — nothing goes out until you publish.")
.font(.callout)
.foregroundStyle(Tok.muted)
control
Text(stateLine(variant == .c ? tokens : parseCategories(text)))
.font(Tok.monoNote)
.foregroundStyle(Tok.muted)
Text("Sends with the app token in your Keychain — Settings → Micro.blog manages it.")
.font(Tok.monoNote)
.foregroundStyle(Tok.muted)
HStack {
Button("Publish") {}
.buttonStyle(.borderedProminent)
.disabled(true)
Button("Send as Draft") {}
.buttonStyle(.bordered)
Button("Cancel") {}
.buttonStyle(.bordered)
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding(16)
.frame(width: 340, alignment: .leading)
.frame(width: 340, height: 360, alignment: .topLeading)
.background(Tok.background)
.task {
if variant == .a {
// B last: it ends up the key window, so its field is first responder at launch.
openWindow(id: Variant.c.id)
openWindow(id: Variant.b.id)
}
if ProcessInfo.processInfo.environment["PROTO_SEED"] != nil {
text = Self.blogCategories.map(fieldForm).joined(separator: ", ")
tokens = Self.blogCategories
}
if variant == .b, let typed = ProcessInfo.processInfo.environment["PROTO_B_TEXT"] {
text = typed
}
}
}
@ViewBuilder
private var control: some View {
switch variant {
case .a: CommaField(text: $text, mode: .visibleRow)
case .b: CommaField(text: $text, mode: .completionMenu)
case .c:
VStack(alignment: .leading, spacing: 4) {
FieldLabel()
TokenField(tokens: $tokens)
}
}
}
}
/// The sheet's label face (mono 11 muted) above the field.
struct FieldLabel: View {
var body: some View {
Text("Categories")
.font(Tok.monoNote)
.foregroundStyle(Tok.muted)
}
}
// MARK: - A + B: comma-separated TextField (A: visible link row · B: native completion menu)
struct CommaField: View {
enum Mode { case visibleRow, completionMenu }
@Binding var text: String
let mode: Mode
/// Screenshot scenario only (PROTO_B_TEXT=Te): focuses the pre-typed field so the native menu shows.
@FocusState private var focused: Bool
var body: some View {
VStack(alignment: .leading, spacing: 4) {
FieldLabel()
switch mode {
case .visibleRow:
field
blogRow
case .completionMenu:
field
// The system filters nothing — it lists every view given here (verified: `Te` typed, all
// five provided → five rows). `suggestions` narrows, `completion` is the merged whole text.
.textInputSuggestions {
ForEach(suggestions(text: text, blog: blog), id: \.self) { name in
Text(name).textInputCompletion(completion(text: text, picking: name, blog: blog))
}
}
}
}
.task {
if mode == .completionMenu, ProcessInfo.processInfo.environment["PROTO_B_TEXT"] != nil {
focused = true
}
}
}
private var field: some View {
TextField("Tech, Notes", text: $text)
.textFieldStyle(.roundedBorder)
.font(Tok.monoField)
.focused($focused)
}
private var blog: [String] {
SheetMock.blogCategories
}
/// A: the blog's categories, always visible; a click appends (never duplicates) the name.
private var blogRow: some View {
VStack(alignment: .leading, spacing: 2) {
Text("On your blog:")
.font(Tok.monoNote)
.foregroundStyle(Tok.muted)
HStack(spacing: 10) {
ForEach(SheetMock.blogCategories, id: \.self) { name in
Button(name) { append(name) }
.buttonStyle(.plain)
.foregroundStyle(Tok.accent)
.pointerStyle(.link)
}
}
}
}
private func append(_ name: String) {
var names = parseCategories(text)
guard !names.contains(name) else { return }
names.append(name)
text = names.map(fieldForm).joined(separator: ", ")
}
}
// MARK: - C: NSTokenField (Mail-style tokens + the delegate completion menu)
struct TokenField: NSViewRepresentable {
typealias NSViewType = NSTokenField
@Binding var tokens: [String]
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
/// Mock limitation: inside the representable the field stays one line tall, so wrapped tokens
/// clip at the bottom (Mail grows its field) — `sizeThatFits`/`maximumNumberOfLines` did not
/// change that; not pursued, the owner ruled for B.
func makeNSView(context: Context) -> NSTokenField {
let field = NSTokenField()
field.placeholderString = "Tech, Notes"
field.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
field.tokenStyle = .rounded
field.delegate = context.coordinator
return field
}
func updateNSView(_ field: NSTokenField, context _: Context) {
guard (field.objectValue as? [String] ?? []) != tokens else { return }
field.objectValue = tokens
}
final class Coordinator: NSObject, NSTokenFieldDelegate {
let parent: TokenField
init(_ parent: TokenField) {
self.parent = parent
}
func controlTextDidChange(_ obj: Notification) {
guard let field = obj.object as? NSTokenField else { return }
parent.tokens = field.objectValue as? [String] ?? []
}
func tokenField(
_: NSTokenField, completionsForSubstring substring: String, indexOfToken _: Int,
indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>?,
) -> [Any]? {
selectedIndex?.pointee = 0
return SheetMock.matches(substring)
}
/// The contract's de-duplication at the control: a token already present is not added twice.
func tokenField(_: NSTokenField, shouldAdd tokens: [Any], at _: Int) -> [Any] {
tokens.compactMap { $0 as? String }.filter { !parent.tokens.contains($0) }
}
}
}
// MARK: - App: three windows, tiled apart; A opens its siblings
@main
struct CategoriesPrototypeApp: App {
init() {
if CommandLine.arguments.contains("--selftest") {
contractSelfCheck()
}
// No saved window state: a relaunch would restore B and C, and A's `.task` opens them again.
UserDefaults.standard.register(defaults: ["NSQuitAlwaysKeepsWindows": false])
}
var body: some Scene {
window(.a, x: 0.18)
window(.b, x: 0.5)
window(.c, x: 0.82)
}
/// `Window` (not `WindowGroup`): `openWindow` on an already-open window activates it instead of stacking a twin.
private func window(_ variant: Variant, x: CGFloat) -> some Scene {
Window(variant.title, id: variant.id) { SheetMock(variant: variant) }
.defaultPosition(UnitPoint(x: x, y: 0.5))
.windowResizability(.contentSize)
}
}