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

@@ -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 |