From 902e860bd8193fc852545b8f2dd288613f937240 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 17 Nov 2026 17:39:39 +0100 Subject: [PATCH] refactor(posts): split PostsModel into Watcher/Writes/Imports files (#193) --- Museion/AGENTS.md | 5 +- Museion/PostsModel.swift | 502 ++------------------------------ Museion/PostsModelImports.swift | 104 +++++++ Museion/PostsModelWatcher.swift | 151 ++++++++++ Museion/PostsModelWrites.swift | 233 +++++++++++++++ 5 files changed, 518 insertions(+), 477 deletions(-) create mode 100644 Museion/PostsModelImports.swift create mode 100644 Museion/PostsModelWatcher.swift create mode 100644 Museion/PostsModelWrites.swift diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 48b2f55..0f8552c 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -36,7 +36,10 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `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`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; 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); 401/403 → authFailed with `error_description`; `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). 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. 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. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept. -- `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`; watcher+rescan in a file-scope extension). **#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`, private(set) — set only by `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). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; 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); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). 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. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). 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. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `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`) — 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. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `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 or an unanswered #67 conflict aborts with nothing changed — the alert stays up), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive). +- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal`/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); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`). - `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID. - `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load. - `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction. diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index c49ca93..c95c7f5 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -2,24 +2,19 @@ // 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. -// #146: the domain extensions (#111/#114/#24/#122/#23/#25/#26) live in -// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching -// + rescan sit in the file-scope watcher extension below (type-body -// ceiling). +// #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 (card closes and the pass substrate stay off it: they -// never regroup the library); the model owns the Home (watchedHome), no -// method takes one. +// 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 CoreServices import Foundation import Observation @@ -38,55 +33,6 @@ struct PostDraft { let mountID = UUID() } -/// Recursive FSEvents stream on one or more directories (#61): file-level -/// events, so nested `projects///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.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 @@ -94,7 +40,8 @@ final nonisolated class PostsWatcher: @unchecked Sendable { final class PostsModel { /// The scanned, title-sorted list — mirrors `projects/` + `archive/` at /// all times (#107). - private(set) var posts: [Post] = [] + /// #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 @@ -103,7 +50,8 @@ final class PostsModel { /// 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. - private(set) var contentRevision = 0 + /// #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. @@ -121,11 +69,13 @@ final class PostsModel { /// #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? + /// #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. - private(set) var pendingImportURLs: [URL]? + /// #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 @@ -136,7 +86,8 @@ final class PostsModel { /// #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 + /// #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 @@ -189,63 +140,21 @@ final class PostsModel { /// 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. - /// `private(set)` — the setter stays PostsModel.swift-file-private. - private(set) var watchedHome: URL? - private var watcher = PostsWatcher() + /// #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). - private let scanCache = PostScanCache() + let scanCache = PostScanCache() /// #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 WorkspaceView's - /// root `.task(id: museionHome)` — first frame and every Home repoint, - /// pane-independent. - func bind(home: URL) { - startWatching(home: home) - Task { await rescan() } - } - - // 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. - - /// #179: the write rail — ONE seam pairs every library store write with - /// exactly one rescan and owns the error strip. A verb passes its - /// PostStore write (plus any post-write state surgery); a throw lands - /// its reason in the strip with nothing rescanned, a clean run rescans - /// once. The strip clears BEFORE the write, so a batch write that sets - /// its own per-file failure messages mid-closure (importFiles) keeps - /// them. The editor's debounced flush stays OUTSIDE the rail — its - /// error semantics are the session's own (EditorSession.onError). - /// Returns nil when the write landed; the failure reason otherwise - /// (createProject hands that to its sheet). - @discardableResult - func performWrite(_ write: (URL) throws -> Void) -> String? { - guard let home = watchedHome else { - lastError = "No library is open yet — nothing was changed." - return lastError - } - lastError = nil - do { - try write(home) - Task { await rescan() } - return nil - } catch { - lastError = error.localizedDescription - return lastError - } - } + 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. - private var targetProject: String { + var targetProject: String { pendingProject ?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project ?? Post.defaultProject @@ -294,16 +203,6 @@ final class PostsModel { 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). - /// #146: internal — the split-out domain extensions dismiss too. - 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. #179: the write rides the rail. @@ -417,274 +316,6 @@ final class PostsModel { return nil } - /// 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. #179: the - /// write rides the rail. - func rename(_ post: Post, to title: String) { - // #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 } - performWrite { home in - 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() - } - } - } - } - - /// 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). - /// #179: the write rides the rail. - func trash(_ post: Post) { - performWrite { home in - 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 - } - } - } - } - - // 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. #179: rides the write - /// rail (one rescan pairs the new folder); the failure reason is BOTH - /// returned for the sheet's inline display AND owned by the strip — - /// the rail posture replaces the old sheet-only rule. - func createProject(named name: String) -> String? { - performWrite { try PostStore.createProject(named: name, home: $0) } - } - - /// #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() -> [String] { - guard let home = watchedHome else { return [Post.defaultProject] } - 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. - /// #33: internal — the Micropub draft flow (Micropub.swift) flushes - /// through the same rail. - 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. - /// #179: the write rides the rail. - func moveToProject(_ post: Post, project: String) { - guard flushOrAbort(post.id) else { return } - performWrite { home in - try PostStore.move(post, to: project, home: home) - if session?.postID == post.id { - session = EditorSession(postID: post.id, home: home) - wireSession() - } - } - } - - /// #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). #179: the write rides the - /// rail. - func archivePost(_ post: Post) { - guard flushOrAbort(post.id) else { return } - performWrite { home in - 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 - } - } - } - - /// #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. - /// #179: the write rides the rail. - func restorePost(_ post: Post) { - guard flushOrAbort(post.id) else { return } - performWrite { home in - 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) - } - } - } - - /// #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). - /// #179: the write rides the rail. - func unarchiveProject(_ name: String) { - // #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/), − 2 = root. - guard let boundHome = watchedHome else { return } - func openPieceInArchivedProject() -> String? { - guard let id = session?.postID, - let projectDir = PostStore.folder(of: id, home: boundHome)?.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 } - } - performWrite { home in - try PostStore.unarchiveProject(name, home: home) - if let openID { - session = EditorSession(postID: openID, home: home) - wireSession() - } - } - } - - // 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). #179: the batch rides the - /// rail — the strip was cleared up front, so the per-file failure - /// messages the loop sets survive the rail's success tail. - func importFiles(origin: Post.Origin) { - guard let urls = pendingImportURLs else { return } - pendingImportURLs = nil - let project = targetProject - var last: Post? - performWrite { home in - for url in urls { - do { - last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) - } catch { - lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" - } - } - } - if let last { - select(last.id) - } - } - /// #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 } @@ -692,84 +323,3 @@ final class PostsModel { externalSession?.onError = route } } - -// MARK: Watcher (#61) — #146: file-scope extension (type_body_length) - -extension PostsModel { - 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. - /// #146: internal — the split-out domain extensions trigger rescans. - 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 scanMemo = scanCache // detached capture, not a property read - // The search's content signal: a re-read post.md (a cache miss) - // changed library content even when its Post compares equal. Read - // the counter before the scan so the delta after it says "this - // scan saw disk change" (#144's mounted half). - let missesBefore = scanMemo.misses - let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { - let posts = Post.scan(home: home, cache: scanMemo) - let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } - return (posts, disk) - }.value - guard !Task.isCancelled else { return } - // #143: @Observable invalidates on assignment regardless of equality — - // skip the no-op so panes don't regroup on our own autosave echoes. - let listChanged = scanned != posts - if listChanged { - posts = scanned - } - // #144's mounted half: any list change OR any re-read file bumps the - // content revision — the search snapshot's invalidation signal. - // Archive/trash/rename arrive as list changes; a body-only edit as - // a cache miss (metadata-equal — the skip above keeps the panes - // still, the bump alone re-keys the mounted search). - if listChanged || scanMemo.misses > missesBefore { - contentRevision += 1 - } - // 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. - if let id = selectedPostID, !posts.contains(where: { $0.id == id }), 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 /cards/ writes too. - refreshCards() - } -} diff --git a/Museion/PostsModelImports.swift b/Museion/PostsModelImports.swift new file mode 100644 index 0000000..55fc5aa --- /dev/null +++ b/Museion/PostsModelImports.swift @@ -0,0 +1,104 @@ +// +// PostsModelImports.swift +// Museion +// +// #193: the external guest (#91–#93) and the import batch (#94/#95), +// moved from PostsModel.swift (file-length ceiling) — openExternal, +// dismissExternal, the guest watch, and stageImport/cancelImport/ +// importFiles, code unchanged. +// + +import Foundation + +extension PostsModel { + /// #92: dismiss the external guest slot, flushing pending edits (the + /// guest is always leaving for somewhere — same posture as post + /// selection change). + /// #146: internal — the split-out domain extensions dismiss too. + func dismissExternal() { + externalSession?.teardown(flushFirst: true) + externalSession = nil + externalWatcher.stop() + } + + // 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). #179: the batch rides the + /// rail — the strip was cleared up front, so the per-file failure + /// messages the loop sets survive the rail's success tail. + func importFiles(origin: Post.Origin) { + guard let urls = pendingImportURLs else { return } + pendingImportURLs = nil + let project = targetProject + var last: Post? + performWrite { home in + for url in urls { + do { + last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) + } catch { + lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" + } + } + } + if let last { + select(last.id) + } + } +} diff --git a/Museion/PostsModelWatcher.swift b/Museion/PostsModelWatcher.swift new file mode 100644 index 0000000..6669176 --- /dev/null +++ b/Museion/PostsModelWatcher.swift @@ -0,0 +1,151 @@ +// +// PostsModelWatcher.swift +// Museion +// +// #193: the watching domain of PostsModel, moved from PostsModel.swift +// (file-length ceiling) — the PostsWatcher FSEvents stream (#61), Home +// binding, startWatching, and the rescan rail, code unchanged. +// + +import CoreServices +import Foundation + +/// Recursive FSEvents stream on one or more directories (#61): file-level +/// events, so nested `projects///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.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() } +} + +// MARK: Watcher (#61) + +extension PostsModel { + /// 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 WorkspaceView's + /// root `.task(id: museionHome)` — first frame and every Home repoint, + /// pane-independent. + func bind(home: URL) { + startWatching(home: home) + Task { await rescan() } + } + + 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. + /// #146: internal — the split-out domain extensions trigger rescans. + 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 scanMemo = scanCache // detached capture, not a property read + // The search's content signal: a re-read post.md (a cache miss) + // changed library content even when its Post compares equal. Read + // the counter before the scan so the delta after it says "this + // scan saw disk change" (#144's mounted half). + let missesBefore = scanMemo.misses + let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { + let posts = Post.scan(home: home, cache: scanMemo) + let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } + return (posts, disk) + }.value + guard !Task.isCancelled else { return } + // #143: @Observable invalidates on assignment regardless of equality — + // skip the no-op so panes don't regroup on our own autosave echoes. + let listChanged = scanned != posts + if listChanged { + posts = scanned + } + // #144's mounted half: any list change OR any re-read file bumps the + // content revision — the search snapshot's invalidation signal. + // Archive/trash/rename arrive as list changes; a body-only edit as + // a cache miss (metadata-equal — the skip above keeps the panes + // still, the bump alone re-keys the mounted search). + if listChanged || scanMemo.misses > missesBefore { + contentRevision += 1 + } + // 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. + if let id = selectedPostID, !posts.contains(where: { $0.id == id }), 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 /cards/ writes too. + refreshCards() + } +} diff --git a/Museion/PostsModelWrites.swift b/Museion/PostsModelWrites.swift new file mode 100644 index 0000000..fe9a582 --- /dev/null +++ b/Museion/PostsModelWrites.swift @@ -0,0 +1,233 @@ +// +// PostsModelWrites.swift +// Museion +// +// #193: the #179 write rail and the structural library ops, moved from +// PostsModel.swift (file-length ceiling) — performWrite, flushOrAbort, +// rename/trash, the #108 project ops, and move/archive/restore, code +// unchanged. +// + +import Foundation + +extension PostsModel { + // 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. + + /// #179: the write rail — ONE seam pairs every library store write with + /// exactly one rescan and owns the error strip. A verb passes its + /// PostStore write (plus any post-write state surgery); a throw lands + /// its reason in the strip with nothing rescanned, a clean run rescans + /// once. The strip clears BEFORE the write, so a batch write that sets + /// its own per-file failure messages mid-closure (importFiles) keeps + /// them. The editor's debounced flush stays OUTSIDE the rail — its + /// error semantics are the session's own (EditorSession.onError). + /// Returns nil when the write landed; the failure reason otherwise + /// (createProject hands that to its sheet). + @discardableResult + func performWrite(_ write: (URL) throws -> Void) -> String? { + guard let home = watchedHome else { + lastError = "No library is open yet — nothing was changed." + return lastError + } + lastError = nil + do { + try write(home) + Task { await rescan() } + return nil + } catch { + lastError = error.localizedDescription + return lastError + } + } + + /// 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. #179: the + /// write rides the rail. + func rename(_ post: Post, to title: String) { + // #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 } + performWrite { home in + 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() + } + } + } + } + + /// 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). + /// #179: the write rides the rail. + func trash(_ post: Post) { + performWrite { home in + 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 + } + } + } + } + + // 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. #179: rides the write + /// rail (one rescan pairs the new folder); the failure reason is BOTH + /// returned for the sheet's inline display AND owned by the strip — + /// the rail posture replaces the old sheet-only rule. + func createProject(named name: String) -> String? { + performWrite { try PostStore.createProject(named: name, home: $0) } + } + + /// #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() -> [String] { + guard let home = watchedHome else { return [Post.defaultProject] } + 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. + /// #33: internal — the Micropub draft flow (Micropub.swift) flushes + /// through the same rail. + 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. + /// #179: the write rides the rail. + func moveToProject(_ post: Post, project: String) { + guard flushOrAbort(post.id) else { return } + performWrite { home in + try PostStore.move(post, to: project, home: home) + if session?.postID == post.id { + session = EditorSession(postID: post.id, home: home) + wireSession() + } + } + } + + /// #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). #179: the write rides the + /// rail. + func archivePost(_ post: Post) { + guard flushOrAbort(post.id) else { return } + performWrite { home in + 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 + } + } + } + + /// #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. + /// #179: the write rides the rail. + func restorePost(_ post: Post) { + guard flushOrAbort(post.id) else { return } + performWrite { home in + 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) + } + } + } + + /// #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). + /// #179: the write rides the rail. + func unarchiveProject(_ name: String) { + // #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/), − 2 = root. + guard let boundHome = watchedHome else { return } + func openPieceInArchivedProject() -> String? { + guard let id = session?.postID, + let projectDir = PostStore.folder(of: id, home: boundHome)?.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 } + } + performWrite { home in + try PostStore.unarchiveProject(name, home: home) + if let openID { + session = EditorSession(postID: openID, home: home) + wireSession() + } + } + } +}