Files
museion/Museion/PostsModelWrites.swift
AlexKucera 8b0d43aed8
CI / ci (push) Canceled after 0s
fix(editor): Home repoint rides the departure gate; document identity is (Home, ID)
Settings committed the new Home and bind flipped watchedHome without
departing the open session: the session's immutable target kept the
OLD Home, a same-slug piece in the new library made the ID-only
reselect return it, and autosave/Save/quit wrote the old library
while structural operations resolved against the new one. #198's
departure gate never saw this seam; a no-collision piece was torn
down by the vanish path with its dirty buffer dropped.

The gate runs BEFORE anything commits. PostsModel.repoint(to:) is a
document departure through the same sessionMayDepart (all three legs:
unanswered #67, failed flush, never-loaded retype — no parallel
gate); on refusal nothing changes (preference, watchedHome, the
session's (A, id) target, its buffer), on acceptance the departed
piece's state dies with it. AppGateState.repointMuseionHome(to:)
commits the preference and its persistence only after the gate;
WorkspaceView's Settings binding routes through it and the root
.task(id:) binds the model after that commit — the dumb binder. A
refusal speaks the #198 reason the way #200's quit refusal does
(hosted-guarded alert: no Posts strip is in sight from Settings).
Nothing auto-reopens after an accepted repoint — the writer picks
from the new list; the in-memory draft survives (no Home until first
save; dropping it would drop the only copy).

Document identity is (Home, ID) everywhere — EditorSession.targets
is the pair, PostsModel.openSessionTargets the model-side question;
every ID-only session comparison is retired: select's reselect
no-op, openUnguarded, the structural rail (rename/trash/move/archive/
restore/unarchive + flushOrAbort), conversion, the pass guard (its
answer now carries the Home it validated), Micropub's launch, the
lock's arm/body reads. Async continuations re-validate identity at
COMPLETION: refreshCards (launch and hop-back — the old ID-only guard
let a scan from the previous library land its cards on the new
library's same-slug piece) and rescan (the stale-Home verdict is
hoisted: a scan that outlived a repoint applies nothing, not just
the vanish check; the #67 disk read runs only for a session targeting
the scan's own Home). scanPieceCards is the per-model injectable
scanner the deterministic stale-scan pin needs.

Tests: PostsModelRepointTests (7) move to the gated entry and go
green (17/17 with PostsModelDepartureTests — the #198 matrix stays
green and composes); the stale-scan pin's RED is a mutation check
(completion guard reverted to ID-only → only that pin fails, cards
→ ["Hedging"]; restored byte-exact). The #179 mid-pass repoint pin
drives the real Settings path now (repoint + bind). swiftformat 0/152,
swiftlint 0.
2026-11-23 20:23:57 +01:00

289 lines
11 KiB
Swift
Raw Permalink 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.
//
// 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 openSessionTargets(post.id) { // brief-28: identity
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, openSessionTargets(post.id) { // brief-28: identity
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 {
// brief-28: identity — only THIS library's open piece flushes here; a
// session born under another Home is not the caller's piece.
guard let session, openSessionTargets(postID) else { return true }
return sessionMayDepart(session)
}
/// brief-25 (failed-flush-discarded-on-document-switch): the departure
/// gate for ONE outgoing session — flushOrAbort's two gates lifted to
/// document departure. An unanswered #67 conflict means disk holds
/// foreign text with the session's version unwritten (#114 audit); a
/// failed flush means the edits never landed. Either way the document
/// may not leave: the caller aborts its navigation BEFORE clearing
/// document-specific state, so the dirty session stays retained and
/// honest while lastError says why (the structural rail's #108
/// posture — now the navigation sites' too).
/// #146: internal — PostsModelOutline's openUnguarded gates too.
func sessionMayDepart(_ outgoing: EditorSession) -> Bool {
if outgoing.conflictAlert {
lastError = "This piece changed on disk underneath you — answer the reload question first."
return false
}
// #200 finish-audit (LOW): a never-loaded session's flush reports
// a vacuous success — its retyped words would die with the
// departure (quit AND navigation). Block instead: never silently
// drop the only copy.
if outgoing.loadFailed, outgoing.saveState == .changed {
lastError = "This piece's file never loaded — the retyped text in the editor can't be saved. Copy it out first."
return false
}
if !outgoing.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
}
/// brief-25: the shared departure run for a full document switch —
/// the external guest and the post session both leave (newPost,
/// newOutline, openExternal). Each flushes through the departure gate
/// first; a failure retains BOTH exactly as they are and the
/// navigation aborts with nothing cleared.
@discardableResult
func departOpenDocuments() -> Bool {
guard dismissExternal() else { return false }
if let open = session {
guard sessionMayDepart(open) else { return false }
open.teardown(flushFirst: false) // the gate already flushed
session = nil
}
return true
}
/// #200 (gate quit-time flushes through the departure gate): the quit
/// run of the same gate — `shutdown`'s flush half, shared with
/// WritingLockAppDelegate's `applicationShouldTerminate` (willTerminate
/// can no longer refuse a quit). Both open documents route through
/// `sessionMayDepart`; false = the quit must not proceed, lastError
/// says why. The failed-flush-at-quit posture is BLOCK QUIT (the
/// WritingLock refusal precedent) — never silently drop the only copy
/// of the edits, never write over an unanswered #67 foreign body.
func documentsMayDepart() -> Bool {
var departed = true
if let guest = externalSession, !sessionMayDepart(guest) {
departed = false
}
if let open = session, !sessionMayDepart(open) {
departed = false
}
return departed
}
/// #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 openSessionTargets(post.id) { // brief-28: identity
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, openSessionTargets(post.id) { // brief-28: identity
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 openSessionTargets(post.id) { // brief-28: identity
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/<name>), − 2 = root.
guard let boundHome = watchedHome else { return }
func openPieceInArchivedProject() -> String? {
guard let id = session?.postID, openSessionTargets(id), // brief-28: identity
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()
}
}
}
}