fix(editor): quit rides the departure gate

shutdown() flushed both sessions best-effort and ignored the
results — quitting with an unanswered #67 conflict wrote local
text over the foreign disk body (flush() holds for conflicts
only in the debounce), and a failed quit-time flush silently
dropped the only copy of the edits.

Quit now routes through the same departure gate as navigation:
documentsMayDepart runs both sessions through sessionMayDepart,
and the failed-flush-at-quit posture is BLOCK QUIT —
applicationShouldTerminate (quitReply(posts:), before the Cold
Turkey ask) refuses termination with one spoken reason via a
hosted-guarded alert. PostsModel.active (weak, registered by
AppGateState.init — the WritingLockState.active precedent) is
the delegate's reachability.

Finish-audit fixes folded in: sessionMayDepart refuses a
never-loaded session's retyped words (its flush is a vacuous
success — the same gap closed for navigation); shutdown stays
void (no production reader of a Bool).

+5 pins (conflict hold, clean flush, guest flush, never-loaded
refusal, delegate refusal incl. chmod-injected flush failure),
all flip-verified. Rail 708/708; format+lint clean.

Closes #200
This commit is contained in:
AlexKucera committed 2026-11-19 13:18:19 +01:00
1 parent 55be3d1a2f
commit 2334afc392
6 files changed
+198 -2

No files matched your search

+3
View File
@@ -67,6 +67,9 @@ final class AppGateState {
) {
// Explicit init: `Self` in a stored-property initializer trips
// @ObservationTracked's macro expansion (covariant Self).
// #200: the app delegate's quit gate reaches the one posts model
// (the WritingLockState.active precedent).
PostsModel.active = posts
if let stored = Self.fileHomeURL(in: defaults) {
museionHome = stored
return
+15 -2
View File
@@ -38,6 +38,13 @@ struct PostDraft {
@MainActor
@Observable
final class PostsModel {
/// #200: the app's one model, for WritingLockAppDelegate's quit-time
/// departure gate (the WritingLockState.active reachability
/// precedent). Weak; registered by AppGateState's init — bare
/// hosted-test rigs never register, so the delegate's pins inject
/// their model through `quitReply(posts:)`.
weak static var active: PostsModel?
/// The scanned, title-sorted list — mirrors `projects/` + `archive/` at
/// all times (#107).
/// #193: setter internal — PostsModelWatcher's rescan writes it.
@@ -164,9 +171,15 @@ final class PostsModel {
/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
/// flushes the open session first (sidecar rides along). #96: quit also
/// flushes the external buffer — same posture, same moment.
/// #200: quit is a document departure — the flush half routes through
/// the departure gate (`documentsMayDepart`): an unanswered #67
/// conflict never writes over the foreign body, a failed flush or a
/// never-loaded retype lands its reason in lastError instead of
/// silently dropping the edits. The verdict itself is quitReply's, at
/// applicationShouldTerminate — this belt runs only at willTerminate.
/// Watchers stop either way — the process is leaving.
func shutdown() {
session?.flush()
externalSession?.flush()
documentsMayDepart()
watcher.stop()
externalWatcher.stop()
}
+27
View File
@@ -148,6 +148,14 @@ extension PostsModel {
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.
@@ -173,6 +181,25 @@ extension PostsModel {
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.
+33
View File
@@ -332,9 +332,19 @@ enum WritingLockKiosk {
/// unlocked quits proceed, a held block gets ONE modal ask — walk away
/// (the block dies quietly with the process, nothing kept — #158 settle
/// 3) or keep writing.
/// #200: quit is also a document departure — the posts gate runs FIRST
/// (never walk away from a block the quit then refuses to complete): an
/// open document that can't depart (unanswered #67 conflict, failed
/// flush) refuses termination with one spoken reason.
@MainActor
final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {
// #200: the departure gate — before the lock ask, so a refusal
// never strands a walked-away block in a still-running app.
guard quitReply(posts: PostsModel.active) == .terminateNow else {
presentQuitRefusal()
return .terminateCancel
}
guard WritingLockState.active?.isLocked == true else { return .terminateNow }
let alert = NSAlert()
alert.messageText = "Walk away from the block?"
@@ -350,4 +360,27 @@ final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
}
return .terminateCancel
}
/// #200: the quit-time departure gate — the pure decision, no UI (the
/// pins' seam; the refusal alert below is hosted-guarded like the
/// kiosk). nil posts (no model alive) passes: nothing is open,
/// nothing to lose.
func quitReply(posts: PostsModel?) -> NSApplication.TerminateReply {
guard let posts else { return .terminateNow }
guard posts.documentsMayDepart() else { return .terminateCancel }
return .terminateNow
}
/// #200: the refusal speaks (#163's ruling — self-aware friction, not
/// silence): one alert naming the strip's reason. Hosted tests never
/// present (the startLaunchCheck guard convention).
private func presentQuitRefusal() {
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
let alert = NSAlert()
alert.messageText = "Quit stopped — a piece needs you first"
alert.informativeText = PostsModel.active?.lastError
?? "An open piece could not be saved. Tend to it, then quit again."
alert.addButton(withTitle: "Back to Museion")
alert.runModal()
}
}
@@ -12,6 +12,16 @@
// stage their temp file beside the destination), the permission-
// injection convention of FixCardApplyTests.
//
// #200 (gate quit-time flushes through the departure gate): quitting is
// the one departure that used to bypass the gate — shutdown() flushed
// both sessions best-effort. Pins: a quit-time shutdown with an
// unanswered #67 conflict leaves the foreign disk body untouched (the
// #114 harm); the open external guest's edits ride the shutdown flush;
// a never-loaded session with retyped words refuses (its flush would
// report a vacuous success and drop the only copy — finish-audit LOW).
// The block-quit posture itself (applicationShouldTerminate's refusal)
// is pinned in WritingLockTests at the delegate seam.
//
import Foundation
@testable import Museion
@@ -179,4 +189,76 @@ struct PostsModelDepartureTests {
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n")
}
@Test func `quit-time shutdown leaves the foreign disk body untouched while the conflict alert is unanswered`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlocal paragraph")
// #67, for real this time: the foreign body is ON disk (quit's
// flush() never held for a conflict — only the debounce did, so
// shutdown used to write the local text over it, #114's harm).
try PostStore.overwrite(id: post.id, body: "foreign body from disk", home: home)
model.session?.diskDidChange(diskText: "foreign body from disk")
model.shutdown()
// AC #200: the foreign disk body survives the quit-time flush and
// the strip says why instead of pretending it saved.
#expect(PostStore.readBody(id: post.id, home: home) == "foreign body from disk")
#expect(model.lastError != nil)
}
@Test func `quit-time shutdown flushes a clean dirty session`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlast words before quitting")
model.shutdown()
// No conflict, no failure: the edits land and quit proceeds clean.
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\nlast words before quitting")
#expect(model.lastError == nil)
}
@Test func `quit-time shutdown flushes the open external guest`() throws {
let (model, _) = try makeModelHome()
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
defer { try? allowWrites(to: extDir) }
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
model.externalSession?.edit("# Foreign\n\nguest words that must land before quitting")
model.shutdown()
// The guest leg of the quit gate: its edits ride the shutdown
// flush, exactly as the old best-effort shutdown did.
#expect(try String(contentsOf: extFile, encoding: .utf8) == "# Foreign\n\nguest words that must land before quitting")
#expect(model.lastError == nil)
}
@Test func `quit-time shutdown refuses over a never-loaded session with retyped text`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
// The file turns unreadable between scan and open: the session
// opens empty (loadFailed), the writer retypes into it.
let file = try #require(PostStore.folder(of: post.id, home: home))
.appendingPathComponent("post.md")
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: file.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path) }
model.select(post.id)
#expect(model.session?.loadFailed == true)
model.session?.edit("# Retyped words over a file that never loaded")
model.shutdown()
// flush() reports a vacuous success for a never-loaded session —
// the gate must refuse instead of letting the retype die quietly.
#expect(model.lastError != nil)
#expect(model.session?.text == "# Retyped words over a file that never loaded")
}
}
+38
View File
@@ -253,6 +253,44 @@ struct WritingLockTests {
#expect(delegate.applicationShouldTerminate(NSApplication.shared) == .terminateNow)
}
// MARK: - #200: the quit-time departure gate
@Test @MainActor
func `quit refuses while an open piece cannot depart and proceeds once it can`() throws {
// The failed-flush-at-quit posture, pinned: block quit (this
// delegate's own refusal precedent) — never silently drop the
// only copy of the edits. quitReply is the pure decision seam;
// the refusal ALERT itself is hosted-guarded like the kiosk.
let delegate = WritingLockAppDelegate()
// No model alive → nothing open, nothing to lose.
#expect(delegate.quitReply(posts: nil) == .terminateNow)
// A dirty-but-clean-writable session departs: quit proceeds and
// the flush lands.
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlast words before quitting")
#expect(delegate.quitReply(posts: model) == .terminateNow)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\nlast words before quitting")
// An unanswered #67 conflict refuses termination — the foreign
// disk body must survive the quit attempt.
try PostStore.overwrite(id: post.id, body: "foreign body from disk", home: home)
model.session?.diskDidChange(diskText: "foreign body from disk")
#expect(delegate.quitReply(posts: model) == .terminateCancel)
#expect(PostStore.readBody(id: post.id, home: home) == "foreign body from disk")
// A failed flush refuses termination too — the pinned posture.
model.session?.keepLocal() // #67 No: the writer keeps their words
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: pieceDir.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: pieceDir.path) }
#expect(delegate.quitReply(posts: model) == .terminateCancel)
#expect(model.lastError != nil)
}
/// Bounded poll for the watched scan to surface a piece (the
/// PostsModelTests poll pattern — the FSEvents latency window).
@MainActor