feat(outline): mixed-content open guard — S7 (#111)
CI / ci (push) Canceled after 0s

Opening a type: outline piece whose body parses with dropped prose
(paragraph lines between bullets) now asks before the outliner mounts:
Open in Prose (default, nothing drops), Open as Outline (explicit
consent to save normalization), or Cancel. The detector shares the
parser's item definition, the ask presents over an empty editor so
nothing can normalize on save before the choice, and the prose answer
rides a routing override that dies with the next open.

Audit round pinned the lifecycle: reselect of the open piece is a
no-op (an armed debounce must never flush mid-ask), and a draft or
guest staged during the ask displaces it without being destroyed.

Closes #111

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-10-15 18:31:26 +02:00
1 parent c23ee0f62f
commit 0b172f73ef
12 files changed
+440 -17

No files matched your search

+2 -2
View File
@@ -22,13 +22,13 @@ Owned by the root AGENTS.md contract.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session.
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call.
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
- `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0.
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107).
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling).
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet.
- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting).
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (the monitor itself can't run in the test host — no running NSApp loop).
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
+16
View File
@@ -254,4 +254,20 @@ struct OutlineTreeTests {
#expect(rootResult == .newNode(path: [2], caret: 0))
#expect(rooted.map(\.text) == ["a", "", ""])
}
// #111 (S7): the mixed-content detector behind the open guard.
@Test func `parsesWithLoss flags prose between bullets and stays quiet otherwise`() {
// The exact hazard: prose after the first item would drop on save.
#expect(OutlineTree.parsesWithLoss("- one\nan stray paragraph\n- two"))
// Deep prose counts anywhere after the first item.
#expect(OutlineTree.parsesWithLoss("- a\n - b\n prose under b"))
// Clean canonical outline — no loss.
#expect(!OutlineTree.parsesWithLoss("- one\n- two\n - nested"))
// Preamble is verbatim by design — never a loss.
#expect(!OutlineTree.parsesWithLoss("# Title\n\n- one\n- two"))
// Blank lines between items are formatting, not prose.
#expect(!OutlineTree.parsesWithLoss("- one\n\n- two\n"))
#expect(!OutlineTree.parsesWithLoss(""))
}
}
+136
View File
@@ -159,3 +159,139 @@ private func makeModelHome() throws -> (PostsModel, URL) {
#expect(model.moveTargets(home: home) == ["essays", "posts"])
// "posts" exists too (bind created it); a dot-project never shows.
}
// #111 (S7): the mixed-content outline guard — no silent prose loss.
/// A `type: outline` piece whose body parses with dropped prose.
@discardableResult
private func writeMixedOutline(home: URL) throws -> Post {
try PostStore.writeNew(
body: "# Mixed\n\n- one\nA paragraph between bullets.\n- two\n",
type: .outline,
home: home,
)
}
@Test @MainActor func `mixed outline fires the guard and holds the open`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id) // the ask is up
#expect(model.session == nil) // nothing editable while it's up
#expect(model.selectedPostID == post.id)
// The file is untouched — the choice precedes any save.
#expect(try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
.contains("A paragraph between bullets."))
}
@Test @MainActor func `guard prose answer opens prose and never drops`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineInProse(home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
#expect(model.proseOverridePostID == post.id) // routes prose despite type
// A full edit+flush cycle in prose mode: nothing drops.
model.session?.edit("- one\nA paragraph between bullets.\n- two\nedited")
_ = model.session?.flush()
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
#expect(onDisk.contains("edited"))
#expect(onDisk.contains("A paragraph between bullets."))
}
@Test @MainActor func `guard outline answer is explicit consent`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
#expect(model.proseOverridePostID == nil) // outline routing stands
// The consented save drops the prose — as ruled, but only now.
model.session?.edit("- one\n- two")
_ = model.session?.flush()
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
#expect(!onDisk.contains("A paragraph between bullets."))
}
@Test @MainActor func `guard cancel backs out and stays guarded`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.cancelOutlineGuard()
#expect(model.outlineGuardPieceID == nil)
#expect(model.session == nil)
// Still guarded: the next open re-fires the ask, file untouched.
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id)
}
// Audit pins: the guard's lifecycle holes (reselect / displacement).
@Test @MainActor func `reselecting the open guarded piece is a no-op`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home) // consent; disk still mixed
let session = try #require(model.session)
session.edit("- one\n- two\nedited") // dirty; debounce armed
model.select(post.id, home: home) // muscle-memory re-click on the open row
#expect(model.outlineGuardPieceID == nil) // no re-ask over a prior answer
#expect(model.session === session) // the open session survives, dirty state intact
}
@Test @MainActor func `new draft during the ask displaces it and survives`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home) // ask up
model.newPost() // ⌘N fires while the sheet is up
#expect(model.outlineGuardPieceID == nil) // the ask died with the displacement
#expect(model.draft != nil)
model.updateDraft("# Keep me\n")
// Answering the (now-gone) ask is inert — the draft survives.
model.openGuardedOutlineInProse(home: home)
model.openGuardedOutlineAsOutline(home: home)
#expect(model.draft != nil)
#expect(model.selectedPostID == nil) // the draft still owns the editor
}
@Test @MainActor func `guard fires from the scan-known type too`() async throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
// Wait for the bind rescan so `posts` knows the piece (poll-loop convention).
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.posts.contains(where: { $0.id == post.id }))
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id) // the scan path guards too
}
@Test @MainActor func `clean outline and prose pieces open without the guard`() throws {
let (model, home) = try makeModelHome()
let clean = try PostStore.writeNew(body: "# Clean\n\n- one\n- two\n", type: .outline, home: home)
let prose = try PostStore.writeNew(body: "# Plain\n\nA paragraph.\n", home: home)
model.select(clean.id, home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == clean.id)
model.select(prose.id, home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == prose.id)
}