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

+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("\"")
}
}