refactor(posts): route every library write through the write rail (#179)
CI / ci (push) Canceled after 0s

One internal seam (PostsModelRail.swift) now pairs every library
verb store write with exactly one library rescan and owns the error
strip: saveDraft, newPostFromSession, rename, trash, createProject,
moveToProject, archivePost, restorePost, unarchiveProject,
importFiles, convertToPost, and runPass pass-state advance (12 sites
on this base; the pass snapshot/stats writes, the publish stamp, and
the editor flush stay outside by design).

The model owns the Home: boundHome is set by bind() alone (app
construction + Settings repoint); every public verb lost its home:
parameter (create post/outline/session-born, rename, move, archive,
restore, trash, convert, project creation, import, select, cards,
passes, blind read, publish).

The three rail entries are railWrite/railWriteReturningReason/
railWriteKeepingStrip — deliberately NOT overloads: a shared base
name let unlabeled trailing-closure calls resolve into the labeled
non-generic entry (Swift binds trailing closures to labeled first
parameters), silently bypassing the strip and the pairing.

Views + 11 test files swept to the homeless signatures (160 sites).
RED suite green: 3/3. Full unit suite: 654/654. Fixes #179
This commit is contained in:
AlexKucera committed 2026-11-10 03:05:48 +01:00
1 parent 8c5ceffa3c
commit 06283b6287
23 files changed
+364 -363

No files matched your search

+3 -3
View File
@@ -149,7 +149,7 @@ private struct CardRow: View {
.controlSize(.small)
} else {
Button("Done") {
gate.posts.doneCard(card, home: gate.museionHome)
gate.posts.doneCard(card)
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -217,7 +217,7 @@ private struct SkipButton: View {
var body: some View {
Button("Skip") {
gate.posts.skipCard(card, home: gate.museionHome)
gate.posts.skipCard(card)
}
.buttonStyle(.borderless)
.controlSize(.small)
@@ -289,7 +289,7 @@ private struct ApplyAskSheet: View {
}
private func apply() {
switch posts.applyCard(card, home: home) {
switch posts.applyCard(card) {
case .applied:
dismiss()
case .stale:
+2 -2
View File
@@ -548,7 +548,7 @@ private struct PassBarView: View {
private func runPass() {
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
Task { await posts.runPass(kind, mentor: model) }
}
/// #122: the Blind Read — one purposeful click judges the current
@@ -561,7 +561,7 @@ private struct PassBarView: View {
disabled: blindReadBlocked != nil,
) {
guard let posts, let home else { return }
Task { await posts.blindRead(home: home, mentor: model) }
Task { await posts.blindRead(mentor: model) }
}
.help(
blindReadBlocked
+3 -2
View File
@@ -244,12 +244,13 @@ extension PostsModel {
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
/// #179: no Home parameter — the model owns its Home.
func micropubSendDraft(
home: URL,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let session,
guard let home = boundHome,
let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
+1 -1
View File
@@ -162,7 +162,7 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = .drafting
Task {
switch await posts.micropubSendDraft(home: home, token: token) {
switch await posts.micropubSendDraft(token: token) {
case let .drafted(url, preview):
draftURL = url
previewURL = preview
+95 -108
View File
@@ -4,8 +4,9 @@
//
// #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.
// selection, and the New Post draft lifecycle (#62). #179: every library
// verb's store write rides the write rail (PostsModelRail.swift) — one
// seam pairing the write with the rescan and the error strip.
// #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
@@ -176,8 +177,11 @@ final class PostsModel {
/// each. Nil in production (no observer, no cost).
@ObservationIgnored
var onRailEvent: (@MainActor (PostsModelRailEvent) -> Void)?
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
/// #179: the Home the model owns — set by `bind` ALONE (app
/// construction and the Settings repoint are the only two places it is
/// set); every verb reads it, none takes it. Watcher root + rescan
/// target.
private(set) var boundHome: URL?
private var watcher = PostsWatcher()
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
/// post.md files, not the library (see PostScanCache).
@@ -265,22 +269,22 @@ final class PostsModel {
/// 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
/// writer keeps typing where they were. #179: rides the write rail —
/// the paired rescan fires immediately (the watcher would too, after
/// its window).
func saveDraft() {
guard let staged = draft, let home = boundHome else { return }
let text = staged.text
let project = staged.project
let type = staged.type
railWrite {
let post = try PostStore.writeNew(body: text, project: project, type: type, home: home)
lastDraftWasOutline = type == .outline // #109: covers the lagging rescan
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
}
}
@@ -288,17 +292,14 @@ final class PostsModel {
/// draft stamped `origin: ai` (never stats-eligible) and open it in
/// Posts (select's open path; the WorkspaceView selection onChange
/// hops the pane). Nil + lastError on failure; Cancel never gets here.
/// #179: rides the write rail.
@discardableResult
func newPostFromSession(body: String, home: URL) -> Post? {
do {
func newPostFromSession(body: String) -> Post? {
guard let home = boundHome else { return nil }
return railWrite {
let post = try PostStore.writeNew(body: body, origin: .ai, home: home)
select(post.id, home: home)
lastError = nil
Task { await rescan() }
select(post.id)
return post
} catch {
lastError = error.localizedDescription
return nil
}
}
@@ -311,7 +312,8 @@ final class PostsModel {
/// 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) {
func select(_ id: String) {
guard let home = boundHome else { return }
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
@@ -323,7 +325,7 @@ final class PostsModel {
if let session {
session.teardown(flushFirst: true)
}
if isGuardedOutline(id, home: home) {
if isGuardedOutline(id) {
outlineGuardPieceID = id
proseOverridePostID = nil
session = nil
@@ -331,13 +333,13 @@ final class PostsModel {
pendingProject = nil
lastDraftWasOutline = false
selectedPostID = id
refreshCards(home: home) // #23: nil session — the held ask shows no cards
refreshCards() // #23: nil session — the held ask shows no cards
return
}
// The prior session was torn down above; openUnguarded's guards
// are dead code on this path (session is nil or a different id) —
// kept: one open body answers select and the ask alike.
openUnguarded(id, home: home)
openUnguarded(id)
proseOverridePostID = nil // #111: the override died with the open it covered
}
@@ -385,13 +387,14 @@ final class PostsModel {
/// 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) {
/// on failure. #179: the move rides the write rail.
func rename(_ post: Post, to title: String) {
guard let home = boundHome else { return }
// #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 {
railWrite {
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
@@ -400,18 +403,16 @@ final class PostsModel {
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 {
/// #179: rides the write rail.
func trash(_ post: Post) {
guard let home = boundHome else { return }
railWrite {
try PostStore.trash(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
@@ -420,10 +421,6 @@ final class PostsModel {
session = nil
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -436,15 +433,15 @@ final class PostsModel {
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 {
/// #108: raw create — the sheet composes on it. The failure reason
/// returns to the sheet (shown inline; never routed into lastError —
/// the strip behind the sheet must not double-message one error).
/// #179: rides the write rail's reason-returning entry — the pairing
/// is the rail's, the error routing stays the sheet's.
func createProject(named name: String) -> String? {
guard let home = boundHome else { return "No library Home yet — try again in a moment." }
return railWriteReturningReason {
try PostStore.createProject(named: name, home: home)
return nil // success
} catch {
return error.localizedDescription
}
}
@@ -462,9 +459,9 @@ final class PostsModel {
/// 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)) ?? []
func moveTargets() -> [String] {
let root = boundHome?.appendingPathComponent("projects", isDirectory: true)
let onDisk = root.flatMap { try? FileManager.default.contentsOfDirectory(atPath: $0.path) } ?? []
var names = Set(onDisk.filter { !$0.hasPrefix(".") })
names.insert(Post.defaultProject)
return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
@@ -498,27 +495,24 @@ final class PostsModel {
/// #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 {
/// #179: rides the write rail.
func moveToProject(_ post: Post, project: String) {
guard let home = boundHome, flushOrAbort(post.id) else { return }
railWrite {
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 {
/// the Archive pane, where they're listed). #179: rides the write rail.
func archivePost(_ post: Post) {
guard let home = boundHome, flushOrAbort(post.id) else { return }
railWrite {
try PostStore.archive(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
@@ -527,10 +521,6 @@ final class PostsModel {
open.teardown(flushFirst: false) // already flushed above
session = nil
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -538,20 +528,17 @@ final class PostsModel {
/// 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 {
/// #179: rides the write rail.
func restorePost(_ post: Post) {
guard let home = boundHome, flushOrAbort(post.id) else { return }
railWrite {
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)
select(post.id)
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -559,11 +546,13 @@ final class PostsModel {
/// 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.
/// #179: rides the write rail.
func unarchiveProject(_ name: String) {
guard let home = boundHome else { return }
// #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(),
@@ -577,16 +566,12 @@ final class PostsModel {
// #108 audit 2: the only #108 folder move that skipped the gate.
guard flushOrAbort(openID) else { return }
}
do {
railWrite {
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
}
}
@@ -649,28 +634,30 @@ final class PostsModel {
/// 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 }
/// post's project (newPost's target rule). #179: rides the write
/// rail's strip-keeping entry — ONE paired rescan for the whole batch.
func importFiles(origin: Post.Origin) {
guard let urls = pendingImportURLs, let home = boundHome 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)"
railWriteKeepingStrip {
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)
}
if failures == 0 {
lastError = nil
}
}
if let last {
select(last.id, home: home)
}
if failures == 0 {
lastError = nil
}
Task { await rescan() }
}
/// #146: internal — the split-out domain extensions wire sessions too.
@@ -685,8 +672,8 @@ final class PostsModel {
extension PostsModel {
private func startWatching(home: URL) {
guard watchedHome != home else { return }
watchedHome = home
guard boundHome != home else { return }
boundHome = home
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
for root in roots {
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
@@ -700,7 +687,7 @@ extension PostsModel {
/// no second debounce on top.
/// #146: internal — the split-out domain extensions trigger rescans.
func rescan() async {
guard let home = watchedHome else { return }
guard let home = boundHome 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
@@ -730,7 +717,7 @@ extension PostsModel {
// 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 {
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), boundHome == 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
@@ -744,6 +731,6 @@ extension PostsModel {
}
// #23: the open piece's stored fix cards ride the same rescan —
// the watcher fires on <piece>/cards/ writes too.
refreshCards(home: home)
refreshCards()
}
}
+16 -13
View File
@@ -20,8 +20,12 @@ extension PostsModel {
/// transitions — the piece-roots watcher already fires on cards/ writes.
/// #122: the same pass also derives `openPieceHasSnapshot` (the Blind
/// Read's base) — one detached read of the open piece's disk facts.
func refreshCards(home: URL) {
guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else {
/// #179: no Home parameter — the model's bound Home is the one target.
func refreshCards() {
guard let id = session?.postID,
let home = boundHome,
let folder = PostStore.folder(of: id, home: home)
else {
openPieceCards = []
openPieceHasSnapshot = false
return
@@ -68,7 +72,7 @@ extension PostsModel {
/// 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 {
func applyCard(_ card: FixCardStore.StoredFixCard) -> 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 {
@@ -86,30 +90,29 @@ extension PostsModel {
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
refreshCards()
return .stale
}
guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") }
closeCard(card, status: .applied, home: home)
closeCard(card, status: .applied)
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)
func skipCard(_ card: FixCardStore.StoredFixCard) {
closeCard(card, status: .skipped)
}
/// #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)
func doneCard(_ card: FixCardStore.StoredFixCard) {
closeCard(card, status: .done)
}
private func closeCard(
_ card: FixCardStore.StoredFixCard,
status: FixCardStore.StoredFixCard.Status,
home: URL,
) {
guard let session else {
lastError = "open the piece to work its cards"
@@ -120,7 +123,7 @@ extension PostsModel {
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
refreshCards()
}
}
@@ -140,7 +143,7 @@ extension PostsModel {
/// 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 {
func promoteCard(_ card: FixCardStore.StoredFixCard) -> 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 {
@@ -149,7 +152,7 @@ extension PostsModel {
lastError = "learning write failed: \(error.localizedDescription)"
return .refused("learning write failed: \(error.localizedDescription)")
}
refreshCards(home: home)
refreshCards()
return .promoted
}
}
+26 -27
View File
@@ -19,10 +19,11 @@ extension PostsModel {
/// 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.
/// both. No bound Home yet (pre-bind) = post: nothing to guard.
/// #146: internal — `select` (PostsModel.swift) asks the guard.
func isGuardedOutline(_ id: String, home: URL) -> Bool {
guard let dir = PostStore.folder(of: id, home: home),
func isGuardedOutline(_ id: String) -> Bool {
guard let home = boundHome,
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 {
@@ -37,17 +38,17 @@ extension PostsModel {
/// 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) {
func openGuardedOutlineInProse() {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
proseOverridePostID = id // routing: prose until the next open
openUnguarded(id, home: home)
openUnguarded(id)
}
func openGuardedOutlineAsOutline(home: URL) {
func openGuardedOutlineAsOutline() {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
openUnguarded(id, home: home)
openUnguarded(id)
}
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
@@ -64,7 +65,8 @@ extension PostsModel {
/// explicit choice the ruling requires.
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String, home: URL) {
func openUnguarded(_ id: String) {
guard let home = boundHome else { return }
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
@@ -76,7 +78,7 @@ extension PostsModel {
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
refreshCards(home: home) // #23: the newly opened piece's cards, now
refreshCards() // #23: the newly opened piece's cards, now
}
}
@@ -95,8 +97,8 @@ extension PostsModel {
/// 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 }
func stageConversion(_ post: Post) {
guard post.type == .outline, let home = boundHome else { return }
let body: String = if let session, session.postID == post.id {
session.text
} else {
@@ -115,35 +117,32 @@ extension PostsModel {
/// 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) {
/// #179: the convert rides the write rail.
func convertToPost(headingsLadder: Bool) {
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
}
guard let home = boundHome, flushOrAbort(pending.id) else { return }
// 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
}
railWrite {
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)
openUnguarded(pending.id)
}
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
}
}
}
+10 -9
View File
@@ -19,7 +19,7 @@ extension PostsModel {
/// 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 {
func runPass(_ kind: PassKind, mentor: MentorSessionModel) async {
guard runningPass == nil, !runningBlindRead else {
lastError = "A pass is already running."
return
@@ -42,7 +42,8 @@ extension PostsModel {
// 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,
guard let home = boundHome,
let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
@@ -82,12 +83,11 @@ extension PostsModel {
guard case let .ended(stopReason) = outcome, stopReason != "refusal" else {
return // cancelled / refused / failed — the transcript tells the story
}
do {
// #179: the library-visible write of a completed pass — Pass State
// advance — rides the write rail; the snapshot/stats/lint writes
// above never do (they don't regroup the library).
railWrite {
_ = try PostStore.advancePassState(id: id, kind: kind, home: home)
lastError = nil
Task { await rescan() } // the library regroups by Pass State
} catch {
lastError = error.localizedDescription
}
}
@@ -109,7 +109,7 @@ extension PostsModel {
/// advance, no cards, no Learnings — the verdict and the reveal live in
/// the transient transcript and die with it. The writer stays judge of
/// record.
func blindRead(home: URL, mentor: MentorSessionModel) async {
func blindRead(mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
@@ -127,7 +127,8 @@ extension PostsModel {
return
}
// Same open-piece rule as a pass: the read judges ONE saved piece.
guard let session,
guard let home = boundHome,
let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
+17 -7
View File
@@ -16,28 +16,38 @@ import Foundation
/// #179: rail observability — what the write-rail suite reads off the
/// seam. `.write` = a verb's body rode the rail; `.pairedRescan` = the
/// rail scheduled the verb's ONE rescan.
/// rail scheduled the verb's ONE rescan; `.writeFailed` = the verb's
/// write threw (the strip owns the reason; nothing paired).
enum PostsModelRailEvent: Equatable {
case write
case pairedRescan
case writeFailed
}
// MARK: Write rail (#179)
/// #179: ONE rail, three error routings — deliberately NOT overloads: a
/// shared base name let unlabeled trailing-closure calls resolve into the
/// wrong entry (Swift binds a trailing closure to a labeled first
/// parameter, and the non-generic overload wins) — a verb meant for the
/// strip silently took the reason-returning path and never touched
/// `lastError`. Distinct names make the routing choice unambiguous at
/// every call site.
extension PostsModel {
/// #179: the rail's default entry — strip-routed. The op runs the
/// verb's store write FIRST, then its state updates (a throw leaves
/// nothing half-updated); success clears the strip and pairs exactly
/// one rescan, a throw routes the failure into the strip.
@discardableResult
func performLibraryWrite<T>(_ op: () throws -> T) -> T? {
func railWrite<T>(_ operation: () throws -> T) -> T? {
onRailEvent?(.write)
do {
let result = try op()
let result = try operation()
lastError = nil
pairRailRescan()
return result
} catch {
onRailEvent?(.writeFailed)
lastError = error.localizedDescription
return nil
}
@@ -46,10 +56,10 @@ extension PostsModel {
/// #179: the reason-returning entry (project creation) — the sheet
/// owns its inline reason and the strip behind the sheet must not
/// double-message one error. Same ONE rescan on success.
func performLibraryWrite(returningReason op: () throws -> Void) -> String? {
func railWriteReturningReason(_ operation: () throws -> Void) -> String? {
onRailEvent?(.write)
do {
try op()
try operation()
pairRailRescan()
return nil
} catch {
@@ -60,9 +70,9 @@ extension PostsModel {
/// #179: the strip-keeping entry (the import batch) — per-file
/// failures continue inside the op and the strip keeps the verb's own
/// message; the rail only pairs the ONE rescan.
func performLibraryWrite(keepingStrip op: () -> Void) {
func railWriteKeepingStrip(_ operation: () -> Void) {
onRailEvent?(.write)
op()
operation()
pairRailRescan()
}
+8 -8
View File
@@ -112,7 +112,7 @@ struct PostsPaneView: View {
draftText: draft.text,
draftEdited: { model.updateDraft($0) },
draftSave: {
model.saveDraft(home: home)
model.saveDraft()
},
outline: draft.type == .outline,
)
@@ -317,7 +317,7 @@ struct PostsLibraryColumn: View {
.background(LaunchFocusReset())
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
model.rename(post, to: title)
}
}
.sheet(item: $movingPost) { post in
@@ -325,8 +325,8 @@ struct PostsLibraryColumn: View {
// the library renders (Unicode-scalar sort split them), and it
// includes empty projects (a fresh New Project has no pieces yet —
// it must already be a move target).
MoveToProjectSheet(post: post, projects: model.moveTargets(home: home)) { project in
model.moveToProject(post, project: project, home: home)
MoveToProjectSheet(post: post, projects: model.moveTargets()) { project in
model.moveToProject(post, project: project)
}
}
// #144: keystroke-debounced (250 ms), structured body scan —
@@ -355,7 +355,7 @@ struct PostsLibraryColumn: View {
/// render the same row (#144: results carry the full menu too).
private func postRow(_ post: Post) -> some View {
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
model.select(post.id)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
@@ -363,15 +363,15 @@ struct PostsLibraryColumn: View {
// body transform, then the piece becomes a prose post.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
model.stageConversion(post)
}
}
Button("Move to Project…") { movingPost = post }
Button("Move to Archive") {
model.archivePost(post, home: home)
model.archivePost(post)
}
Button("Move to Trash", role: .destructive) {
model.trash(post, home: home)
model.trash(post)
}
}
}
+1 -1
View File
@@ -108,7 +108,7 @@ struct PromoteAskSheet: View {
}
private func promote() {
switch posts.promoteCard(card, home: home) {
switch posts.promoteCard(card) {
case .promoted:
dismiss()
case let .refused(reason):
+1 -1
View File
@@ -341,7 +341,7 @@ struct SessionsPaneView: View {
/// (ApplyAskSheet posture — the edited draft is never destroyed).
private func newPostFromSession() -> String? {
guard let posts, let home else { return "No library to write into." }
if posts.newPostFromSession(body: sessionDraft ?? "", home: home) == nil {
if posts.newPostFromSession(body: sessionDraft ?? "") == nil {
return posts.lastError ?? "The piece couldn't be written."
}
sessionDraft = nil
+10 -10
View File
@@ -117,14 +117,14 @@ struct WorkspaceView: View {
// answer (Esc/Cancel) drops the batch.
.sheet(isPresented: originAskBinding) {
OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in
gate.posts.importFiles(origin: origin, home: gate.museionHome)
gate.posts.importFiles(origin: origin)
}
}
// #108: File ▸ New Project… ask — commands can't present sheets, so
// the model stages and this window presents (OriginAsk pattern).
.sheet(isPresented: newProjectAskBinding) {
NewProjectSheet { name in
if let reason = gate.posts.createProject(named: name, home: gate.museionHome) {
if let reason = gate.posts.createProject(named: name) {
return reason
}
gate.posts.newProjectPending(named: name)
@@ -137,9 +137,9 @@ struct WorkspaceView: View {
// drop; Esc/Cancel backs out with nothing opened.
.sheet(isPresented: outlineGuardBinding) {
OutlineGuardSheet {
gate.posts.openGuardedOutlineInProse(home: gate.museionHome)
gate.posts.openGuardedOutlineInProse()
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
gate.posts.openGuardedOutlineAsOutline()
}
}
// #114 (S4): the Convert to Post ask — which body the outline
@@ -147,7 +147,7 @@ struct WorkspaceView: View {
// is the default: lossless. Esc/Cancel converts nothing.
.sheet(isPresented: convertAskBinding) {
ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in
gate.posts.convertToPost(headingsLadder: headingsLadder, home: gate.museionHome)
gate.posts.convertToPost(headingsLadder: headingsLadder)
}
}
}
@@ -437,7 +437,7 @@ private struct ArchivePaneView: View {
// 'Unarchive Group' — it moves the whole
// project, not one piece.
Button("Unarchive Group") {
model.unarchiveProject(project, home: home)
model.unarchiveProject(project)
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
.help("Move the whole project back to projects/")
@@ -453,7 +453,7 @@ private struct ArchivePaneView: View {
// at x28 (the one indent). The hairline is
// BOUNDED to the fixed frame: x14 → 706.
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
model.select(post.id)
onOpenPiece()
}
.overlay(alignment: .bottom) {
@@ -464,14 +464,14 @@ private struct ArchivePaneView: View {
}
.contextMenu {
Button("Move Back to \(post.project)") {
model.restorePost(post, home: home)
model.restorePost(post)
}
Button("Rename…") { renamingPost = post }
// #114 (S4): works archived too — the piece
// stays where it is, only type + body flip.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
model.stageConversion(post)
}
}
}
@@ -496,7 +496,7 @@ private struct ArchivePaneView: View {
.background(DesignTokens.background)
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
model.rename(post, to: title)
}
}
}