Merge pull request 'fix(editor): guard document departure on failed flushes [museion/failed-flush-discarded-on-document-switch]' (#198) from fix/failed-flush-discarded-on-document-switch into main
CI / ci (push) Canceled after 0s

This commit was merged in pull request #198.
This commit is contained in:
AlexKucera committed 2026-11-19 09:45:30 +01:00
commit b2d01c852a
7 files changed
+304 -23

No files matched your search

+7 -8
View File
@@ -176,9 +176,7 @@ final class PostsModel {
/// target the default — new pieces are never born archived).
func newPost() {
let target = targetProject
dismissExternal() // #92: opening a draft dismisses the guest
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(project: target)
lastDraftWasOutline = false // #109: the afterglow died with the draft
proseOverridePostID = nil // #111: same death, same clearing
@@ -192,9 +190,7 @@ final class PostsModel {
/// Title keeps prose semantics (raw first line).
func newOutline() {
let target = targetProject
dismissExternal()
session?.teardown(flushFirst: true)
session = nil
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(text: "- ", project: target, type: .outline)
lastDraftWasOutline = false // #109: a new draft resets the afterglow
proseOverridePostID = nil // #111: same death, same clearing
@@ -246,7 +242,7 @@ final class PostsModel {
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String) {
guard watchedHome != nil else { return } // #179: no library, no open
dismissExternal()
guard dismissExternal() else { return } // brief-25: the guest's edits land or the switch aborts
// 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
// the ask again would nil its session without teardown (the armed
@@ -255,7 +251,10 @@ final class PostsModel {
return
}
if let session {
session.teardown(flushFirst: true)
// 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
}
if isGuardedOutline(id) {
outlineGuardPieceID = id
+15 -6
View File
@@ -13,12 +13,23 @@ 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).
/// selection change). brief-25: the dismissal is GUARDED — a guest
/// whose flush fails (or whose #67 conflict is unanswered) STAYS,
/// buffer and watcher live: teardown would drop the only retained
/// copy of the unsaved edits. Callers abort their navigation on
/// false, before clearing anything.
/// #146: internal — the split-out domain extensions dismiss too.
func dismissExternal() {
externalSession?.teardown(flushFirst: true)
@discardableResult
func dismissExternal() -> Bool {
guard let guest = externalSession else {
externalWatcher.stop()
return true
}
guard sessionMayDepart(guest) else { return false }
guest.teardown(flushFirst: false) // the gate already flushed
externalSession = nil
externalWatcher.stop()
return true
}
// MARK: External buffer (#91–#93) + Import (#94/#95)
@@ -33,9 +44,7 @@ extension PostsModel {
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
guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts
draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing
+5 -3
View File
@@ -66,10 +66,12 @@ extension PostsModel {
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String) {
guard let home = watchedHome else { return }
dismissExternal()
guard let home = watchedHome, dismissExternal() else { return } // brief-25: the guest's edits land or the open aborts
if let session, session.postID != id {
session.teardown(flushFirst: true)
// 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 = id == session?.postID ? session : EditorSession(postID: id, home: home)
draft = nil
+32 -6
View File
@@ -130,15 +130,25 @@ extension PostsModel {
/// 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 {
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
}
if !session.flush() {
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."
@@ -147,6 +157,22 @@ extension PostsModel {
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
}
/// #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.
+182
View File
@@ -0,0 +1,182 @@
//
// PostsModelDepartureTests.swift
// MuseionTests
//
// brief-25 (failed-flush-discarded-on-document-switch): document
// departure is guarded. A navigation whose outgoing flush fails (write
// error, or an unanswered #67 conflict) aborts and retains the dirty
// session — teardown used to discard the flush result and drop the only
// retained copy of unsaved prose. Both navigation families (saved-post
// session, external guest) pinned with injected write failures: a
// read-only piece folder / read-only guest directory (atomic writes
// stage their temp file beside the destination), the permission-
// injection convention of FixCardApplyTests.
//
import Foundation
@testable import Museion
import Testing
@Suite("PostsModelDepartureTests")
@MainActor
struct PostsModelDepartureTests {
private func denyWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path)
}
private func allowWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
}
@Test func `new post aborts when the dirty session flush fails and keeps its text`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Keeper\n", home: home)
model.select(post.id)
model.session?.edit("# Keeper\n\nunique failed-flush paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
model.newPost()
// The switch aborted: the dirty session is retained, not replaced
// by the draft — its text is the only copy of the edits.
#expect(model.session?.postID == post.id)
#expect(model.session?.text == "# Keeper\n\nunique failed-flush paragraph")
#expect(model.session?.saveState == .failed)
#expect(model.draft == nil)
#expect(model.selectedPostID == post.id)
#expect(model.lastError != nil)
// Writability restored → the retry lands the edits, then switches.
try allowWrites(to: pieceDir)
model.newPost()
#expect(model.draft != nil)
#expect(model.session == nil)
#expect(model.lastError == nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nunique failed-flush paragraph")
}
@Test func `new outline aborts when the dirty session flush fails`() 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\noutgoing paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
model.newOutline()
#expect(model.session?.postID == post.id)
#expect(model.draft == nil)
#expect(model.lastError != nil)
try allowWrites(to: pieceDir)
model.newOutline()
#expect(model.draft?.type == .outline)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `switching pieces aborts when the outgoing session flush fails`() throws {
let (model, home) = try makeModelHome()
let postA = try PostStore.writeNew(body: "# A\n", home: home)
let postB = try PostStore.writeNew(body: "# B\n", home: home)
model.select(postA.id)
model.session?.edit("# A\n\noutgoing paragraph")
let dirA = try #require(PostStore.folder(of: postA.id, home: home))
try denyWrites(to: dirA)
defer { try? allowWrites(to: dirA) }
model.select(postB.id)
// The switch aborted before replacing the session (select's own
// teardown AND the second one through openUnguarded both gated).
#expect(model.session?.postID == postA.id)
#expect(model.session?.text == "# A\n\noutgoing paragraph")
#expect(model.selectedPostID == postA.id)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n")
try allowWrites(to: dirA)
model.select(postB.id)
#expect(model.session?.postID == postB.id)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `open external aborts when the dirty session flush fails`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Host\n", home: home)
model.select(post.id)
model.session?.edit("# Host\n\noutgoing paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
// The guest did not take the column: the switch aborted with the
// dirty session retained.
#expect(model.session?.postID == post.id)
#expect(model.externalSession == nil)
#expect(model.lastError != nil)
try allowWrites(to: pieceDir)
model.openExternal(extFile)
#expect(model.externalSession != nil)
#expect(model.session == nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# Host\n\noutgoing paragraph")
}
@Test func `select aborts when the dirty guest flush fails and keeps the guest`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Host\n", home: home)
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 paragraph that must survive")
try denyWrites(to: extDir)
model.select(post.id)
// The guest stays: its buffer is the only copy of the edits.
#expect(model.externalSession != nil)
#expect(model.externalSession?.text == "# Foreign\n\nguest paragraph that must survive")
#expect(model.session == nil) // the switch aborted before opening the post
#expect(model.selectedPostID == nil)
#expect(model.lastError != nil)
try allowWrites(to: extDir)
model.select(post.id)
#expect(model.externalSession == nil)
#expect(model.session?.postID == post.id)
#expect(try String(contentsOf: extFile, encoding: .utf8) == "# Foreign\n\nguest paragraph that must survive")
}
@Test func `new post aborts 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: a foreign disk body arrived — the alert is up, unanswered.
model.session?.diskDidChange(diskText: "foreign body from disk")
model.newPost()
// Departure mirrors flushOrAbort: the unanswered conflict holds the
// navigation (and never overwrites the foreign disk body).
#expect(model.session?.postID == post.id)
#expect(model.draft == nil)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n")
}
}
@@ -0,0 +1,62 @@
# Document departure guard — a failed flush aborts navigation
> **Date:** 2026-11-16
> **Type:** fix
> **Reference:** brief-25 `failed-flush-discarded-on-document-switch` (unticketed; argus cycle-4 dedicated bugs pass, finding 1 — evidence `~/argus-audits/audit/2026-11-16/museion-bugs.md`). Base `11b196d68a23d10fdbe474848b9472c523ae0279` (main tip re-verified via `tea api repos/AlexKucera/museion/branches/main` at claim, 20:03 CET — no drift).
## Goal
`EditorSession.flush()` returns false after a write failure (saveState `.failed`), but `teardown(flushFirst:)` discarded the result — so every document departure (New Post, New Outline, piece switch, open external, guest dismissal) tore down the outgoing session even when its flush FAILED, then navigation replaced the only retained copy of the unsaved prose. Structural ops (move/archive/rename/convert) already aborted through `flushOrAbort`; ordinary departure did not. Make departure report failure and abort navigation while retaining the dirty session — one shared guard at every site, placed before any document-specific state clears.
## Site re-derivation (mandate — from root cause, not the seed list)
All production `teardown(` call sites re-enumerated at the pinned base:
| Site | Location | Verdict |
|------|----------|---------|
| `newPost` | PostsModel.swift:271 | exposed — guarded |
| `newOutline` | PostsModel.swift:287 | exposed — guarded |
| `dismissExternal` | PostsModel.swift:302 | exposed — guarded (guest half) |
| `select` | PostsModel.swift:359 | exposed — guarded (session half) |
| `openExternal` | PostsModel.swift:620 | exposed — guarded |
| `openUnguarded` | PostsModelOutline.swift:72 | exposed — guarded |
| trash:451, archivePost:550, convert:145, rescan:762 | — | `flushFirst: false` behind `flushOrAbort` or a vanished post — correctly unguarded |
Six sites, matching the seed list exactly; no seventh. `select`'s potential second teardown through `openUnguarded` is covered by gating both members of the pair. No seeded site disproved.
## What Was Done
- **`sessionMayDepart(_:)`** (PostsModel.swift): the departure gate for ONE outgoing session — `flushOrAbort`'s two gates (unanswered #67 conflict holds; failed flush holds) lifted to document departure, message strings byte-identical. `flushOrAbort` now routes through it (pure refactor, same contract).
- **`dismissExternal() -> Bool`**: the guest departs only when its flush lands; on failure the guest, its buffer, AND its watcher stay live; returns false so callers abort.
- **`departOpenDocuments()`**: the full-switch composition (guest + post session, each gated then torn down `flushFirst: false` — the gate already flushed) behind `newPost` / `newOutline` / `openExternal`.
- **`select` / `openUnguarded`**: gate the guest unconditionally at head (reselect-as-return still dismisses it, now guarded) and gate their same-id-conditional session teardowns through `sessionMayDepart` directly.
- **Disclosed semantic addition:** departure now also aborts on an *unanswered #67 conflict* (mirroring `flushOrAbort`). Previously, departing while the alert was up silently overwrote the foreign disk body via the teardown flush — the alert promises the writer chooses. Pinned by `new post aborts while the conflict alert is unanswered` (asserts disk NOT overwritten).
- **Tests** (`PostsModelDepartureTests.swift`, 6 pins): both navigation families with injected write failures (read-only piece folder / guest directory — atomic writes stage their temp beside the destination; FixCardApplyTests' permission-injection convention), the conflict hold, and retry-after-writability-restored proving the edits land and the switch then completes.
## Gates
- **RED at base:** `-only-testing:MuseionTests/PostsModelDepartureTests` at `11b196d` + tests-only commit — 6/6 failed, per-case lines printed, `** TEST FAILED **` (xcresult `Test-Museion-2026.11.16_20-13-27-+0100.xcresult`, dd `$TMPDIR/b25-dd`).
- **GREEN focused:** same filter at the fix tree — 6/6 passed, `** TEST SUCCEEDED **`.
- **Full suite ×2** (repo runner `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test`, same dd, post-commit tree `250a662`): xcresult summaries **699 passed / 1 failed / 0 skipped** both runs — the 1 is `MuseionUITests-Runner` failing at INIT ("Timed out while enabling automation mode"), a System Failure node with zero test assertions executed; xcresults `Test-Museion-2026.11.16_20-18-05-+0100.xcresult` and `Test-Museion-2026.11.16_20-20-18-+0100.xcresult`. 699 = 693 trunk executions + 6 new pins.
- **Environmental wall, disclosed:** a third full run (fresh dd) failed the UI runner identically, then the hosted unit runner wedged at session init (log frozen, killed per the wedge protocol; `b25-full-test3.log`, `b25-unit-clean.log` kept). `killall -9 testmanagerd` between runs 1 and 2 did not clear it — the machine's automation mode is wedged machine-wide (reboot-class, the #134 lesson). All hosted/UI test INIT was blocked after ~20:20; every green number above predates the wedge. The UI smoke (single XCUITest, no seam touched by this model-layer diff) is UNVERIFIED on this machine tonight — re-run post-reboot.
- **swiftformat:** 1/3 touched files rewrapped. **swiftlint:** net zero — `file_length` 775→809 and `type_body_length` 327→342 both pre-existing at base; no new rule fires; two `identifier_name` errors in the first test draft (`a`/`b`) fixed before commit.
- **gitnexus:** impact (owner index `f49e4b6`, 20 commits stale — disclosed): `dismissExternal`/`openUnguarded`/`flushOrAbort` CRITICAL, `newPost` HIGH (transitive closure through the `@Observable` model into the view tree — the direct callers are the enumerated sites above). `detect-changes` on a fresh worktree index: 3 files / 23 symbols / 15 flows / risk high — exactly the intended symbols, nothing unexpected. The analyze step's root-AGENTS.md gitnexus marker rewrite was reverted (brief-15 lesson).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| One gate engine (`sessionMayDepart`) shared by `flushOrAbort` and departure | One contract at the flush-or-abort seam; the coupled `home-repoint` brief (held behind this merge) rebases onto exactly this "flush-or-abort before committing" shape. |
| Guard placed before ANY document-specific state clears | The failure path must leave selection, draft, session, and watcher byte-identical — the retry is then a clean re-entry. |
| `departOpenDocuments` for the three full switches; primitives under same-id rules in `select`/`openUnguarded` | Reselect-as-return still dismisses the guest (existing #92 contract) but must not gate a session that is not departing. |
| Conflict-alert abort included (not just write failure) | Mirrors `flushOrAbort`; without it, departure resolves an unanswered #67 by silently overwriting the foreign body — the exact class of loss the guard exists to prevent. |
| Teardown flags flipped to `flushFirst: false` behind the gate | `flushOrAbort` precedent comment ("already flushed"); avoids a redundant second flush attempt. |
| Guest watcher stays live on a held guest | The retained guest must keep its #67 disk-change check — it is still the open document. |
## Docs
`Museion/AGENTS.md` PostsModel bullet carries two clause edits (guest held by the departure gate; document departure rides `sessionMayDepart`). AGENTS.md writes are consent-gated in this environment — shipped as an owner-apply patch beside the handoff: `~/daedalus-builds/museion/brief-25-agents-md-owner-apply.patch` (`git apply` verified CLEAN against the branch). PR body to carry: `git apply brief-25-agents-md-owner-apply.patch`.
## Coupling
`museion/home-repoint-retains-old-editor-target` is HELD behind this PR's merge and rebases onto this branch — `sessionMayDepart` / `departOpenDocuments` are its departure seam.
+1
View File
@@ -9,6 +9,7 @@ Complete history of session logs in this directory, newest first. One-line summa
| 2026-11-17 | issue | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | Root gate-running learnings collapse into the full-test.sh pointer; 8 deletions mapped to script/hook behavior; authoring rules retained; 693/693 |
| 2026-11-17 | issue | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | Lint-green doc truth (#197) + finish-audit; watcher-race test quiesced, symlink pin flip-verified, stale-xcodebuild hazard found; 693/693 |
| 2026-11-17 | feat | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) | Classis full-test.sh ported as the verify rail + pre-push hook; 4-round finish-audit; suite 692/692 via the rail, hook rig 23/23 |
| 2026-11-16 | fix | [20261116-failed-flush-discarded-on-document-switch_log.md](20261116-failed-flush-discarded-on-document-switch_log.md) | Unticketed fix (brief-25, argus cycle-4): document departure aborts on a failed flush — one sessionMayDepart gate (flushOrAbort's conflict+flush gates) behind dismissExternal/departOpenDocuments and select/openUnguarded; both navigation families pinned RED-first (6 pins); unit suite 699 green ×2 |
| 2026-11-13 | opt | [20261113-fold-typing-budget-pin_log.md](20261113-fold-typing-budget-pin_log.md) | Unticketed pin (brief-24): typing-cost guard for the #142 re-key — per-call line-scan observer through the real keystroke pipeline; zero scans beside a fold at N/2N, exact-count control 206/406, mutation-checked |
| 2026-11-13 | opt | [20261113-cold-turkey-full-tokenization_log.md](20261113-cold-turkey-full-tokenization_log.md) | Unticketed opt (argus digest): minutes feeds skip word counting entirely; DraftStats.words count-only — no token array per keystroke; +3 pins (RED-first rail-trip seam, corpus equivalence), suite 684 |
| 2026-11-11 | fix | [20261111-fix-library-search-stale-after-mutation_log.md](20261111-fix-library-search-stale-after-mutation_log.md) | Search snapshots re-key on Home + a rescan-rail content revision (list change OR re-read post.md — body-only edits included); stale rows drop to the recompute spinner (#144/#157 mounted gap) |