Files
museion/Museion/PostsModelOutline.swift
T
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

162 lines
6.3 KiB
Swift

//
// PostsModelOutline.swift
// Museion
//
// #146: the outline-domain extensions of PostsModel — the mixed-content
// guard (#111, S7) and Convert to Post (#114, S4) — moved from
// PostsModel.swift (file-length ceiling), code unchanged save the #114
// guard unwrap (#142 posture).
//
import Foundation
// MARK: Mixed-content outline guard (#111, S7)
extension PostsModel {
/// A `type: outline` piece that parses with dropped prose — the guard's
/// target. The old session already ended by the time this runs; its
/// flush was prose-mode, so it couldn't drop anything.
/// Type: the scan's word when the list knows it (archive pane opens,
/// app-start selection), the frontmatter's word during the rescan lag
/// (the same window lastDraftWasOutline covers) — ONE disk read derives
/// both. No watched home yet (pre-bind) = post: nothing to guard.
/// #146: internal — `select` (PostsModel.swift) asks the guard.
func isGuardedOutline(_ id: String) -> Bool {
guard let home = watchedHome,
let dir = PostStore.folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type {
known
} else {
PostFrontmatter.decoded(PostFrontmatter.parse(text)).type
}
return type == .outline && OutlineTree.parsesWithLoss(PostFrontmatter.split(text).body)
}
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
/// outliner never mounts, nothing drops); Outline = explicit consent,
/// opens the outliner (saves normalize/drop as today). Cancel = back
/// out (no session); the piece stays guarded on the next open.
func openGuardedOutlineInProse() {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
proseOverridePostID = id // routing: prose until the next open
openUnguarded(id)
}
func openGuardedOutlineAsOutline() {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
openUnguarded(id)
}
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
/// nothing stays selected over the empty editor).
func cancelOutlineGuard() {
outlineGuardPieceID = nil
if session == nil {
selectedPostID = nil
}
}
/// #111 (S7): the open with the guard passed (either answer or a clean
/// parse) — the plain select body. No re-check: the answer is the
/// explicit choice the ruling requires.
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String) {
guard let home = watchedHome, dismissExternal() else { return } // brief-25: the guest's edits land or the open aborts
// brief-28: identity — a session born under another Home is never
// "the same piece", whatever its id says; it departs here too.
if let session, !session.targets(postID: id, home: home) {
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
}
session = session?.targets(postID: id, home: home) == true ? session : EditorSession(postID: id, home: home)
draft = nil
pendingProject = nil
lastDraftWasOutline = false
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
refreshCards() // #23: the newly opened piece's cards, now
}
}
// MARK: Convert to Post (#114, S4)
/// The staged ask: which piece, and whether the headings ladder would
/// drop prose lines (mixed content — the sheet warns, verbatim keeps
/// everything).
struct PendingConversion {
let id: String
let lossy: Bool
}
extension PostsModel {
/// #114 (S4): row-menu entry — stage the ask. Outline pieces only.
/// The open session's text is the truth when the piece is open — disk
/// lags the debounce, and a stale-clean read would drop the warning
/// for prose typed since the last flush (#114 audit).
func stageConversion(_ post: Post) {
guard post.type == .outline else { return }
let body: String = if let session, openSessionTargets(post.id) { // brief-28: identity
session.text
} else if let home = watchedHome {
PostStore.readBody(id: post.id, home: home) ?? ""
} else {
""
}
pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body))
}
/// #114 (S4): the ask's Cancel (binding dismissal).
func cancelConversion() {
pendingConversion = nil
}
/// #114 audit: consent recheck — 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.
private func conversionWentLossyBehindAsk(_ pending: PendingConversion, headingsLadder: Bool) -> Bool {
guard headingsLadder, !pending.lossy, let home = watchedHome,
let body = PostStore.readBody(id: pending.id, home: home)
else { return false }
return OutlineTree.parsesWithLoss(body)
}
/// #114 (S4): the answer. Flush-first when the piece is open (the
/// transform reads disk), flip `type` + transform the body once, then
/// reopen the session routed to prose — proseOverridePostID covers the
/// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that
/// isn't open just converts; nothing else moves. One-way in v1.
/// #179: the write rides the rail.
func convertToPost(headingsLadder: Bool) {
guard let pending = pendingConversion else { return }
pendingConversion = nil
guard flushOrAbort(pending.id) else { return }
if conversionWentLossyBehindAsk(pending, headingsLadder: headingsLadder) {
lastError = "The outline changed since the sheet opened — nothing was converted."
return
}
performWrite { home in
try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home)
if let session, openSessionTargets(pending.id) { // brief-28: identity
session.teardown(flushFirst: false) // flushOrAbort already wrote
self.session = nil
proseOverridePostID = pending.id
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()
}
}
}
}