feat(microblog): post summary for Micro.blog

A piece's `summary:` frontmatter line now travels to Micro.blog
beside `category:`. A first send carries the summary when it is not
empty; a re-send replaces the post's summary only when the piece has
the line (opt-in by key; an empty value clears it; no line leaves the
blog's). The same rule as categories, so a piece that never gained
the line cannot blank a summary set on Micro.blog itself.

The publish sheet gains a Summary field and an AI summary button. The
button drafts a first-person teaser from the open piece on a fresh
one-shot engine on the chat profile (the Blind Read's rail — the
resident session is never touched); the reply fills the field for the
writer to edit, and nothing is written until the send stamps the
line. The sheet is modal, so while its own turn runs the button is
the Stop; a Pass or Blind Read that owns the rail disables the button
with the reason on hover and refuses from behind it.

The summary is read off the RAW frontmatter line, never through the
lenient decode — which trims every edge quote — and the read walks
the block the way the lenient reader does. A `split`-based read finds
no block in a mixed-ending file while the lenient reader still sees
the key, and the empty value it answers would have been sent over a
live post's summary.

Reviewed twice (two-axis during the build, three-reviewer
finish-audit after): the mixed-ending read, an unfenced body line
claiming the key, the uncancellable modal turn, and the wrapper rule
eating a teaser's edge quotes were found and fixed before this
commit. Every guard was watched fail on its own pin. Rail 814/814;
SwiftFormat and SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, and the devlog.

Closes #208
This commit is contained in:
AlexKucera committed 2026-12-05 12:32:38 +01:00
1 parent 6db4cf8cf1
commit 36393a9e8e
22 files changed
+1096 -36

No files matched your search

+4 -1
View File
@@ -147,6 +147,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- 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)
- A modal sheet hides every Cancel behind it — a one-shot turn it starts must be stoppable from inside the sheet (the trigger button doubles as Stop) or a hung turn wedges the sheet (#208)
### 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.
@@ -169,6 +170,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- 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)
- A flip that reddens NOTHING means the pin observes a downstream state another guard also holds — assert the guard's own output (`lastError` text), then re-flip; `runningPass == nil` held through the host's one-shot lock while the refusal under test was disabled (#208)
### 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)
@@ -176,6 +178,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- 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)
- Two readers of one frontmatter file must agree on where the block ends — a `split`-based read finds no block in a mixed-ending file while `parse` sees the key, and the `""` it answers rides the wire over a live post (#208)
## Session Logs
@@ -184,6 +187,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-12-05 | [20261205-issue208-post-summary-for-micro-blog_log.md](20261205-issue208-post-summary-for-micro-blog_log.md) |
| 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) |
@@ -193,5 +197,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-12-03 | [20261203-image-drop-27-2-drag-routing-pastes-path_log.md](20261203-image-drop-27-2-drag-routing-pastes-path_log.md) |
| 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) |
<!-- 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 summaries travel (#208) — the piece's `summary:` frontmatter line rides the send beside `category:`. A first send carries the summary when non-empty; a re-send replaces the post's summary only when the piece has the line (no line leaves whatever the blog has; an empty `summary:` clears it) — the same opt-in-by-key rule as categories, so a piece that never gained the line can't blank a summary set on Micro.blog itself. The publish sheet has a **Summary** field (line breaks become spaces, the sink is one line) and an **AI summary** button that drafts a first-person teaser from the open piece on a fresh one-shot engine on the chat profile; the reply fills the field for the writer to edit, nothing is written until the send stamps the line. The edit lands at the send like a category edit (a failed write refuses with nothing on the wire; Publish applies it first). While the turn runs the AI button is the Stop — the sheet is modal, so the pass bar's Cancel sits behind it — and a Pass or Blind Read that owns the one-shot rail disables the button with the reason on hover (and refuses from behind it). The AI button refuses while the piece can't be flushed or the engine isn't ready, with the field's text kept. Import keeps an imported `summary:` line. The field reads its text off the RAW frontmatter line, never through the lenient decode (which trims every edge quote — a teaser's closing `"why"` would vanish through that door), walking the block the way the lenient reader does so a mixed-ending file can't fuse the closing fence onto the last block line (which would have sent an empty summary over a live post's). +23 tests (the wire contract for create and update, the one-line codec incl. quote-bearing round-trips and the mixed-ending and unfenced-body reads, apply-at-send with the failed-write refusal, publish-applies-first, the end-to-end clear, the import keeping the line, the sheet field's trimmed-string pending-edit rule, the prompt and reply cleanup, and the model's summarize turn over the scripted engine incl. refusal, rail-busy refusal, and cancel); each guard was watched fail on its own pin. Suite 814
- **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.
+4
View File
@@ -172,3 +172,7 @@ _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
### Summary
A Micro.blog post summary carried as the Piece's one-line `summary:` frontmatter scalar — a first-person teaser that entices the reader to read the full piece, typed by the writer or drafted by the AI summary button (a one-shot chat-profile engine; the reply fills the field, the writer edits). One line by construction (line breaks become spaces); a value with a quote at either edge renders quoted so the lenient read never trims it. Travels like Category: a create carries it when non-empty, a re-send replaces it only when the line exists, an empty value clears the post's. Import keeps it — the writer's words, unlike the Publish Record keys.
_Avoid_: excerpt (the body is never cut), description, teaser (the field is the summary wherever it came from)
+7 -5
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. #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.
- `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). #208 the one-line `summary:` scalar: `summaryValue(_:)` renders it (every run of whitespace — a newline included — collapses to one space, control characters drop; a value holding a quote or backslash renders QUOTED with both escaped — the category codec's own escape, ONE grammar for both keys) and `summary(inText:)` reads it back off the RAW line, never through `parse`: the lenient decode trims EVERY edge quote, so a teaser's closing `"why"` would vanish through that door — the wire (`updateRememberedOrCreate`, `openPieceSummary`) and the sheet's settle all read the raw line. The read walks the block the way `parse` does (past the opening fence to the next `---`) — NOT via `split`, whose closing-fence check a mixed-ending file defeats (a stray `\r` fuses `---` onto the last block line: `parse` sees the key, `split` sees no block) — and cuts a fused `\r\n---` tail off the value; a BODY line named `summary:` never claims the key (no fence, no block). Empty/blank/absent = `""` — the field's settled empty.
- `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`, #207 the `category:` line, and #208 the `summary:` line a sheet edit writes at the send — `[]` renders `category: []`, a cleared summary renders `summary:` empty; 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,10 @@ 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`, `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.
- `SummaryPrompt.swift` — #208: the AI post summary's prompt vocabulary (pure) — `prompt(title:body:)` carries the Title and body inline and asks for a first-person teaser that entices the reader to read the full piece; `cleaned(_:)` is the reply as the field's text (trimmed, ONE leading `Summary:` label dropped — colon required, so prose opening with the word keeps it; one pair of surrounding quotes stripped; then the codec's round-trip — `summaryValue` → the raw-line read — so the FIELD shows exactly the text the wire will carry, one line, no escapes). The model half is `PostsModelMicropubSummary.swift`; the summary's HOME is the frontmatter `summary:` line the SEND stamps — this half only drafts text for the publish sheet's field.
- 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); #208 the piece's `summary:` line travels the same way — a create carries `properties.summary` ONLY when non-empty, a re-send carries `summary` in `replace` only when the piece has the line (opt-in by key, `""` is sent and CLEARS the post's summary); 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). #208 the sheet's Summary field — the same discipline over the one-line `summary:` scalar: a multi-line `TextEditor` with an `AI summary` button (a bordered small control in the label row) that runs `posts.summarize(mentor:)` — the sheet holds `let mentor: MentorSessionModel` (PostsPaneView passes its own; the ONE construction site) and the reply fills the field for the writer to edit; the button and the field hold still while the turn runs; the button is ALSO disabled while a Pass or Blind Read owns the one-shot rail, with the hover reason saying so (the pass bar's disabled-with-reason idiom — the guard behind it is `guardOpenPieceRun`), and a refusal shows inline with the field's text kept. The sheet is MODAL — the pass bar's Cancel sits behind it — so while this sheet's own summary turn runs the AI button IS the Stop (the spinner stays clickable, `cancelPass` ends the turn on the shared rail); `summarizing` is the MODEL's flag (`PostsModel.summarizing`, the third rider beside `runningPass`/`runningBlindRead`), read by the sheet, the pass bar's Cancel visibility, and `cancelPass`/`guardOpenPieceRun` through the ONE `oneShotRailBusy` predicate — a fourth rider joins the predicate and every site follows. The edit-for-send test is `MicropubSummaryField.pendingSummary` — a STRING compare on trimmed text, so whiLine truncated
- `PostsModelMicropubSummary.swift` — #208: the AI summary's model half — `summarize(mentor:)`: the shared open-piece guard rail (`guardOpenPieceRun`, the brief-28 Home identity) → flush-first → ONE disk read feeds the prompt → `mentor.runSummary` on a fresh one-shot chat-profile engine → `SummaryPrompt.cleaned`. Returns the text or nil with `lastError` naming the blocker; a stale guard refusal never survives into the strip (`lastError` cleared once the guards pass). Writes NOTHING — the text is the publish sheet's to place, and the SEND stamps the `summary:` line.
- `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; #208 a non-nil `summary:` edit lands the same way, sanitized through `summaryValue`) → ONE disk read serves the wire fields, the categories, the summary, and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update (`stampCategories` + `stampSummary` + `updateRememberedOrCreate` are its steps); `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), #207/#208 runs `micropubSend` FIRST when `categories:` or `summary:` 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`).
@@ -86,7 +88,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial `writerQueue` — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown.
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); #208 the AI post summary rides the same rail (`runSummary` — chat profile, label `Summary · <piece>`, the reply read back through `draftCandidateText`; one-shot exclusivity unchanged: a summary refuses while a Pass or Blind Read runs); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm; #204 **Jump** on every non-stale card that still shows an action row (a closed-and-promoted card has none) — leaves reading mode, selects the anchor span in the editor, reveals it, and makes the main window key (the coordinator owns `tv.window`; `NSApp.activate` is a no-op once the palette's click already activated the app)), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). #200: quit FIRST routes through `WritingLockAppDelegate.applicationShouldTerminate`'s departure gate (`AppGateState.init` registers `PostsModel.active`) — a piece that can't depart blocks quit with one spoken reason; willTerminate's `posts.shutdown()` stays as the belt (conflict-held flush + watcher stop).
+1 -1
View File
@@ -525,7 +525,7 @@ private struct PassBarView: View {
/// #122: the Blind Read trigger sits beside Run — advisory-only.
private var actions: some View {
HStack(spacing: 7) {
if posts?.runningPass != nil || posts?.runningBlindRead == true {
if posts?.oneShotRailBusy == true {
MonoButton(title: "Cancel", style: .outline) {
posts?.cancelPass(mentor: model)
}
+21 -4
View File
@@ -912,14 +912,15 @@ extension MentorSessionModel {
return outcome
}
/// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read): a
/// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read,
/// #208 the AI summary): a
/// fresh engine on `profile` via the host (spawn → slim handshake →
/// body → teardown — never resident past the body's end, even on thrown
/// errors), a transient unrostered transcript, one turn. Same lifecycles
/// for both riders — the cancel rail (stopStreaming) and the read-only
/// for all three riders — the cancel rail (stopStreaming) and the read-only
/// composer guard key on the transient entry and need no per-rider
/// branches. `name` ("Pass 1" / "Blind Read") composes the entry label —
/// callers can't pass a title-inconsistent one.
/// branches. `name` ("Pass 1" / "Blind Read" / "Summary") composes the
/// entry label — callers can't pass a title-inconsistent one.
private func runOneShot(profile: String, name: String, prompt: String, pieceTitle: String) async -> TurnOutcome {
guard phase.isReady, !isStreaming, !host.isOneShotRunning, host.binaryPath != nil else { return .failed }
let label = "\(name) · \(pieceTitle)"
@@ -1276,4 +1277,20 @@ extension MentorSessionModel {
}
return nil
}
/// #208: the AI summary — a fresh one-shot engine on the museion
/// profile drafts a teaser from the prompt; the reply text comes
/// back to the caller (nil when the turn did not end normally or
/// said nothing). Never rostered, never saved — the caller owns
/// where the text goes (the publish sheet's field).
func runSummary(prompt: String, pieceTitle: String) async -> String? {
let outcome = await runOneShot(
profile: ProfileSurface.chat.profileName,
name: "Summary",
prompt: prompt,
pieceTitle: pieceTitle,
)
guard case let .ended(stopReason) = outcome, stopReason == "end_turn" else { return nil }
return Self.draftCandidateText(in: transcripts[Self.passTranscriptKey]?.rows ?? [])
}
}
+81 -14
View File
@@ -10,7 +10,11 @@
// 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.
// The blog's own list for the sheet's suggestions: MicropubCategories.swift.
// #208: the piece's `summary:` line TRAVELS the same way — a create
// carries it when non-empty, a re-send carries it in `replace` only
// when the piece has the line ("" clears). The AI half that drafts it
// rides a one-shot engine (SummaryPrompt.swift / PostsModelMicropubSummary.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
@@ -82,16 +86,15 @@ nonisolated enum Micropub {
return request
}
static func makeDraftRequest(title: String, body: String, token: String, categories: [String] = []) -> URLRequest {
static func makeDraftRequest(title: String, body: String, token: String, categories: [String] = [], summary: 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
// illustration refs, which REWRITE to their uploaded URLs on
// the WIRE (position and alt are the writer's; the piece on
// disk never changes). No photo property: it would render
// (GLOSSARY: any carve-out rewrites on the WIRE only — the piece
// on disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// #207: the categories travel — naming one Micro.blog doesn't
// know creates it there; no list, no key.
// #208: the summary travels when non-empty.
var properties: [String: Any] = [
"name": [title],
"content": [body],
@@ -100,6 +103,9 @@ nonisolated enum Micropub {
if !categories.isEmpty {
properties["category"] = categories
}
if !summary.isEmpty {
properties["summary"] = [summary]
}
return jsonPost(["type": ["h-entry"], "properties": properties], token: token)
}
@@ -118,7 +124,17 @@ nonisolated enum Micropub {
/// #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 {
/// #208: `summary` opts the summary into `replace` the same way —
/// a string (even empty: it clears it) is sent as written; nil
/// leaves whatever the post has.
static func makeUpdateRequest(
url: String,
title: String,
body: String,
token: String,
categories: [String]? = nil,
summary: String? = nil,
) -> URLRequest {
var replace: [String: Any] = [
"name": [title],
"content": [body],
@@ -126,6 +142,9 @@ nonisolated enum Micropub {
if let categories {
replace["category"] = categories
}
if let summary {
replace["summary"] = [summary]
}
return jsonPost([
"action": "update",
"url": url,
@@ -144,9 +163,10 @@ nonisolated enum Micropub {
body: String,
token: String,
categories: [String] = [],
summary: String = "",
transport: Transport = urlSessionTransport,
) async -> Outcome {
let request = makeDraftRequest(title: title, body: body, token: token, categories: categories)
let request = makeDraftRequest(title: title, body: body, token: token, categories: categories, summary: summary)
return await run(request, transport: transport, decodeDraftURL: true)
}
@@ -164,16 +184,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. #207:
/// `categories` non-nil also replaces the post's categories.
/// `categories` non-nil also replaces the post's categories. #208:
/// `summary` non-nil also replaces the post's summary.
static func update(
url: String,
title: String,
body: String,
token: String,
categories: [String]? = nil,
summary: String? = nil,
transport: Transport = urlSessionTransport,
) async -> Outcome {
let request = makeUpdateRequest(url: url, title: title, body: body, token: token, categories: categories)
let request = makeUpdateRequest(url: url, title: title, body: body, token: token, categories: categories, summary: summary)
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.
@@ -356,6 +378,19 @@ extension PostsModel {
return PostFrontmatter.categories(in: PostFrontmatter.parse(raw))
}
/// #208: the open piece's summary as it is on DISK — what the
/// publish sheet's field syncs to (the Categories discipline,
/// never the scan snapshot). The raw line read: the lenient parse
/// would trim a teaser's closing quote. No open saved piece or no
/// line → "".
func openPieceSummary() -> 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.summary(inText: raw)
}
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// (name = Title, markdown content). runPass's guard set minus
/// the engine gates (no engine involved); flush-first so the wire
@@ -376,11 +411,17 @@ extension PostsModel {
/// 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.
/// #208: `summary` rides the same posture — nil = no edit, the
/// piece's line is used as written; non-nil = that text is written
/// to the piece FIRST (sanitized to one line), after the flush and
/// before the one disk read. A 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,
summary: String? = nil,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
@@ -392,12 +433,14 @@ extension PostsModel {
if let refused = stampCategories(categories, piece: piece) {
return refused
}
if let refused = stampSummary(summary, 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), the remembered URL, and the categories. No scan
// dependency: the list can lag the open piece.
// GLOSSARY), the remembered URL, the categories, and the summary.
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
@@ -442,6 +485,20 @@ extension PostsModel {
return nil
}
/// #208: the sheet's summary edit lands on the piece HERE — the
/// Categories posture (after the flush, before the one read that
/// feeds the wire). nil is no edit. The refusal when the line
/// cannot land: the send stops here and nothing goes out.
private func stampSummary(_ summary: String?, piece: (id: String, home: URL)) -> Micropub.Outcome? {
guard let summary else { return nil }
do {
try PostStore.stampMicropub(piece.id, home: piece.home, [("summary", PostFrontmatter.summaryValue(summary))])
} catch {
return .refused("Couldn't save this piece's summary — 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
@@ -456,6 +513,11 @@ extension PostsModel {
/// #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.
/// #208: the summary rides the same rule — a create carries it
/// when non-empty; an update carries `summary` only when the piece
/// HAS the line (opt-in by key, `""` clears, no line leaves the
/// blog's). Read off the raw line (`summary(inText:)`): the lenient
/// parse trims a closing quote the teaser may own.
private func updateRememberedOrCreate(
raw: String,
wireBody: String,
@@ -465,6 +527,7 @@ extension PostsModel {
) async -> Micropub.Outcome {
let matter = PostFrontmatter.parse(raw)
let title = Post.title(of: raw)
let summaryLine = matter["summary"] != nil
if let remembered = Micropub.rememberedURL(matter) {
let outcome = await Micropub.update(
url: remembered,
@@ -472,6 +535,7 @@ extension PostsModel {
body: wireBody,
token: token,
categories: matter["category"] != nil ? PostFrontmatter.categories(in: matter) : nil,
summary: summaryLine ? PostFrontmatter.summary(inText: raw) : nil,
transport: transport,
)
if case .requestFailed(404, _) = outcome {
@@ -484,6 +548,7 @@ extension PostsModel {
body: wireBody,
token: token,
categories: PostFrontmatter.categories(in: matter),
summary: PostFrontmatter.summary(inText: raw),
transport: transport,
)
if case let .drafted(url, _) = outcome {
@@ -508,10 +573,12 @@ extension PostsModel {
/// 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.
/// #208: `summary` rides the same applies-first posture.
func micropubPublish(
url: String,
token: String,
categories: [String]? = nil,
summary: String? = nil,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
@@ -521,8 +588,8 @@ extension PostsModel {
return .refused("That post address isn't a clean https URL — nothing was sent or remembered.")
}
var target = url
if let categories {
switch await micropubSend(token: token, categories: categories, transport: transport) {
if categories != nil || summary != nil {
switch await micropubSend(token: token, categories: categories, summary: summary, transport: transport) {
case let .updated(touched):
target = touched
case let .drafted(fresh, _):
+135 -4
View File
@@ -28,6 +28,12 @@
// 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).
// #208: a Summary field — the piece's `summary:` scalar, typed or
// drafted by the `AI summary` button (a one-shot chat-profile
// engine; the reply fills the field, the writer edits). Same
// discipline as Categories: the edit lands AT THE SEND, the field
// syncs on open/forget and settles from disk after a send. While the
// turn runs the button is the sheet's own Stop (the sheet is modal).
//
import SwiftUI
@@ -108,9 +114,25 @@ nonisolated enum MicropubCategoryField {
}
}
/// #208: the publish sheet's Summary field — its pure rules. The
/// edit-for-send test is a STRING compare (not a list), so a
/// trailing-space difference is not an edit and equal empties stay
/// nil (a piece without a line never gains an empty key).
nonisolated enum MicropubSummaryField {
/// The sheet's edit for the model: nil when the field IS the
/// settled one (both trimmed — whitespace alone is not an edit);
/// else the field's text ("" = cleared — the model writes
/// `summary:` empty and the re-send clears the post's).
static func pendingSummary(field: String, settled: String) -> String? {
let f = field.trimmingCharacters(in: .whitespacesAndNewlines)
return f == settled.trimmingCharacters(in: .whitespacesAndNewlines) ? nil : f
}
}
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
let mentor: MentorSessionModel
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
@@ -147,6 +169,11 @@ struct MicropubPublishSheet: View {
/// 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
/// #208: the Summary field as typed, and the text it rests on (the
/// disk read on open, or a successful send's canonical form — the
/// pending-edit baseline).
@State private var summaryField = ""
@State private var settledSummaryField = ""
/// Token entry shows when none is saved — or again after an auth
/// failure (the entered-once token can be replaced, never a dead end).
@@ -163,6 +190,11 @@ struct MicropubPublishSheet: View {
MicropubCategoryField.pendingCategories(field: categoryField, settled: settledCategoryField)
}
/// #208: the Summary field's edit for the send — nil when nothing changed.
private var pendingSummary: String? {
MicropubSummaryField.pendingSummary(field: summaryField, settled: settledSummaryField)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
@@ -196,6 +228,43 @@ struct MicropubPublishSheet: View {
.foregroundStyle(DesignTokens.muted)
}
// #208: the Summary field, in every phase — a send is possible in all of them.
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 6) {
Text("Summary")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer()
Button {
draftSummary()
} label: {
if summarizing {
ProgressView().controlSize(.small)
} else {
Text("AI summary")
}
}
.buttonStyle(.bordered)
.controlSize(.small)
// Disabled-with-reason (the pass bar's idiom) while ANOTHER
// rider owns the rail or a send runs — but never while this
// sheet's own summary turn runs: the spinner is the Stop.
.disabled(busy || (!summarizing && posts.oneShotRailBusy))
.help(summarizing ? "Stop the summary turn." : summaryButtonHelp)
.accessibilityLabel(summarizing ? "Stop summary" : "AI summary")
}
TextEditor(text: $summaryField)
.font(.system(size: 11, design: DesignTokens.mono))
.frame(height: 72)
.scrollContentBackground(.hidden)
.background(RoundedRectangle(cornerRadius: 6).stroke(DesignTokens.muted.opacity(0.35)))
.disabled(busy || posts.summarizing)
.accessibilityLabel("Summary")
Text("Shown by Micro.blog in feeds and cross-posts. One or two sentences, first person — line breaks become spaces.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if showsTokenField {
SecureField("App token", text: $tokenField)
.textFieldStyle(.roundedBorder)
@@ -265,7 +334,7 @@ struct MicropubPublishSheet: View {
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding(16)
.frame(width: 340, alignment: .leading)
.frame(width: 420, alignment: .leading)
.onAppear {
// A piece sent in an earlier session still has its record:
// the remembered URL, and (#206) its publish stamp.
@@ -276,6 +345,7 @@ struct MicropubPublishSheet: View {
publishedAt = post.micropubPublished
phase = settledPhase
syncFieldFromDisk()
syncSummaryFromDisk()
loadSuggestions()
}
}
@@ -356,6 +426,7 @@ struct MicropubPublishSheet: View {
refusal = message
phase = settledPhase
syncSettledFromDisk()
syncSettledSummaryFromDisk()
}
/// Step 1 — the model decides create-vs-update by the piece's
@@ -369,7 +440,7 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = postURL == nil ? .drafting : .updating
Task {
switch await posts.micropubSend(token: token, categories: pendingCategories) {
switch await posts.micropubSend(token: token, categories: pendingCategories, summary: pendingSummary) {
case let .drafted(url, preview):
postURL = url
previewURL = preview
@@ -401,11 +472,12 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = .publishing
Task {
switch await posts.micropubPublish(url: url, token: token, categories: pendingCategories) {
switch await posts.micropubPublish(url: url, token: token, categories: pendingCategories, summary: pendingSummary) {
case .published:
publishedAt = Date()
phase = .published
settle()
syncSummaryFromDisk()
case let .authFailed(detail):
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
@@ -433,6 +505,7 @@ struct MicropubPublishSheet: View {
// line the failed send already wrote stays on the piece, so the
// field re-syncs to it (no false pending state).
syncFieldFromDisk()
syncSummaryFromDisk()
}
// MARK: Categories (#207)
@@ -479,13 +552,71 @@ struct MicropubPublishSheet: View {
settledCategoryField = categoryField
}
/// A successful send: the field settles, and a token first entered
/// A successful send: the fields settle, 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()
syncSummaryFromDisk()
if !suggestionsLoaded {
loadSuggestions()
}
}
// MARK: Summary (#208)
/// The piece's `summary:` line as it is on DISK (the model's read).
private var diskSummaryText: String {
posts.openPieceSummary()
}
/// The field AND its baseline take the disk's line (on open, after a forget).
private func syncSummaryFromDisk() {
summaryField = diskSummaryText
settledSummaryField = summaryField
}
/// Only the BASELINE follows the disk (a failed step — the send
/// writes the line before the wire; the Categories discipline).
private func syncSettledSummaryFromDisk() {
settledSummaryField = diskSummaryText
}
/// #208: the AI button's hover reason — the disabled state says why
/// (the pass bar's idiom).
private var summaryButtonHelp: String {
posts.oneShotRailBusy
? "A Pass, Blind Read, or summary is running — the engine is busy."
: "Drafts a first-person teaser from the piece — edit it before sending."
}
/// #208: the AI draft — a fresh one-shot chat-profile engine reads
/// the piece and the reply fills the field for the writer to edit.
/// A refusal shows inline (the field keeps its text). While the turn
/// runs the button is the sheet's OWN Stop (the sheet is modal — the
/// pass bar's Cancel sits behind it): `cancelPass` ends the turn on
/// the shared rail, and `summarizing` follows the model's flag so a
/// stop from anywhere clears the spinner.
private var summarizing: Bool {
posts.summarizing
}
private func draftSummary() {
guard !summarizing else {
// The spinner IS the stop: a hung engine must not hold the
// sheet.
posts.cancelPass(mentor: mentor)
return
}
refusal = nil
Task {
// The model owns the flag; the reply fills the field, a
// refusal lands inline.
if let text = await posts.summarize(mentor: mentor) {
summaryField = text
} else {
refusal = posts.lastError ?? "The engine didn't return a summary — try again."
}
}
}
}
+52
View File
@@ -247,6 +247,58 @@ nonisolated enum PostFrontmatter {
"[" + categoryListValue(names) + "]"
}
/// #208: the piece's summary from its raw frontmatter text — ONE
/// line by construction (the read is line-bounded). Walks the block
/// the way the lenient `parse` does (past the opening fence to the
/// next `---`), but keeps the line's own quotes: `parse`'s scalar
/// trim strips EVERY edge quote character, which would eat a
/// teaser's closing `"why"`. A quoted value (the shape `summaryValue`
/// renders) unescapes through the category codec's one unescape; a
/// bare value is taken as written. No block, or no line → `""`, the
/// field's settled empty: a piece without a line never gains one, and
/// a BODY line named `summary:` never claims the key.
static func summary(inText text: String) -> String {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard trimmed.hasPrefix("summary:") else { continue }
// A stray \r before the newline fuses the closing fence onto
// this line (the last block line of a mixed-ending file) —
// the fence is never part of the value.
var raw = trimmed.dropFirst("summary:".count).trimmingCharacters(in: .whitespaces)
if let fused = raw.range(of: "\r\n---") {
raw = raw[..<fused.lowerBound].trimmingCharacters(in: .whitespaces)
}
if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 {
return categoryUnescaped(String(raw.dropFirst().dropLast()))
}
return raw
}
return ""
}
/// #208: the one-line `summary:` value `summary(inText:)` reads
/// back. Control characters drop and every run of whitespace — a
/// newline included — collapses to one space: the frontmatter sink
/// is line-bounded, so the value is ONE line or nothing. A value
/// holding a quote or backslash renders QUOTED with both escaped —
/// the category codec's own escape, so ONE grammar serves both keys:
/// the lenient `parse` trims every edge quote (a teaser's closing
/// `"why"` would vanish through that door), so the summary is read
/// off its raw line and the wire never ships an altered teaser.
static func summaryValue(_ text: String) -> String {
let flattened = text
.split(whereSeparator: \.isWhitespace)
.joined(separator: " ")
.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }
let cleaned = String(flattened)
let needsQuoting = cleaned.contains(where: { "\"'\\".contains($0) })
guard needsQuoting else { return cleaned }
let slashed = cleaned.replacingOccurrences(of: "\\", with: "\\\\")
return "\"" + slashed.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
// 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`, and #207 the `category:` line) — a
/// `micropub_published`, #207 the `category:` line, and #208 the
/// `summary:` 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
+11
View File
@@ -130,6 +130,17 @@ final class PostsModel {
/// bar's Run ↔ Cancel swap.
/// #146: setter internal — the split-out domain extensions set it.
var runningBlindRead = false
/// #208: the AI summary turn currently drafting over the open piece —
/// the third rider of the one-shot rail; false = idle. Shares the
/// pass bar's Run ↔ Cancel swap like the Blind Read's.
var summarizing = false
/// The one-shot rail is owned by a rider — the pass bar's Cancel
/// shows, and every other rider refuses. ONE predicate, so a fourth
/// rider joins here and every site follows.
var oneShotRailBusy: Bool {
runningPass != nil || runningBlindRead || summarizing
}
/// #122: does the OPEN piece have a Pass-start snapshot on disk (the
/// Blind Read's comparison base)? Refreshed with the cards at the
/// rescan tail and open transitions.
+57
View File
@@ -0,0 +1,57 @@
//
// PostsModelMicropubSummary.swift
// Museion
//
// SummaryPrompt.swift's model half — #208: PostsModel.summarize drafts
// a first-person summary of the OPEN piece on a fresh one-shot
// chat-profile engine and hands the text to the caller. The write is
// NOT here — the send stamps the frontmatter `summary:` line
// (PostFrontmatter, slice 1).
//
import Foundation
@MainActor
extension PostsModel {
/// #208: draft a first-person summary of the OPEN piece on a fresh
/// one-shot chat-profile engine. Flush-first (the engine reads
/// disk); the guards are the shared open-piece rail's. Returns the
/// cleaned reply, or nil with `lastError` set naming the blocker
/// (nothing running / not ready / no open piece / the engine said
/// nothing). Writes NOTHING — the text is the caller's to place.
/// `summarizing` is live while the turn runs: the pass bar's Cancel
/// ends it (the Blind Read posture) and a Pass refuses meanwhile.
func summarize(mentor: MentorSessionModel) async -> String? {
guard let (id, _, home) = guardOpenPieceRun("a summary", mentor: mentor) else { return nil }
guard flushOrAbort(id) else { return nil }
// House posture (blindRead): the run is firing — a stale guard
// refusal no longer owns the error strip.
lastError = nil
// brief-28: the guard answered the session's OWN library; disk is
// the truth post-flush — ONE read feeds the prompt AND the title
// (the scan snapshot can lag a just-flushed heading).
guard let dir = PostStore.folder(of: id, home: home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
lastError = "Couldn't read the piece before summarizing."
return nil
}
let body = PostFrontmatter.split(raw).body
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
lastError = "This piece has no text to summarize."
return nil
}
summarizing = true
defer { summarizing = false }
let pieceTitle = Post.title(of: raw)
let reply = await mentor.runSummary(
prompt: SummaryPrompt.prompt(title: pieceTitle, body: body),
pieceTitle: pieceTitle,
)
guard let summary = reply.map(SummaryPrompt.cleaned), !summary.isEmpty else {
lastError = "The engine didn't return a summary — try again."
return nil
}
return summary
}
}
+6 -1
View File
@@ -34,6 +34,10 @@ extension PostsModel {
lastError = "A Blind Read is already running."
return nil
}
guard !summarizing else {
lastError = "A summary is already running."
return nil
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return nil
@@ -125,7 +129,8 @@ extension PostsModel {
/// rail stops the agent; nothing advances (runPass reads .cancelled).
/// #122: the Blind Read shares the rail — Cancel ends either run.
func cancelPass(mentor: MentorSessionModel) {
guard runningPass != nil || runningBlindRead else { return }
// Any one-shot rider — a summary turn ends like a Blind Read's.
guard oneShotRailBusy else { return }
mentor.stopStreaming()
}
}
+1 -1
View File
@@ -90,7 +90,7 @@ struct PostsPaneView: View {
// #33 (S6.1): the publish ask rides the pane (not the library
// column) — it targets the open piece.
.sheet(isPresented: $showingPublish) {
MicropubPublishSheet(posts: model)
MicropubPublishSheet(posts: model, mentor: mentor)
}
}
+62
View File
@@ -0,0 +1,62 @@
//
// SummaryPrompt.swift
// Museion
//
// #208: the AI summary — a first-person teaser a fresh one-shot engine
// on the museion profile drafts from the open piece. The prompt and the
// reply cleanup live here, pure; the model half is PostsModel.summarize
// (PostsModelMicropubSummary.swift). The summary's home is the
// frontmatter `summary:` line the SEND stamps — this half only drafts
// text for the publish sheet's field.
//
import Foundation
/// #208: the AI summary's prompt vocabulary — the title and body travel
/// inline, the ask is a first-person teaser, and the reply is the
/// summary text and nothing else.
nonisolated enum SummaryPrompt {
/// The ask: a first-person teaser that entices the reader to read
/// the full piece. Title and body travel inline; the reply is the
/// summary text and nothing else.
static func prompt(title: String, body: String) -> String {
"Summary — a first-person teaser for the piece below.\n\n"
+ "Title: \(title)\n\n\(body)\n\n"
+ "Write a short summary in first person that entices the reader to read the full piece. "
+ "Reply with the summary text only — no preamble, no quotes, no markdown heading."
}
/// The engine's reply as the field's text: trimmed; a reply that
/// wraps its answer in a leading label ("Summary: …") drops the
/// label; surrounding double quotes strip; "" when blank. Internal
/// newlines collapse to one space through the codec's own
/// `summaryValue` — the sink is line-bounded and the FIELD shows
/// one line too.
static func cleaned(_ reply: String) -> String {
var text = reply.trimmingCharacters(in: .whitespacesAndNewlines)
// ONE leading label, case-insensitive; the colon is required so a
// reply that merely opens with the word "Summary" keeps it.
if let label = text.range(of: #"^summary:\s*"#, options: [.regularExpression, .caseInsensitive]) {
text.removeSubrange(label)
}
// ONE pair of surrounding double quotes — a WRAPPER, not prose: a
// reply whose inner text still holds a `"` is a teaser that opens
// and closes on quoted words, and its edge quotes are the writer's.
if Self.isQuotedWrapper(text) {
text = String(text.dropFirst().dropLast())
}
// The codec's round-trip, not just its render: `summaryValue`
// quotes a quote-bearing value for the line-bounded sink, and
// the raw-line read gives it back — so the FIELD shows exactly
// the text the wire will carry (no escapes ever reach the eyes).
// Fenced: the read takes the block `split` finds, like disk.
return PostFrontmatter.summary(inText: "---\nsummary: \(PostFrontmatter.summaryValue(text))\n---\n")
}
/// Edge quotes around text that holds no other `"` — a WRAPPER the
/// model put around its reply, not a teaser opening on a quoted word.
private static func isQuotedWrapper(_ text: String) -> Bool {
text.count >= 2 && text.hasPrefix("\"") && text.hasSuffix("\"")
&& !text.dropFirst().dropLast().contains("\"")
}
}
+3 -3
View File
@@ -31,7 +31,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on. Mode strings (mirroring the retired zsh fake): full/crashAfterHandshake/hangOnPrompt/hangOnPromptLoad/cancelOnPrompt/refuseOnPrompt/noStopReason/strayResearchOnPrompt/summaryOnPrompt (#208 — a summary-shaped two-chunk reply, a normal end, NO fix-card tool call; placed AHEAD of the `full` mode's `Hello mentor.` chunks, which concatenate into the one agent row)/loadReplay*/strictMcp.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched); brief-27: the blocked-writer regression rig (never-reading `/bin/sleep` fake mode — deadline/Stop-delivery/bounded-close stay live behind a full stdin pipe) + the `serverPing` healthy-contract smoke.
- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists.
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
@@ -39,10 +39,10 @@ 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`, `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.
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests`, `MicropubSummaryTests` — 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); #208 `MicropubSummaryTests` — the summary travels (create when non-empty; re-send opt-in by key, `""` clears), the one-line codec (`summaryValue`/`summary(inText:)` — the raw-line read; newlines collapse, controls drop, quote-bearing values render quoted and round-trip), apply-at-send with the failed-write refusal, the model's `openPieceSummary()` read, an edge-quote summary reaching the wire exactly as typed, + the sheet field's trimmed-string pending-edit rule. `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).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `SummaryGenerationTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, #208 the AI post summary (`SummaryGenerationTests` — the pure prompt + `cleaned`, and `summarize` over the `summaryOnPrompt` rig: a fresh chat-profile one-shot drafts and the cleaned reply comes back with NOTHING written and the roster untouched; refusals — no open piece, the one-shot rail busy, a refused/empty turn), 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).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import, image ingest + the 27.2 drag-routing seam (`DragInfoStub`, the suite's NSDraggingInfo mock: a Finder-shaped drag routes through the text view and never pastes the path; text-only drags keep the stock drop; outline rows bounce; the probe follows `changeCount`; web URLs and vanished files refuse with the right notice) + the one router's pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal).
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
+377
View File
@@ -0,0 +1,377 @@
// MicropubSummaryTests.swift
// MuseionTests
//
// #208: a post summary for Micro.blog — the wire + codec half. The
// sheet's Summary field is sheet state (the Categories discipline);
// the edit lands on the piece AT THE SEND as a one-line `summary:`
// key, and the wire reads from disk: a CREATE carries
// `properties.summary` when non-empty; a RE-SEND carries `summary`
// in `replace` ONLY when the piece has the line (opt-in by key —
// an empty string is sent and clears the post's summary; no line →
// `replace` names exactly name + content, the blog keeps whatever it
// has). The AI half (the one-shot engine drafting the summary) rides
// its own file; the sheet itself is not pinned here.
//
// Pins: S1 the codec reads the line · S2 create carries it · S3 the
// re-send opt-in by key · S4 the edit lands at the send (sanitized,
// one line, readable through the model; a failed write refuses).
//
// ## Scenario: the summary travels on the wire
// From #208
//
// Given a saved Post whose frontmatter carries a one-line `summary:`
// When the writer sends it to Micro.blog or re-sends over the
// remembered post
// Then a CREATE carries `properties.summary` (only when non-empty);
// a RE-SEND carries `summary` in `replace` ONLY when the piece has
// the line (`""` is sent and clears; no line leaves the blog's).
//
// ## Scenario: the edit lands at the send
// From #208
//
// Given a sheet Summary edit (the model's `summary:` argument)
// When the writer sends
// Then the line is written to the piece AFTER the flush and BEFORE
// the one disk read that feeds the wire — disk and blog never
// disagree; a write that cannot land REFUSES the send with nothing
// on the wire.
//
import Foundation
@testable import Museion
import Testing
@Suite("MicropubSummaryTests")
struct MicropubSummaryTests {
/// A saved piece opened in the model, with `frontmatter` planted
/// after the owned keys; 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` — through `request(_:)`, never a
/// subscript (#206).
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])
}
// MARK: S1 — the codec reads the one-line summary (pure)
@Test func `summary read is the raw line's scalar and empty when absent`() {
#expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left the city.\n---\n") == "Why I left the city.")
#expect(PostFrontmatter.summary(inText: "---\nsummary: Padded. \n---\n") == "Padded.")
// A hand-quoted scalar reads back as the bare text.
#expect(PostFrontmatter.summary(inText: "---\nsummary: \"Quoted, with comma\"\n---\n") == "Quoted, with comma")
// Empty, blank, or absent → "" (a piece without a line never gains one).
#expect(PostFrontmatter.summary(inText: "---\nsummary:\n---\n") == "")
#expect(PostFrontmatter.summary(inText: "---\nsummary: \n---\n") == "")
#expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n") == "")
// A body line named summary: never claims the key.
#expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n\nsummary: not frontmatter\n") == "")
// No block at all → nothing.
#expect(PostFrontmatter.summary(inText: "# Title\n\nBody.\n") == "")
// A body line named summary: never claims the key — fenced or not.
#expect(PostFrontmatter.summary(inText: "# Title\n\nsummary: body prose\n") == "")
// ponytail: a CRLF post.md is one grapheme-cluster "line" to every
// `\n` split in the corpus (PostStore: LF-only by design, CRLF is
// normalized at the boundaries) — no reader sees its block, this
// one included. The MIXED shape (an LF block with a stray trailing
// \r on one line) is where parse and a `.whitespaces` trim would
// diverge — pinned at the wire in `a mixed-line-ending piece…`.
#expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left.\r\n---\n") == "Why I left.")
}
@Test func `summary value strips newlines so the line-bounded sink is safe`() {
// The frontmatter sink is line-bounded — a summary can never ride
// a newline into the block; the value is one line or nothing.
let value = PostFrontmatter.summaryValue("Line one.\nLine two.")
#expect(!value.contains("\n"))
#expect(PostFrontmatter.summary(inText: "---\nsummary: \(value)\n---\n") == "Line one. Line two.")
// Leading/trailing whitespace trims; a blank becomes "".
#expect(PostFrontmatter.summaryValue(" ") == "")
}
@Test func `summary value round-trips through the raw line read without losing edge quotes or controls`() {
// The lenient parse trims EVERY leading/trailing quote char, so
// the wire and the sheet read the raw line (`summary(inText:)`);
// the render QUOTES anything holding a quote or backslash, so
// `asked "why"` ships exactly as typed.
let read = { text in PostFrontmatter.summary(inText: "---\nsummary: \(PostFrontmatter.summaryValue(text))\n---\n") }
#expect(read(#"I finally asked "why""#) == #"I finally asked "why""#)
#expect(read(#""Why did you leave?" haunted me."#) == #""Why did you leave?" haunted me."#)
// An inner quote and a newline together: flattened AND round-tripped.
#expect(read("Line \"one\".\nLine two.") == "Line \"one\". Line two.")
// A backslash survives too (the category codec's escape).
#expect(read(#"C:\path "x""#) == #"C:\path "x""#)
// Control characters (NUL, ESC) never reach the sink — the
// category codec's rule; whitespace still collapses to one space.
#expect(PostFrontmatter.summaryValue("a\u{0}b\u{1B} c") == "ab c")
// A plain value renders bare.
#expect(PostFrontmatter.summaryValue("Why I left.") == "Why I left.")
}
// MARK: S2 — a create carries the summary when non-empty (builder + model)
@Test func `draft request carries summary only when non-empty`() throws {
let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", summary: "Why I left.")
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
#expect(props["summary"] as? [String] == ["Why I left."])
#expect(props["name"] as? [String] == ["T"])
#expect(props["content"] as? [String] == ["B"])
// No summary → no key at all (a create never carries an empty one).
let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any])
#expect(bare["summary"] == nil)
}
@Test @MainActor func `create carries the piece's summary 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/summarized"], log: log)
_ = try openPiece(model, home, frontmatter: "summary: Why I left the city.\n")
let outcome = await model.micropubSend(token: "tok", transport: transport)
#expect(outcome == .drafted(url: "https://example.micro.blog/summarized", preview: nil))
let props = try createProperties(log, 0)
#expect(props["summary"] as? [String] == ["Why I left the city."])
// No line at all → no key; an empty line → no key either.
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(try createProperties(log, 1)["summary"] == nil)
_ = try openPiece(model, home, frontmatter: "summary:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(try createProperties(log, 2)["summary"] == nil)
}
// MARK: S3 — a re-send replaces, opt-in by key (the model)
@Test @MainActor func `a re-send carries the line's summary in replace and clears on an empty one`() 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)\nsummary: Why I left.\n")
let outcome = await model.micropubSend(token: "tok", transport: transport)
#expect(outcome == .updated(url: url))
let replace = try updateReplace(log, 0)
#expect(replace["summary"] as? [String] == ["Why I left."])
#expect(replace["name"] as? [String] == ["Titled"])
// An empty summary IS sent — it clears the post's.
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let cleared = try updateReplace(log, 1)
#expect(cleared["summary"] 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 summary edit lands on the piece before the wire`() async throws {
let (model, home) = try makeModelHome()
let id = try openPiece(model, home) // no summary 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", summary: "A teaser.", 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; the body is byte-identical.
#expect(PostFrontmatter.split(after).block.contains("\nsummary: A teaser.\n"))
#expect(PostFrontmatter.split(after).body == before)
let props = try createProperties(log, 0)
#expect(props["summary"] as? [String] == ["A teaser."])
}
@Test @MainActor func `a refused send with a summary 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", summary: "A teaser.", transport: micropubCanned(201, log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
#expect(try readPost(home, post.id) == before) // the edit never reached the disk
}
@Test @MainActor func `a summary 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 summary line cannot land.
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", summary: "A teaser.", 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 summary — nothing was sent."))
#expect(log.requests.isEmpty)
#expect(try PostFrontmatter.summary(inText: readPost(home, id)) == "")
}
@Test @MainActor func `an edge-quote summary reaches the wire exactly as typed`() async throws {
// The review's finding: the lenient parse trims every edge quote,
// so a teaser closing in `"why"` must still ship whole — on a
// create AND on a re-send, and reopen whole in the sheet's read.
let (model, home) = try makeModelHome()
let teaser = #"I finally asked "why""#
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/quoted"], log: log)
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", summary: teaser, transport: transport)
#expect(try createProperties(log, 0)["summary"] as? [String] == [teaser])
#expect(model.openPieceSummary() == teaser)
// A re-send reads the stamped line back — still whole. The piece
// remembers its post from the first send, so this is the update.
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(log.requests.count == 2)
#expect(try updateReplace(log, 1)["summary"] as? [String] == [teaser])
}
@Test @MainActor func `the sheet's disk read is the open piece's summary line`() async throws {
let (model, home) = try makeModelHome()
#expect(model.openPieceSummary() == "") // nothing open
_ = try openPiece(model, home)
#expect(model.openPieceSummary() == "") // no line yet
_ = await model.micropubSend(
token: "tok",
summary: "A teaser.",
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: MicropubRequestLog()),
)
#expect(model.openPieceSummary() == "A teaser.") // read from disk, never a snapshot
}
@Test @MainActor func `a mixed-line-ending piece re-sends its real summary never an empty clear`() async throws {
// The trimmed() rule. A pure CRLF file is ONE grapheme "line" to
// every `\n` split in the corpus (LF-only by design, normalized at
// the boundaries) — no reader sees its block, so nothing can
// disagree. The shape that CAN: an LF block carrying a stray
// trailing \r on the summary line (a half-converted edit) — parse's
// trimmed() sees the key, a `.whitespaces` trim would leave `\r`
// on the fence and read "" → replace summary [""] over the live post.
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary: Why I left.\n")
let id = try #require(model.selectedPostID)
let file = try #require(PostStore.folder(of: id, home: home)?.appendingPathComponent("post.md"))
try String(contentsOf: file, encoding: .utf8)
.replacingOccurrences(of: "summary: Why I left.\n", with: "summary: Why I left.\r\n")
.write(to: file, atomically: true, encoding: .utf8)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
#expect(outcome == .updated(url: url))
#expect(log.requests.count == 1)
let replace = try updateReplace(log, 0)
#expect(replace["summary"] as? [String] == ["Why I left."])
}
@Test @MainActor func `publish with only a summary edit updates first then flips the status`() async throws {
// The applies-first condition is `categories != nil || summary != nil` —
// a summary-only edit must still send before the flip, or Publish
// would publish the stale post and silently drop the edit.
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 outcome = await model.micropubPublish(url: url, token: "tok", summary: "A teaser.", transport: micropubCanned(200, log: log))
#expect(outcome == .published)
// TWO requests, in order: the update carrying the edit, THEN the flip.
#expect(log.requests.count == 2)
#expect(try updateReplace(log, 0)["summary"] as? [String] == ["A teaser."])
let flip = try #require(log.request(1))
let flipReplace = try #require(micropubJSON(flip)["replace"] as? [String: Any])
#expect(flipReplace["post-status"] as? [String] == ["published"])
#expect(flipReplace["summary"] == nil)
#expect(model.openPieceSummary() == "A teaser.")
#expect(try PostFrontmatter.split(readPost(home, id)).block.contains("micropub_published: "))
}
@Test @MainActor func `clearing a sent summary writes the empty line and clears the post's`() async throws {
// End to end through the model's own written form (not a hand-planted
// line): send, then clear → the update carries summary [""].
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
let transport = micropubCanned(200, headers: ["Location": url], log: log)
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
_ = await model.micropubSend(token: "tok", summary: "A teaser.", transport: transport)
#expect(model.openPieceSummary() == "A teaser.")
let outcome = await model.micropubSend(token: "tok", summary: "", transport: transport)
#expect(outcome == .updated(url: url))
#expect(log.requests.count == 2)
let cleared = try updateReplace(log, 1)
#expect(cleared["summary"] as? [String] == [""])
let id = try #require(model.selectedPostID)
let disk = try readPost(home, id)
#expect(PostFrontmatter.split(disk).block.contains("\nsummary: \n"))
#expect(model.openPieceSummary() == "")
}
@Test func `an imported summary line rides through import`() throws {
let home = try storeHome()
// The summary is the writer's content, like `category:` — it stays;
// only Museion's bookkeeping drops at the boundary (#206).
let ext = FileManager.default.temporaryDirectory.appendingPathComponent("summarized-\(UUID().uuidString).md")
try "---\nsummary: Why I left.\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 disk = try readPost(home, post.id)
let matter = try PostFrontmatter.parse(disk)
#expect(PostFrontmatter.summary(inText: disk) == "Why I left.")
#expect(matter["micropub_url"] == nil)
}
// MARK: S5 — the sheet field's pending-edit rule (pure)
@Test func `a summary edit is pending only when the trimmed field differs from the settled one`() {
#expect(MicropubSummaryField.pendingSummary(field: "Why I left.", settled: "Why I left.") == nil)
// Trailing whitespace is not an edit.
#expect(MicropubSummaryField.pendingSummary(field: "Why I left. ", settled: "Why I left.") == nil)
// Clearing a piece that had a line sends an empty summary.
#expect(MicropubSummaryField.pendingSummary(field: "", settled: "Why I left.") == "")
#expect(MicropubSummaryField.pendingSummary(field: "New", settled: "") == "New")
// A piece without a line never gains an empty key.
#expect(MicropubSummaryField.pendingSummary(field: " ", settled: "") == nil)
}
}
+10
View File
@@ -334,6 +334,16 @@ extension ScriptedEngine {
continuation.resume(returning: .object(["stopReason": .string("refusal")]))
return
}
if mode == "summaryOnPrompt" {
// #208: a summary-shaped reply — two chunks of one sentence,
// a normal end, NO fix-card tool call (the draft IS the reply
// text). Ahead of the "Hello mentor." chunks so the summary
// pins read the reply exactly.
chunk(sid, "agent_message_chunk", "I left the city because ")
chunk(sid, "agent_message_chunk", "the noise never stopped.")
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
return
}
chunk(sid, "user_message_chunk", "echo")
chunk(sid, "agent_thought_chunk", "weighing the structure")
chunk(sid, "agent_message_chunk", "Hello ")
+176
View File
@@ -0,0 +1,176 @@
//
// SummaryGenerationTests.swift
// MuseionTests
//
// ## Scenario: the AI drafts a first-person summary
// From #208
//
// Given an open saved piece and an idle one-shot rail
// When the writer asks for an AI summary
// Then a fresh one-shot engine on the museion profile receives the
// piece's Title and body (flushed to disk first) with a prompt that
// asks for a first-person teaser, and the reply text comes back to
// the caller — nothing is written to disk, the roster is untouched,
// and the transcript it ran in is transient.
//
import Foundation
@testable import Museion
import Testing
@Suite("SummaryGenerationTests")
struct SummaryGenerationTests {
// MARK: The pure prompt (SummaryPrompt)
@Test func `prompt carries the title and body and asks for first person`() {
let prompt = SummaryPrompt.prompt(title: "T", body: "B")
#expect(prompt.contains("T"))
#expect(prompt.contains("B"))
#expect(prompt.lowercased().contains("first person"))
#expect(prompt.lowercased().contains("entice"))
}
@Test func `cleaned trims drops a leading label and surrounding quotes`() {
#expect(SummaryPrompt.cleaned(" Summary: Why I left. ") == "Why I left.")
#expect(SummaryPrompt.cleaned("\"Why I left.\"") == "Why I left.")
#expect(SummaryPrompt.cleaned("Line one.\nLine two.") == "Line one. Line two.")
#expect(SummaryPrompt.cleaned(" ") == "")
// A reply that merely opens with the word keeps it.
#expect(SummaryPrompt.cleaned("Summary opens the piece.") == "Summary opens the piece.")
// Prose bracketed by quoted words is a teaser, not a wrapper — the
// edge quotes are the writer's and stay.
let bracketed = "\"Why did you leave?\" I asked. She said \"never.\""
#expect(SummaryPrompt.cleaned(bracketed) == bracketed)
// Label and wrapper together.
#expect(SummaryPrompt.cleaned("Summary: \"Why I left.\"") == "Why I left.")
}
// MARK: The model half (PostsModel.summarize over the scripted rig)
/// A saved `# Titled` piece opened in the model, waited into the
/// library scan (the label and the prompt read the library's title).
@MainActor private func openPiece(_ rig: ScriptedRig) async throws -> String {
let id = try plantedPiece(rig.home)
rig.model.select(id)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
return id
}
/// How many `museion` (chat-profile) engines spawned — the resident
/// plus every one-shot (BlindReadTests' countable).
@MainActor private func museionSpawns(_ rig: ScriptedRig) -> Int {
rig.engines.spawnedProfiles.filter { $0 == "museion" }.count
}
@Test @MainActor func `summarize runs a fresh chat-profile engine and returns the cleaned reply`() async throws {
let rig = try makeScriptedRig(mode: "summaryOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
_ = try await openPiece(rig)
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == "I left the city because the noise never stopped.")
// A fresh CHAT-profile engine drafted (the resident is the only
// other `museion` spawn; pass profiles never ran).
#expect(museionSpawns(rig) == 2)
#expect(!rig.engines.spawnedProfiles.contains { $0.contains("museion-pass") })
// The prompt carried the piece's body inline (the engines' prompt log).
let asked = rig.engines.engines.flatMap(\.promptLog).map(\.text).joined()
#expect(asked.contains("Body."))
// The transient label renders; the roster never grew; nothing was
// written — the piece on disk carries no summary line.
#expect(textRows(of: rig.mentor).contains("Summary · Titled"))
#expect(rig.mentor.roster.count == rosterBefore)
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(!onDisk.contains("summary:"))
#expect(rig.model.lastError == nil)
}
@Test @MainActor func `summarize refuses when no piece is open`() async throws {
let rig = try makeScriptedRig(mode: "summaryOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("Open a saved post") == true)
// Nothing ran beyond the resident engine.
#expect(museionSpawns(rig) == 1)
}
@Test @MainActor func `summarize refuses while the one-shot rail is busy`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
for _ in 0 ..< 250 where rig.model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == .pass1)
// Exclusivity — the summary refuses while the pass owns the rail.
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("already running") == true)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
for _ in 0 ..< 250 where rig.model.runningPass != nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == nil)
rig.mentor.shutdown() // frees the held turn if the rail regressed — bounds the await
_ = await run.value
}
@Test @MainActor func `a cancelled summary turn returns nil and frees the rail`() async throws {
// A hung engine must not hold the sheet's spinner forever: the pass
// bar's Cancel (cancelPass) ends the summary turn like a Blind Read's.
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let run = Task { await rig.model.summarize(mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.summarizing {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.summarizing) // the flag the pass bar's Cancel keys on
// Reverse exclusivity: a Pass refuses while the summary owns the
// rail — and the refusal NAMES the summary (the guard, not the
// host's engine lock downstream).
await rig.model.runPass(.pass1, mentor: rig.mentor)
#expect(rig.model.lastError == "A summary is already running.")
#expect(rig.model.runningPass == nil)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
let summary = await run.value
#expect(summary == nil)
for _ in 0 ..< 250 where rig.model.summarizing {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(!rig.model.summarizing)
#expect(!rig.mentor.isStreaming) // the rail is free again
}
@Test @MainActor func `a refused or empty turn returns nil`() async throws {
let rig = try makeScriptedRig(mode: "refuseOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("didn't return a summary") == true)
}
}
+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:` 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.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. A frontmatter `summary:` line travels the same way since #208 — the publish sheet's Summary field takes a one-line teaser (typed, or drafted by its AI summary button on a one-shot chat engine, edited before it lands) and is stamped on the piece at the send.
- **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,82 @@
# Post Summary for Micro.blog (#208)
> **Date:** 2026-12-05
> **Type:** issue
> **Reference:** https://git.babylondreams.de/alex/Museion/issues/208
## Goal
Give the publish dialog a post-summary field plus an "AI summary" button. The summary is first-person, entices the reader to read the full piece, and travels to Micro.blog with the send.
## What Was Done
- **Wire** (`Micropub.swift`): `makeDraftRequest`/`makeUpdateRequest`/`update`/`sendDraft` carry a `summary:` parameter. A create adds `properties.summary` only when non-empty; an update carries `summary` in `replace` only when the piece has the line (opt-in by key — `nil` leaves the post's summary alone, `""` clears it). One read (`updateRememberedOrCreate`) serves the wire fields, the categories, the summary, and the remembered URL.
- **Codec** (`PostFrontmatter.swift`): `summaryValue(_:)` renders one line (whitespace runs — newlines included — collapse to one space, control characters drop; a value holding a quote or backslash renders QUOTED with the category codec's own escapes — one grammar for both keys). `summary(inText:)` reads it back off the RAW line: a parse-style block walk (past the opening fence to the next `---`) with a fused `\r\n---` tail strip, never through the lenient `parse` (which trims every edge quote) and never via `split` (whose closing-fence check a mixed-ending file defeats). `summary(in:)` — the lossy decoded read — was deleted (zero production consumers).
- **Model** (`PostsModelMicropubSummary.swift`, `PostsModel.swift`, `PostsModelPasses.swift`): `summarize(mentor:)` = the shared open-piece guard rail → flush → ONE disk read feeds the prompt → `mentor.runSummary` on a fresh one-shot chat-profile engine → `SummaryPrompt.cleaned`. Writes nothing. `PostsModel.summarizing` is the one-shot rail's third rider; `oneShotRailBusy` is the ONE predicate the sheet, the pass bar's Cancel, `cancelPass`, and `guardOpenPieceRun` all consult. `micropubSend(categories:summary:)` stamps a pending summary edit at the send (write-before-wire — a failed stamp refuses with nothing on the wire); `micropubPublish` applies a pending edit first.
- **Engine** (`MentorSessionModel.swift`): `runSummary(prompt:pieceTitle:)` rides `runOneShot` (label `Summary · <piece>`, reply read through `draftCandidateText`); exclusivity unchanged — a summary refuses while a Pass or Blind Read runs, and vice versa.
- **Prompt** (`SummaryPrompt.swift`): `prompt(title:body:)` asks for a first-person teaser that entices the reader, reply = summary text only. `cleaned(_:)` trims, drops ONE leading `Summary:` label (colon required), strips ONE pair of surrounding quotes only when the inner text holds no other `"` (a wrapper, not a teaser that opens on a quoted word), then round-trips through the codec so the field shows exactly the text the wire will carry.
- **Sheet** (`MicropubPublishSheet.swift`, `PostsPaneView.swift`): a Summary `TextEditor` (mono-11, 72pt) with the `AI summary` button in the label row; the reply fills the field for the writer to edit. The sheet holds `let mentor: MentorSessionModel` (PostsPaneView passes its own — the one construction site). Sync points mirror the Categories field: disk on open and after a forget, canonical one-line text after a successful send/publish, baseline only after a failed step. `MicropubSummaryField.pendingSummary` is a trimmed-STRING compare (whitespace alone is not an edit; equal empties stay nil — a piece without the line never gains an empty key).
- **Cancel** (`MentorPaneView.swift`, `PostsModelPasses.swift`): the sheet is modal, so while its own summary turn runs the AI button IS the Stop (click → `cancelPass`); the pass bar's Cancel shows on `oneShotRailBusy`.
- **Tests**: `MicropubSummaryTests.swift` (16 pins) + `SummaryGenerationTests.swift` (7 pins), plus `ScriptedEngine` mode `summaryOnPrompt` (a two-chunk summary-shaped reply, normal end, no fix-card call). 814 total (791 before).
- **Docs**: `Museion/AGENTS.md` (SummaryPrompt, PostsModelMicropubSummary, the Micropub bullet, PostFrontmatter, PostStore, MentorSessionModel), `MuseionTests/AGENTS.md`, `GLOSSARY.md` Summary term, `PRD.md` S6.1, `CHANGELOG.md` [Unreleased].
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| The summary lives in a frontmatter `summary:` line, stamped at the send like `category:` (owner ruling) | Survives reopen, rides every re-send, visible in the file — the same discipline the category line established in #207. A sheet-only value would be lost on every reopen and could never be re-sent. |
| The AI summary runs on the one-shot engine on the chat profile, never the resident session (owner ruling) | The resident session is the writer's conversation; a drafting side-quest would pollute its transcript. The one-shot rail (ADR-0014) spawns, drafts, and tears down — the Blind Read's proven shape. |
| Create carries `summary` only when non-empty; update carries it in `replace` only when the line exists (opt-in by key); `""` clears | Mirrors #207 exactly. Without the opt-in, every re-send of a piece without a line would wipe a summary set on Micro.blog itself. |
| The reader walks the RAW line, never `parse` | The lenient decode trims every edge quote — a teaser ending in `"why"` would lose its quotes through that door. Raw-line read + codec unescape keeps the writer's text exact. |
| `summary(in:)` deleted rather than kept beside `summary(inText:)` | Zero production consumers and lossy by design. Two readers for one key invite the wrong one at a new call site. |
| `oneShotRailBusy` as ONE computed predicate over three riders | The sheet, both Cancels, the guard, and `cancelPass` all need the same answer. One predicate: a fourth rider joins here and every site follows. |
| `lastError` for refusals (not a `Result` return) | House posture — `blindRead` and `runPass` report through `lastError`; the sheet already renders the strip. A typed result would be the only one of its kind. |
| Refusals keep the field's text | The writer may have typed a summary by hand before clicking AI; a refusal must not eat it. |
| The AI button is the Stop during its own turn | The sheet is modal — the pass bar's Cancel is unreachable behind it. Without this, a hung turn would wedge the sheet with no way out. |
| `cleaned` strips edge quotes only when no `"` remains inside | A reply opening and closing on quoted words is a teaser; its edge quotes are the writer's. Only a true wrapper (nothing quoted inside) strips. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---|---|---|
| A mixed-ending `post.md` (a stray `\r` on the last block line) fused the closing fence; the lenient reader still saw the key → re-send path, a `split`-based reader found no block → `""` → `replace summary [""]` would wipe a LIVE post's summary | Two readers of one file disagreed on where the block ends | `summary(inText:)` walks the block the way `parse` does and strips a fused `\r\n---` tail; the mixed-ending wire pin went red on exactly this guard (FLIP-A) |
| An unfenced body line named `summary:` was read as the summary | The reader did not require a fence | The parse-style walk requires an opening fence; body prose never claims the key |
| A hung summary turn could not be cancelled from the modal sheet | The AI button had no Stop behavior and the pass bar's Cancel was behind the sheet | Model `summarizing` flag + `oneShotRailBusy`; the AI button doubles as Stop; `cancelPass` and `guardOpenPieceRun` consult the predicate. Flip: disabling `cancelPass`'s guard hangs the cancel pin (the timeout is the red). |
| The first cancel pin's observable was wrong — asserting `runningPass == nil` held through the host's own one-shot lock, so the flip reddened nothing | A third belt masked the guard under test | The pin asserts `lastError == "A summary is already running."` instead; the flip then reddened exactly that pin |
| `cleaned`'s wrapper rule stripped the edge quotes of prose bracketed by quoted words | The rule matched any string starting and ending with `"` | Strip only when the inner text holds no further `"`; pinned, flip-verified (FLIP-B) |
| The audit round's own edits left 3 lint regressions (a missing blank line after a computed property; a lone `{` under a wrapped condition; a 144-char test line) | Hand edits after the last lint run | Fixed; the lone-brace was the house trap (#142/#179) — hoisted an `isQuotedWrapper` predicate |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/Micropub.swift` | `summary:` on the draft/update builders; create carries when non-empty, update in `replace` by key; one read serves wire fields + categories + summary + URL |
| `Museion/PostFrontmatter.swift` | `summaryValue` (one-line render, quote-aware) + `summary(inText:)` (raw-line read, parse-style walk, fused-fence strip); `summary(in:)` deleted |
| `Museion/PostsModelMicropubSummary.swift` | new — `summarize(mentor:)`: guard rail → flush → one disk read → `runSummary` → `cleaned`; nil + `lastError` on refusal |
| `Museion/SummaryPrompt.swift` | new — the prompt + `cleaned` (label drop, wrapper-only quote strip, codec round-trip) |
| `Museion/PostsModel.swift` | `summarizing` flag; `oneShotRailBusy` predicate; `micropubSend(categories:summary:)`; `micropubPublish` applies a pending edit first |
| `Museion/PostsModelPasses.swift` + `Museion/MentorPaneView.swift` | `cancelPass` + `guardOpenPieceRun` honor `oneShotRailBusy`; the pass bar's Cancel shows on it |
| `Museion/MicropubPublishSheet.swift` | Summary field + AI summary button (doubles as Stop); sync mirrors the Categories field |
| `Museion/PostsPaneView.swift` | the sheet takes the pane's own `mentor` |
| `Museion/MentorSessionModel.swift` | `runSummary` over `runOneShot` |
| `Museion/PostStore.swift` | `stampMicropub` carries the `summary:` line |
| `MuseionTests/ScriptedEngine.swift` | `summaryOnPrompt` mode |
| `MuseionTests/MicropubSummaryTests.swift` | new — 16 pins |
| `MuseionTests/SummaryGenerationTests.swift` | new — 7 pins |
| `GLOSSARY.md`, `PRD.md`, `CHANGELOG.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | Summary term, S6.1 clause, [Unreleased] entry, DOX rows |
## Verification
- Finish-audit gates (final tree): `swiftformat --lint .` 0/161 · `swiftlint --strict .` 0 violations · `full-test.sh` **814/814** (run `20261205T095042Z-Museion`; 791 → 814, +23). The three files edited during the audit compiled in that run (SwiftCompile lines present).
- Flips: fused-fence strip → exactly the 2 mixed-ending pins red; `cleaned` wrapper rule → exactly the bracketed-prose pin; `guardOpenPieceRun` summarizing refusal → exactly the reverse-exclusivity pin; `cancelPass` guard → the cancel pin hangs. All restored byte-exact (`cmp` + sha256).
- Baseline before the audit: 809/809 on the pre-audit tree.
## Open Items & Next Steps
- [ ] Owner to try the live sheet: the AI button's Stop behavior and the one-shot rail refusal are SwiftUI wiring, not host-testable.
- [ ] Ticket candidate: Convert to Post rebuilds frontmatter and drops a piece's `summary:` line (#114 posture — same as `category:`).
- [ ] Ticket candidate: a malformed frontmatter block lets a stamp land in the wrong place — pre-existing for every stamp, not #208's seam.
---
*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-05 | issue | [20261205-issue208-post-summary-for-micro-blog_log.md](20261205-issue208-post-summary-for-micro-blog_log.md) | Micro.blog summary travels with the piece; publish sheet Summary field + AI summary button on the one-shot rail (rail 814/814) |
| 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) |