Files
museion/Museion/PostsModel.swift
T
AlexKucera 36393a9e8e 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
2026-12-05 12:32:38 +01:00

367 lines
17 KiB
Swift

//
// PostsModel.swift
// Museion
//
// #18 (S1.1): the Posts pane's write side — selection and the New Post
// draft lifecycle (#62). Own ops route through the same rescan: one path.
// #179: every library-reflecting store write rides `performWrite` — the
// one write rail pairing each write with exactly one rescan and owning
// the error strip; the model owns the Home (watchedHome), no method
// takes one.
// #146/#193: the domain extensions live in their own files — guard+
// Convert PostsModelOutline, passes+Blind Read PostsModelPasses, fix
// cards PostsModelCards, write rail+structural ops PostsModelWrites,
// external guest+imports PostsModelImports, watcher+rescan
// PostsModelWatcher.
//
import Foundation
import Observation
/// The New Post draft: body text only, no folder until first save (#62).
/// #107: remembers the project the piece will land in when first saved.
/// #109: remembers the content type too (post default; .outline for New
/// Outline) so saveDraft stamps the right frontmatter.
struct PostDraft {
var text = "# Untitled\n\n"
let project: String
var type = Post.ContentType.post
/// Mount identity: bumped on every stage (newPost/newOutline) so the
/// editor view REMOUNTS per draft — the outliner's one-shot seed
/// (`guard loadedGeneration < 0`) would otherwise keep a stale tree
/// when a new draft replaces the old without a hierarchy change.
let mountID = UUID()
}
/// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern).
/// The watcher runs while the workspace is open (app-scoped, #61).
@MainActor
@Observable
final class PostsModel {
/// #200: the app's one model, for WritingLockAppDelegate's quit-time
/// departure gate (the WritingLockState.active reachability
/// precedent). Weak; registered by AppGateState's init — bare
/// hosted-test rigs never register, so the delegate's pins inject
/// their model through `quitReply(posts:)`.
weak static var active: PostsModel?
/// The scanned, title-sorted list — mirrors `projects/` + `archive/` at
/// all times (#107).
/// #193: setter internal — PostsModelWatcher's rescan writes it.
var posts: [Post] = []
/// #144 (mounted half): the library content revision — the search
/// snapshot's invalidation signal. The rescan rail bumps it whenever
/// a scan sees the library change: a Post-list change OR any re-read
/// post.md (a body-only edit compares equal as a Post — #143's skip
/// keeps the list still — yet the search must re-sweep). The `posts`
/// assignment skip stays untouched: panes never regroup on bumps,
/// only the mounted search re-keys.
/// #193: setter internal — PostsModelWatcher's rescan bumps it.
var contentRevision = 0
/// The selected Post's id; nil = nothing selected (empty editor).
/// #146: setter internal — the split-out domain extensions set it.
var selectedPostID: String?
/// The in-memory draft for New Post (#62): no folder until first save.
/// #146: setter internal — the split-out domain extensions set it.
var draft: PostDraft?
/// #19: the open post's editing session; nil while a draft is open or
/// nothing is selected.
/// #146: setter internal — the split-out domain extensions set it.
var session: EditorSession?
/// #92: the external buffer's guest slot — one at a time, transient per
/// launch. Takes the editor column; opening a Post or draft dismisses it
/// (flush first).
/// #193: setter internal — PostsModelImports owns the guest slot.
var externalSession: EditorSession?
/// #94: a multi-file import waiting on its ONE Origin ask; the sheet
/// answers, then the batch runs.
/// #193: setter internal — PostsModelImports stages the batch.
var pendingImportURLs: [URL]?
/// #108: the explicit target for the NEXT new piece — set by New Project
/// once the folder exists; outranks selection. Cleared when the draft
/// lands (saveDraft) or the ask is canceled.
/// #146: setter internal — the split-out domain extensions set it.
var pendingProject: String?
/// #108: File ▸ New Project… stages its ask here — commands can't
/// present sheets, so the model holds the flag and WorkspaceView
/// presents (the pendingImportURLs pattern, #94).
/// #193: setter internal — PostsModelWrites stages the ask.
var askNewProject = false
/// #109: the just-saved outline draft's afterglow — the posts list
/// lags one rescan (the FSEvents window), so the freshly-opened
/// session can't read its type from the scan yet and would flash the
/// prose editor. True only between saveDraft and the next selection.
/// #146: setter internal — the split-out domain extensions set it.
var lastDraftWasOutline = false
/// #111 (S7): a mixed-content outline piece whose open is held for the
/// guard ask. Non-nil = the ask is up (no session — the ask presents
/// over an empty editor); cleared by any answer.
/// #146: setter internal — the split-out domain extensions set it.
var outlineGuardPieceID: String?
/// #111 (S7): the piece the guard's Prose answer opened in prose mode —
/// a routing override with lastDraftWasOutline's exact lifecycle (dies
/// on the next open/draft/guest; the rescan lag window is covered).
/// #146: setter internal — the split-out domain extensions set it.
var proseOverridePostID: String?
/// #114 (S4): the staged Convert to Post ask (row menu → sheet). The
/// ask targets a piece id, not the session — it survives background
/// selects; the sheet is modal in its window, and the convert itself
/// re-derives everything (flush, disk read) at answer time.
/// #146: setter internal — the split-out domain extensions set it.
var pendingConversion: PendingConversion?
/// #24 (S3.1): the pass currently streaming over the open piece —
/// one at a time; nil = idle. Drives the pass bar's Run ↔ Cancel swap.
/// #146: setter internal — the split-out domain extensions set it.
var runningPass: PassKind?
/// #122: the Blind Read currently judging over the open piece —
/// one at a time beside runningPass; false = idle. Shares the pass
/// 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.
/// #146: setter internal — the split-out domain extensions set it.
var openPieceHasSnapshot = false
/// #23 (M2, slice 3): the OPEN piece's stored fix cards
/// (`<piece>/cards/*.json`, newest-first) — what any MCP client
/// submitted; nil session (draft/guest/nothing) shows none.
/// #146: setter internal — the split-out domain extensions set it.
var openPieceCards: [FixCardStore.StoredFixCard] = []
/// #204: one jump-to-the-anchor request from the Fix Cards palette —
/// the anchor's span in the LIVE session text plus a token that
/// advances per jump (the editor column applies once per token, the
/// #71 flip-back caret pattern). Set by `revealCard`; never written
/// to disk — a jump is a view act.
var revealRequest: FixCardRevealRequest?
/// Last failed-op message surfaced in the editor (nil = clean).
/// #146: setter internal — the split-out domain extensions set it.
var lastError: String?
/// #179: the bound Home — the MODEL owns it. `bind` is the only writer,
/// driven by WorkspaceView's root `.task(id: museionHome)` (first frame
/// + every repoint, whichever pane is showing); no public method takes
/// a Home parameter, callers pass none.
/// #193: setter internal — PostsModelWatcher's startWatching (the one
/// writer) is a split-out extension now.
var watchedHome: URL?
var watcher = PostsWatcher()
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
/// post.md files, not the library (see PostScanCache).
let scanCache = PostScanCache()
/// brief-28: the card scanner behind `refreshCards` — injectable so the
/// stale-result pin can HOLD an old-library scan past a repoint (a
/// detached disk read is otherwise faster than any test can arrange).
/// Per-model, never static (the hosted suite runs tests in parallel).
var scanPieceCards: @Sendable (URL) -> [FixCardStore.StoredFixCard] = FixCardStore.scan
/// brief-28 r1 (MF-1): the library scanner behind `rescan` — the same
/// injection shape, so the stale-Home pin can HOLD an old library's scan
/// past a repoint and watch its continuation land under the new binding.
var scanLibrary: @Sendable (URL, PostScanCache?) -> [Post] = Post.scan
/// #93: per-file watcher on the open external file — the #67 conflict
/// check reused verbatim for foreign files.
var externalWatcher = PostsWatcher()
/// #107: the project a NEW piece lands in — #108: an explicit pending
/// target first, else the selected non-archived post's project, else the
/// default. One home; newPost/importFiles must not drift.
var targetProject: String {
pendingProject
?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project
?? Post.defaultProject
}
/// Tear the watcher down on the main actor (its scheduling thread) —
/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
/// flushes the open session first (sidecar rides along). #96: quit also
/// flushes the external buffer — same posture, same moment.
/// #200: quit is a document departure — the flush half routes through
/// the departure gate (`documentsMayDepart`): an unanswered #67
/// conflict never writes over the foreign body, a failed flush or a
/// never-loaded retype lands its reason in lastError instead of
/// silently dropping the edits. The verdict itself is quitReply's, at
/// applicationShouldTerminate — this belt runs only at willTerminate.
/// Watchers stop either way — the process is leaving.
func shutdown() {
documentsMayDepart()
watcher.stop()
externalWatcher.stop()
}
/// New Post (#62): fresh in-memory draft, no folder, editor takes it.
/// #107: the draft targets the selected post's project (archived posts
/// target the default — new pieces are never born archived).
func newPost() {
let target = targetProject
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(project: target)
lastDraftWasOutline = false // #109: the afterglow died with the draft
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil
openPieceCards = [] // #23: no open piece, no cards
}
/// #109: New Outline — newPost's draft path with an outline draft instead:
/// body seeds one empty root node ("- "), the outline surface parses it.
/// Title keeps prose semantics (raw first line).
func newOutline() {
let target = targetProject
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(text: "- ", project: target, type: .outline)
lastDraftWasOutline = false // #109: a new draft resets the afterglow
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil
openPieceCards = [] // #23: no open piece, no cards
}
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
/// here. The saved post opens straight into an editing session — the
/// writer keeps typing where they were. #179: the write rides the rail.
func saveDraft() {
guard let draft else { return }
performWrite { home in
let post = try PostStore.writeNew(body: draft.text, project: draft.project, type: draft.type, home: home)
lastDraftWasOutline = draft.type == .outline // #109: covers the lagging rescan
self.draft = nil
pendingProject = nil // #108: the explicit target landed with the draft
selectedPostID = post.id
session = EditorSession(postID: post.id, home: home)
wireSession()
}
}
/// #30 (S2.7): New Post from Session — materialize the session-born
/// draft stamped `origin: ai` (never stats-eligible) and open it in
/// Posts (select's open path; the WorkspaceView selection onChange
/// hops the pane). Nil + lastError on failure; Cancel never gets here.
/// #179: the write rides the rail.
@discardableResult
func newPostFromSession(body: String) -> Post? {
var written: Post?
performWrite { home in
let post = try PostStore.writeNew(body: body, origin: .ai, home: home)
written = post
select(post.id)
}
return written
}
/// Select a Post; selecting anything abandons an unsaved draft (the
/// draft otherwise hijacks the editor — its only exits are save or
/// selecting away). #19: opening a post ends the previous session
/// (flush-on-selection-change, #64) and starts a new one. #92: it also
/// dismisses the external guest (flush first).
/// #111 (S7): a `type: outline` piece that parses with dropped prose
/// fires the mixed-content guard — the open is held (routing stays
/// prose) until the writer picks. The old session still ends here:
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String) {
guard watchedHome != nil else { return } // #179: no library, no open
guard dismissExternal() else { return } // brief-25: the guest's edits land or the switch aborts
// A reselect of the already-open piece is a no-op — INCLUDING a
// guarded one: the piece is open under a prior answer, and firing
// the ask again would nil its session without teardown (the armed
// debounce would then flush mid-ask, outside any owned session).
// brief-28: identity, not id — only THIS library's piece counts as
// open; a session born under another Home departs below.
if let session, let home = watchedHome, session.targets(postID: id, home: home) {
return
}
if let session {
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
}
if isGuardedOutline(id) {
outlineGuardPieceID = id
proseOverridePostID = nil
session = nil
draft = nil
pendingProject = nil
lastDraftWasOutline = false
selectedPostID = id
refreshCards() // #23: nil session — the held ask shows no cards
return
}
// The prior session was torn down above; openUnguarded's guards
// are dead code on this path (session is nil or a different id) —
// kept: one open body answers select and the ask alike.
openUnguarded(id)
proseOverridePostID = nil // #111: the override died with the open it covered
}
/// Draft typing from the editor (private(set) barrier).
func updateDraft(_ text: String) {
draft?.text = text
}
// MARK: - Cold Turkey (#162, map #158)
/// #162: can the writing lock arm on what's open? Mirrors the editor
/// column's branch precedence and outline routing (PostsPaneView) —
/// prose drafts, the external guest, and prose posts qualify; an
/// outline piece never does (#158 settle 11: Posts + drafts, not
/// Outline). Keep the expression in step with the editor branch.
var canArmWritingLock: Bool {
if let draft {
return draft.type != .outline
}
if externalSession != nil {
return true
}
// brief-28: this library's piece, by identity (Home, ID).
guard let session, let id = selectedPostID, openSessionTargets(id) else { return false }
let outline = id != proseOverridePostID
&& (lastDraftWasOutline || posts.first(where: { $0.id == id })?.type == .outline)
return !outline
}
/// #162: the live whole-document text of the surface the editor is
/// showing — the lock's baseline at Start. The per-keystroke feed
/// rides ProseTextView.onTextChange; this is the arm-time snapshot.
var editorBodyText: String? {
if let draft {
return draft.text
}
if let externalSession {
return externalSession.text
}
if let session, let id = selectedPostID, openSessionTargets(id) { // brief-28: this library's piece, by identity
return session.text
}
return nil
}
/// #146: internal — the split-out domain extensions wire sessions too.
func wireSession() {
let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message }
session?.onError = route
externalSession?.onError = route
}
}