Files
museion/Museion/PostsModel.swift
T
AlexKucera 1c697440d8
CI / ci (push) Canceled after 0s
feat(mentor): per-surface engine lifecycle (#137)
Profiles S4: passes run on their OWN one-shot engines —
`hermes acp -p museion-passN` spawns per pass run and tears down at
the verdict, so a model switch costs nothing (the next spawn reads
fresh config). The verdict streams into a TRANSIENT unrostered
transcript (#129's ruling: one Sessions surface over the chat
engine; a rostered pass session would be unresumable by the chat
engine). `beginPassSession` died with it — passes never mint
sessions; the #28 roster pins flipped to the transient posture.

The chat engine stays resident (adopted museion profile): a Chat
model change in Settings fires onChatSurfaceWrite after a
successful chat-surface write only, wired to requestRestart —
re-spawn in place when idle (resuming the pre-restart active
session), deferred to turn end while any turn streams (#129).

Missing-key posture (#132): refreshPassReadiness reads both pass
profiles' providers and their .env keys at pane entry; Run Pass
disables naming the provider with an Open Settings link, .unknown
never blocks, and the guard refuses before anything touches disk.

Finish-audit (ponytail/security/general fanout) applied: the
general reviewer's Medium — a session/new/load/fork completing
mid-pass stole the active surface and lost the Cancel to the wrong
engine — fixed with ONE claimActive gate across the post-await
activation writers, pinned deterministically via the fake's
loadReplayHold park + a mode-file flip (flip-verified: guard off
fails on the steal observables and the misrouted-cancel hang).
Also fixed: a spawn-window cancel loss in stopStreaming (keyed on
the transient entry, not the late-arriving wire id), and a
PRE-EXISTING rescan bug where a stale scan snapshot "vanished" a
just-opened piece and killed its session, cancelling the edit
debounce — the vanish-kill now re-checks disk and the watched
home. Ponytail cut ~59 lines of test duplication; the app target's
only force-unwrap is gone.

Suite 477 (was 472): EngineLifecycleTests new (own-engine
end-to-end, held-pass cancel, idle + deferred restart ordering,
readiness, steal pin), +3 Settings hook pins, one duplicate pin
deduplicated. swiftformat clean, swiftlint at HEAD baseline.

Closes #137
2026-10-28 17:26:40 +01:00

1034 lines
40 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// PostsModel.swift
// Museion
//
// #18 (S1.1): the Posts pane's write side — FSEvents watcher on the piece
// roots (projects/ + archive/, #107) with a ~0.5 s debounced rescan (#61),
// selection, and the New Post draft lifecycle (#62). Own ops route through
// the same rescan: one path.
// #108: project targeting + the move/archive/restore ops behind the
// variant-B library and the Archive pane.
//
import CoreServices
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()
}
/// Recursive FSEvents stream on one or more directories (#61): file-level
/// events, so nested `projects/<name>/<id>/post.md` edits from Finder fire
/// too — a plain dir-FD dispatch source only sees direct children and misses
/// them.
final nonisolated class PostsWatcher: @unchecked Sendable {
/// Fired on the main actor when anything under a watched path changes.
var onEvent: (@MainActor @Sendable () -> Void)?
private var stream: FSEventStreamRef?
func start(urls: [URL]) {
stop()
var context = FSEventStreamContext(
version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: nil,
release: nil,
copyDescription: nil,
)
// C function pointer — no captures; `self` rides the info pointer.
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
Task { @MainActor in watcher.onEvent?() }
}
guard let stream = FSEventStreamCreate(
kCFAllocatorDefault,
callback,
&context,
urls.map(\.path) as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
) else { return }
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(stream)
self.stream = stream
}
func stop() {
guard let stream else { return }
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
self.stream = nil
}
deinit { stop() }
}
/// 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).
private(set) var posts: [Post] = []
/// The selected Post's id; nil = nothing selected (empty editor).
private(set) var selectedPostID: String?
/// The in-memory draft for New Post (#62): no folder until first save.
private(set) var draft: PostDraft?
/// #19: the open post's editing session; nil while a draft is open or
/// nothing is selected.
private(set) 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).
private(set) var externalSession: EditorSession?
/// #94: a multi-file import waiting on its ONE Origin ask; the sheet
/// answers, then the batch runs.
private(set) 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.
private(set) 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).
private(set) 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.
private(set) 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.
private(set) 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).
private(set) 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.
private(set) 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.
private(set) var runningPass: PassKind?
/// #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.
private(set) var openPieceCards: [FixCardStore.StoredFixCard] = []
/// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String?
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
private var watcher = PostsWatcher()
/// #93: per-file watcher on the open external file — the #67 conflict
/// check reused verbatim for foreign files.
private var externalWatcher = PostsWatcher()
/// Bind a Home: ensure both container roots exist (FSEvents on a missing
/// path is unreliable; archive/ is a watcher root now, #107), initial
/// scan + start (or restart) the watcher. Called from
/// `.task(id: home)` — re-fires on Home repoint.
func bind(home: URL) {
startWatching(home: home)
Task { await rescan() }
}
// MARK: Watcher (#61)
private func startWatching(home: URL) {
guard watchedHome != home else { return }
watchedHome = home
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
for root in roots {
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
}
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
watcher.start(urls: roots)
}
/// Off-main scan; keeps selection valid across the fresh refresh.
/// FSEvents already coalesces bursts within its 0.5 s latency window —
/// no second debounce on top.
private func rescan() async {
guard let home = watchedHome else { return }
// Scan + the #67 disk read both run off-main (a synced large post.md
// must never stall the UI on a watcher burst).
let openPostID = session?.postID
// #114 audit: identity, not id — a same-id reopen (convert/restore/
// move) must not receive the OLD session's stale disk text as a
// spurious #67 conflict.
let openSession = session
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = Post.scan(home: home)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.value
guard !Task.isCancelled else { return }
posts = scanned
if let id = selectedPostID, !posts.contains(where: { $0.id == id }),
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
// current selection — bind's initial rescan (detached scan over the
// empty tree) can land its continuation after a select its scan never
// saw, "vanishing" a piece that exists. Disk is the truth for
// vanished; a stale snapshot must not kill a live session (teardown
// cancels the debounce — unflushed edits would die with it).
// #137 audit (finish): a scan that outlived a Home repoint speaks
// for the OLD tree — never let it kill a session selected under
// the NEW home (the id is missing from the old snapshot by
// construction); the next rescan under the new home owns it.
watchedHome == home, PostStore.folder(of: id, home: home) == nil
{
selectedPostID = nil // the post vanished (deleted in Finder or here)
if let open = session, open.postID == id {
open.teardown(flushFirst: false) // post is gone; cancel the debounce
session = nil
}
}
// #67: watcher echo check on the open post — equality against the
// session's lastFlushedText suppresses our own writes exactly.
if openSession === session, let openDiskText {
openSession?.diskDidChange(diskText: openDiskText)
}
// #23: the open piece's stored fix cards ride the same rescan —
// the watcher fires on <piece>/cards/ writes too.
refreshCards(home: home)
}
// MARK: Own ops (route through the same rescan, #61)
// ponytail: the PostStore calls here run on MainActor — small single-file
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
// them in Task.detached like rescan.
/// #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.
private 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
dismissExternal() // #92: opening a draft dismisses the guest
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
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
dismissExternal()
session?.teardown(flushFirst: true)
session = nil
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
}
/// #92: dismiss the external guest slot, flushing pending edits (the
/// guest is always leaving for somewhere — same posture as post
/// selection change).
private func dismissExternal() {
externalSession?.teardown(flushFirst: true)
externalSession = nil
externalWatcher.stop()
}
/// 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. Rescans immediately (the watcher
/// would too, after its window).
func saveDraft(home: URL) {
guard let draft else { return }
do {
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()
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #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.
@discardableResult
func newPostFromSession(body: String, home: URL) -> Post? {
do {
let post = try PostStore.writeNew(body: body, origin: .ai, home: home)
select(post.id, home: home)
lastError = nil
Task { await rescan() }
return post
} catch {
lastError = error.localizedDescription
return nil
}
}
/// 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, home: URL) {
dismissExternal()
// 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 {
session.teardown(flushFirst: true)
}
if isGuardedOutline(id, home: home) {
outlineGuardPieceID = id
proseOverridePostID = nil
session = nil
draft = nil
pendingProject = nil
lastDraftWasOutline = false
selectedPostID = id
refreshCards(home: home) // #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, home: home)
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
}
/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
/// first (rename reads the file from disk — unflushed edits must land
/// before the move), then reopens a session at the new id. Sets lastError
/// on failure.
func rename(_ post: Post, to title: String, home: URL) {
// #108 audit 2: rename reads the file from disk — a failed write
// aborts (moving the folder would strand unflushed edits), and the
// session stays up, dirty and honest.
guard flushOrAbort(post.id) else { return }
do {
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
if session?.postID == post.id {
session = EditorSession(postID: moved.id, home: home)
wireSession()
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
/// was the post; the session is torn down (cancel only — the folder is
/// leaving, a flush would resurrect nothing but churn the watcher).
func trash(_ post: Post, home: URL) {
do {
try PostStore.trash(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
if let open = session, open.postID == post.id {
open.teardown(flushFirst: false)
session = nil
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
// MARK: Projects (#108)
/// #108: New Project's confirmed sheet — the folder exists, the next
/// draft targets it, and opens now.
func newProjectPending(named name: String) {
pendingProject = name
newPost()
}
/// #108: raw create — the sheet composes on it. The failure reason on
/// false (shown inline in the sheet; never routed into lastError — the
/// strip behind the sheet must not double-message one error).
func createProject(named name: String, home: URL) -> String? {
do {
try PostStore.createProject(named: name, home: home)
return nil // success
} catch {
return error.localizedDescription
}
}
/// #108: File ▸ New Project… — stage the ask (WorkspaceView presents).
func stageNewProject() {
askNewProject = true
}
/// #108: the ask's Cancel.
func cancelNewProject() {
askNewProject = false
}
/// #108 audit 2: the Move-to-Project list — every project on disk under
/// projects/ plus the default (bind creates the roots, not posts/ — an
/// empty Home must still offer it), localized-sorted to match the
/// library's section order.
func moveTargets(home: URL) -> [String] {
let root = home.appendingPathComponent("projects", isDirectory: true)
let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
var names = Set(onDisk.filter { !$0.hasPrefix(".") })
names.insert(Post.defaultProject)
return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
/// #108 audit: flush the open piece, aborting when the write failed — a
/// folder move must never carry away text that didn't land (the move
/// itself succeeds exactly when a file write fails). Returns false with
/// lastError set; the session stays up, dirty and honest.
private func flushOrAbort(_ postID: String) -> Bool {
guard let session, session.postID == postID else { return true }
// #114 audit: an unanswered #67 conflict means disk holds foreign
// text with the session's version unwritten — proceeding would act
// on the foreign body and discard the editor's. Abort; the alert
// stays up for the writer to answer, then the op retries.
if session.conflictAlert {
lastError = "This piece changed on disk underneath you — answer the reload question first."
return false
}
if !session.flush() {
// Append, don't replace — the flush already routed the write's
// localizedDescription into lastError; only say what was skipped.
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
return false
}
return true
}
/// #108: Move to Project — flush first (move reads disk), then the
/// folder moves under projects/. Id stays the same; the session is
/// reopened anyway so folderURL re-resolves to the new parent.
func moveToProject(_ post: Post, project: String, home: URL) {
guard flushOrAbort(post.id) else { return }
do {
try PostStore.move(post, to: project, home: home)
if session?.postID == post.id {
session = EditorSession(postID: post.id, home: home)
wireSession()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #108: Move to Archive. Archiving the open piece clears it — the
/// editor is empty until the next selection (archived pieces open from
/// the Archive pane, where they're listed).
func archivePost(_ post: Post, home: URL) {
guard flushOrAbort(post.id) else { return }
do {
try PostStore.archive(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
}
if let open = session, open.postID == post.id {
open.teardown(flushFirst: false) // already flushed above
session = nil
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #108: Move Back — the restored piece lands in its project and opens;
/// the writer stays in the piece they just revived. A session already
/// open on the piece survives `select` — reopen it so folderURL points
/// at projects/, not the archive path it was born with.
func restorePost(_ post: Post, home: URL) {
guard flushOrAbort(post.id) else { return }
do {
try PostStore.restore(post, home: home)
if let open = session, open.postID == post.id {
session = EditorSession(postID: post.id, home: home)
wireSession()
} else {
select(post.id, home: home)
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #108: whole-project unarchive from the Archive pane's section header.
/// Flush-first like every folder move (a dirty open piece inside the
/// project would otherwise race the move), and its session is reopened so
/// folderURL re-resolves off archive/ (same reason as restorePost).
func unarchiveProject(_ name: String, home: URL) {
/// #108 audit 2: disk-derived membership — the posts snapshot is stale
/// the moment a Finder move lands. Captured BEFORE the move: after it
/// the piece resolves under projects/ and its archive membership is
/// invisible. dir − 1 = project dir (…/archive/<name>), − 2 = root.
func openPieceInArchivedProject() -> String? {
guard let id = session?.postID,
let projectDir = PostStore.folder(of: id, home: home)?.deletingLastPathComponent(),
projectDir.lastPathComponent == name,
projectDir.deletingLastPathComponent().lastPathComponent == "archive"
else { return nil }
return id
}
let openID = openPieceInArchivedProject()
if let openID {
// #108 audit 2: the only #108 folder move that skipped the gate.
guard flushOrAbort(openID) else { return }
}
do {
try PostStore.unarchiveProject(name, home: home)
if let openID {
session = EditorSession(postID: openID, home: home)
wireSession()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
// MARK: External buffer (#91–#93) + Import (#94/#95)
/// #91/#92: open an external markdown file in the guest slot — one at a
/// time; opening anything else (file, Post, draft) flushed and replaced
/// it first. A Post session/draft stands down while the guest is up
/// (the editor column is the guest's; the selection stays for return).
/// Local files only (a dragged web link is not a document) and symlinks
/// resolve to their real target so the in-place write never severs the
/// link (rename over a symlink replaces it).
func openExternal(_ url: URL) {
guard url.isFileURL else { return }
let target = url.resolvingSymlinksInPath()
dismissExternal()
session?.teardown(flushFirst: true) // #92: the guest takes the column
session = nil
draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask
openPieceCards = [] // #23: the guest is not a piece
externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
externalSession = nil
return
}
wireSession()
startExternalWatch(url: target)
}
/// #93: watch the open external file — its rescan is the #67 disk-change
/// check, reused verbatim for foreign files. PostsWatcher fires on the
/// main actor already; no re-hop needed.
private func startExternalWatch(url: URL) {
externalWatcher.onEvent = { [weak self] in
guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
session.diskDidChange(diskText: disk)
}
externalWatcher.start(urls: [url.deletingLastPathComponent()])
}
/// #94: stage a multi-file import — the ONE Origin ask presents; the
/// sheet's answer runs the batch.
func stageImport(_ urls: [URL]) {
guard !urls.isEmpty else { return }
pendingImportURLs = urls
}
/// #94: dismiss the ask without an answer — the batch drops.
func cancelImport() {
pendingImportURLs = nil
}
/// #94/#95: run the batch after the Origin answer — copy each file in as
/// a Post; a per-file failure continues the batch into lastError (stated
/// default, reversible; never an alert, never an abort). The last
/// imported post opens; a failure anywhere keeps its message up even
/// when other files landed. #107: the batch lands in the selected
/// post's project (newPost's target rule).
func importFiles(origin: Post.Origin, home: URL) {
guard let urls = pendingImportURLs else { return }
pendingImportURLs = nil
let project = targetProject
var last: Post?
var failures = 0
for url in urls {
do {
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
} catch {
failures += 1
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
}
}
if let last {
select(last.id, home: home)
}
if failures == 0 {
lastError = nil
}
Task { await rescan() }
}
private func wireSession() {
let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message }
session?.onError = route
externalSession?.onError = route
}
}
// MARK: Mixed-content outline guard (#111, S7)
extension PostsModel {
/// A `type: outline` piece that parses with dropped prose — the guard's
/// target. The old session already ended by the time this runs; its
/// flush was prose-mode, so it couldn't drop anything.
/// Type: the scan's word when the list knows it (archive pane opens,
/// app-start selection), the frontmatter's word during the rescan lag
/// (the same window lastDraftWasOutline covers) — ONE disk read derives
/// both. No watched home yet (pre-bind) = post: nothing to guard.
private func isGuardedOutline(_ id: String, home: URL) -> Bool {
guard let dir = PostStore.folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type {
known
} else {
Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
}
return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body)
}
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
/// outliner never mounts, nothing drops); Outline = explicit consent,
/// opens the outliner (saves normalize/drop as today). Cancel = back
/// out (no session); the piece stays guarded on the next open.
func openGuardedOutlineInProse(home: URL) {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
proseOverridePostID = id // routing: prose until the next open
openUnguarded(id, home: home)
}
func openGuardedOutlineAsOutline(home: URL) {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
openUnguarded(id, home: home)
}
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
/// nothing stays selected over the empty editor).
func cancelOutlineGuard() {
outlineGuardPieceID = nil
if session == nil {
selectedPostID = nil
}
}
/// #111 (S7): the open with the guard passed (either answer or a clean
/// parse) — the plain select body. No re-check: the answer is the
/// explicit choice the ruling requires.
private func openUnguarded(_ id: String, home: URL) {
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
}
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
draft = nil
pendingProject = nil
lastDraftWasOutline = false
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
refreshCards(home: home) // #23: the newly opened piece's cards, now
}
}
// MARK: Convert to Post (#114, S4)
/// The staged ask: which piece, and whether the headings ladder would
/// drop prose lines (mixed content — the sheet warns, verbatim keeps
/// everything).
struct PendingConversion {
let id: String
let lossy: Bool
}
extension PostsModel {
/// #114 (S4): row-menu entry — stage the ask. Outline pieces only.
/// The open session's text is the truth when the piece is open — disk
/// lags the debounce, and a stale-clean read would drop the warning
/// for prose typed since the last flush (#114 audit).
func stageConversion(_ post: Post, home: URL) {
guard post.type == .outline else { return }
let body: String = if let session, session.postID == post.id {
session.text
} else {
PostStore.readBody(id: post.id, home: home) ?? ""
}
pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body))
}
/// #114 (S4): the ask's Cancel (binding dismissal).
func cancelConversion() {
pendingConversion = nil
}
/// #114 (S4): the answer. Flush-first when the piece is open (the
/// transform reads disk), flip `type` + transform the body once, then
/// reopen the session routed to prose — proseOverridePostID covers the
/// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that
/// isn't open just converts; nothing else moves. One-way in v1.
func convertToPost(headingsLadder: Bool, home: URL) {
guard let pending = pendingConversion else { return }
pendingConversion = nil
guard flushOrAbort(pending.id) else { return }
do {
// The sheet's warning covered the STAGED body. If the
// answer-time body went lossy behind the ask (foreign write,
// late edit) and the writer was never warned, Headings would
// drop unconsented prose — abort, nothing converted (#114 audit).
if headingsLadder, !pending.lossy,
let body = PostStore.readBody(id: pending.id, home: home),
OutlineTree.parsesWithLoss(body)
{
lastError = "The outline changed since the sheet opened — nothing was converted."
return
}
try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home)
if session?.postID == pending.id {
session?.teardown(flushFirst: false) // flushOrAbort already wrote
session = nil
proseOverridePostID = pending.id
openUnguarded(pending.id, home: home)
}
if outlineGuardPieceID == pending.id {
// Multi-window: the held #111 ask targets an outline that no
// longer is — dismiss it as a cancel (the ask's own teardown).
cancelOutlineGuard()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
}
// MARK: Pass orchestration (#24, S3.1)
extension PostsModel {
/// #24 (S3.1): run one structured critique pass over the OPEN piece.
/// The pre-pass snapshot lands before the engine sees the text; the
/// minimal stub (PassContext) crosses the bridge and the critique
/// streams into the mentor pane. Pass State advances ONLY when the
/// engine's turn ends normally — never on cancel, refusal, or crash,
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings, BEFORE the open-piece guard so nothing writes
// to disk (not even the pre-pass snapshot).
if case let .missingKey(label) = mentor.readiness(for: kind) {
lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys."
return
}
// The pass targets the open Piece: a never-saved draft has no
// folder, and the external guest and a held #111 guard ask are
// not Pieces.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a pass."
return
}
guard flushOrAbort(id) else { return } // the engine reads disk
do {
try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home)
} catch {
lastError = error.localizedDescription
return
}
// #31 (S5.1): unaided-first-draft stats — fires at the invocation,
// before the engine sees anything; eligibility (writer origin, First
// Draft, post type) is read from disk. A failed capture must never
// fail the pass (decay-clock posture), so the Bool is ignored.
PostStore.captureFirstDraftStats(id: id, body: session.text, home: home)
// #137 (S4): runningPass goes live BEFORE the mentor awaits —
// flush/snapshot/capture above are synchronous, so nothing can slip
// between the guards and the flag: the #124 Cancel-visibility
// invariant now holds for the WHOLE run, pass-engine spawn included.
runningPass = kind
defer { runningPass = nil }
let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch)
// #137: the pass runs on its OWN one-shot engine and streams into the
// transient pass transcript — never rostered (#129, ADR-0014).
let outcome = await mentor.runPass(kind: kind, stub: stub, pieceTitle: title(of: id))
guard case let .ended(stopReason) = outcome, stopReason != "refusal" else {
return // cancelled / refused / failed — the transcript tells the story
}
do {
_ = try PostStore.advancePassState(id: id, kind: kind, home: home)
lastError = nil
Task { await rescan() } // the library regroups by Pass State
} catch {
lastError = error.localizedDescription
}
}
/// #24 (S3.1): the pass bar's Cancel — the existing session/cancel
/// rail stops the agent; nothing advances (runPass reads .cancelled).
func cancelPass(mentor: MentorSessionModel) {
guard runningPass != nil else { return }
mentor.stopStreaming()
}
}
// MARK: Stored fix cards (#23, M2 slice 3)
extension PostsModel {
/// #23 (M2, slice 3): re-derive `openPieceCards` from the OPEN piece's
/// `<piece>/cards/` (FixCardStore.scan — any MCP client's submissions,
/// newest-first; archive pieces resolve through folder(of:) too). The
/// nil-session rule clears: draft, external guest, held guard ask,
/// nothing open → []. Called at the rescan tail and the open
/// transitions — the piece-roots watcher already fires on cards/ writes.
func refreshCards(home: URL) {
guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else {
openPieceCards = []
return
}
// Plain disk reads re-run on every watcher burst (typing retriggers
// rescan) — keep the I/O off MainActor, same posture as rescan's
// Post.scan. The id re-check on hop-back drops a scan that raced a
// piece switch.
Task.detached { [weak self] in
let cards = FixCardStore.scan(pieceURL: folder)
await MainActor.run { [weak self] in
guard let self, session?.postID == id else { return }
openPieceCards = cards
}
}
}
/// The piece's display title (fallback: id) — runPass, the pass bar,
/// and the Fix Cards palette share this one lookup (review: three
/// hand-copies).
func title(of id: String) -> String {
posts.first(where: { $0.id == id })?.title ?? id
}
}
// MARK: Fix Card apply/skip/done (#25, S3.2/S3.3)
/// #25 (S3.2/S3.3): what Apply did — the edit landed, the anchor went
/// stale (no text touched, card flagged), or the operation refused with
/// a reason for the error strip.
enum FixCardApplyOutcome: Equatable {
case applied
case stale
case refused(String)
}
extension PostsModel {
/// #25 (S3.2/S3.3): Apply a mechanical card — the blocking ask already
/// happened in the UI (ask-before trust level); this lands the edit.
/// Dirty buffer lands first (Apply reads live text); an unanswered #67
/// conflict aborts here with the existing wording. A stale anchor
/// flags the card and touches no text. A failed close after a landed
/// edit is reported via lastError, never silent.
@discardableResult
func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome {
guard card.status == .open else { return .refused("card already closed") }
guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") }
guard let session, let postID = session.postID else {
return .refused("open the piece to work its cards")
}
guard flushOrAbort(postID) else { return .refused(lastError ?? "edits did not land") }
guard let newText = FixCardStore.appliedText(of: card, in: session.text) else {
// Stale anchor — the Post changed after the card was issued:
// persist the honest flag, select and change nothing. A failed
// flag write surfaces like the applied path's — never silent.
do {
_ = try FixCardStore.close(
pieceURL: session.passPieceURL, id: card.id, status: .open, anchorStatus: .stale,
)
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
return .stale
}
guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") }
closeCard(card, status: .applied, home: home)
return .applied
}
/// #25 (S3.3): Skip — not this instance. Closes the card recording
/// NOTHING beyond the status flip (CONTEXT.md).
func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .skipped, home: home)
}
/// #25 (S3.3): Done — the writer rewrote the span themselves. Same
/// flip, different terminal.
func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .done, home: home)
}
private func closeCard(
_ card: FixCardStore.StoredFixCard,
status: FixCardStore.StoredFixCard.Status,
home: URL,
) {
guard let session else {
lastError = "open the piece to work its cards"
return
}
do {
_ = try FixCardStore.close(pieceURL: session.passPieceURL, id: card.id, status: status)
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
}
}
// MARK: Fix Card promote (#26, S4.1/S4.3)
/// #26 (S4.1): what Promote did — the Learning landed, or the operation
/// refused with a reason (the ask sheet shows it; lastError carries it).
enum FixCardPromoteOutcome: Equatable {
case promoted
case refused(String)
}
extension PostsModel {
/// #26 (S4.1/S4.3): Promote a card into ONE plain markdown Learning
/// under `<home>/learnings/<type>s/` — the writer's EXPLICIT
/// confirmation only (one confirm = one entry, never a repetition
/// counter; the store guarantees the one-stamp rule). Touches no text
/// and flushes nothing: this writes a Learning, not an edit.
@discardableResult
func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome {
guard card.promotedAt == nil else { return .refused("card already promoted") }
guard let session else { return .refused("open the piece to work its cards") }
do {
_ = try FixCardStore.promote(pieceURL: session.passPieceURL, card: card)
} catch {
lastError = "learning write failed: \(error.localizedDescription)"
return .refused("learning write failed: \(error.localizedDescription)")
}
refreshCards(home: home)
return .promoted
}
}