Files
museion/Museion/PostsModel.swift
T
AlexKucera ffb9457a63
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
integrate main: #193 PostsModel split (Watcher/Writes/Imports) into failed-flush departure guard
# Conflicts:
#	Museion/PostsModel.swift
#	docs/devlog/INDEX.md
2026-11-17 20:12:53 +01:00

325 lines
14 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 {
/// 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
/// #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] = []
/// 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()
/// #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.
func shutdown() {
session?.flush()
externalSession?.flush()
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).
if let session, session.postID == id {
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
}
guard let session, session.postID == selectedPostID else { return false }
let outline = session.postID != proseOverridePostID
&& (lastDraftWasOutline || posts.first(where: { $0.id == session.postID })?.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, session.postID == selectedPostID {
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
}
}