feat(outline): convert to post — S4 (#114)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
In-place outline→post conversion on the piece: id, folder, Pass State, origin kept, type frontmatter flips to post, body transforms once. The ask picks the transform — Verbatim Bullets (default, lossless) or Headings ladder (roots ##, stepping to the ###### floor, deeper stays bullets), with a warning when the ladder would drop paragraph lines between bullets. The open session flushes first, then reopens routed to prose via proseOverridePostID (lastDraftWasOutline's machinery reversed). An outline that went lossy on disk behind an unwarned ask aborts the convert; an unanswered #67 conflict aborts every flush-first op (shared flushOrAbort seam); rescan no longer hands a same-id reopened session its predecessor's stale disk text; a held #111 guard ask dies with the outline it pointed at. Audit round (finish-audit, three reviewers) included: 13 new pins, 206 tests green, pin discrimination verified. Record: docs/devlog/20261016-issue114-convert-to-post_log.md
This commit is contained in:
1 parent
21e2f27450
commit
c0513aae85
14 files changed
+547
-19
No files matched your search
@@ -21,14 +21,14 @@ Owned by the root AGENTS.md contract.
|
||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch.
|
||||
- `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. **#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.
|
||||
- `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). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#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. **#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. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel.
|
||||
- `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). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused).
|
||||
- `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. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused). **#114:** `headingsLadderBody` pin — ladder shape to the `######` floor, bullet remainder re-based, preamble verbatim, mixed-content prose drops.
|
||||
- `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). **#112 (S6):** nine pins — `draggedIDs` dedup (selection rides, ancestor carries descendants, unselected/no-selection go solo), `isValidDrop` (ref moving / inside moving subtree / own-parent-legal / unknown), precise `before`/`afterLast`/`lastChild` landings (incl. the seam-below-a-deeper-follower FIRST-child nest and cross-parent extraction that keyboard batches refuse), contiguous deduped batch landing with id travel, origin no-ops + invalid refusals (snapshot equality — storage untouched), zoom projection (children rooted, depths re-based, zoom root's fold ignored, inner folds still hide, unknown id → whole doc), `rangeIDs` nil across the zoom boundary, and `hitTestDrop` fat-gap bands (30/40/30, ±6 into edge rows, window-space y-up frames, empty rows nil).
|
||||
- `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 (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`).
|
||||
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
|
||||
|
||||
@@ -307,4 +307,20 @@ struct OutlineTreeTests {
|
||||
#expect(!OutlineTree.insertRun([], parentPath: [], index: 0, in: &nodes))
|
||||
#expect(nodes.map(\.text) == ["r1", "r2", "a", "x", "b"])
|
||||
}
|
||||
|
||||
@Test func `headingsLadderBody maps levels to headings with a bullet floor`() {
|
||||
let body = "# Title\n- a\n - a1\n - a2\n - a3\n - a4\n - a4x\n - deep"
|
||||
// roots ##, one heading per level to the ###### floor, deeper
|
||||
// levels stay bullets re-based flush under it; preamble verbatim.
|
||||
#expect(
|
||||
OutlineTree.headingsLadderBody(body)
|
||||
== "# Title\n## a\n### a1\n#### a2\n##### a3\n###### a4\n- a4x\n - deep",
|
||||
)
|
||||
// mixed content: prose between bullets drops (the ask warns)
|
||||
#expect(OutlineTree.headingsLadderBody("- a\nprose\n- b") == "## a\n## b")
|
||||
// identity edges: empty in → empty out; prose-only body is all
|
||||
// preamble → rides verbatim (nothing to ladder)
|
||||
#expect(OutlineTree.headingsLadderBody("") == "")
|
||||
#expect(OutlineTree.headingsLadderBody("# Just a title\nsome words") == "# Just a title\nsome words")
|
||||
}
|
||||
}
|
||||
@@ -517,3 +517,43 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String)
|
||||
try PostStore.createProject(named: ".x", home: home) // hidden — scan skips dot-dirs
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `convert flips type transforms the body once and keeps identity`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home)
|
||||
|
||||
// verbatim: body unchanged, type flips, stamp keeps its own values
|
||||
try PostStore.convert(id: post.id, headingsLadder: false, home: home)
|
||||
let verbatim = try readPost(home, post.id)
|
||||
#expect(verbatim.hasPrefix("---\ntype: post\n"))
|
||||
#expect(verbatim.contains("pass_state: First Draft"))
|
||||
#expect(verbatim.contains("origin: writer"))
|
||||
#expect(PostStore.splitFrontmatter(verbatim).body == "# Chapter\n- one\n - nested")
|
||||
// folder never moved; scan reads the new type on rescan
|
||||
#expect(Post.scan(home: home).first?.id == post.id)
|
||||
#expect(Post.scan(home: home).first?.type == .post)
|
||||
|
||||
// ladder: the headings mapping, preamble above
|
||||
try PostStore.convert(id: post.id, headingsLadder: true, home: home)
|
||||
let ladder = try readPost(home, post.id)
|
||||
#expect(ladder.hasPrefix("---\ntype: post\n"))
|
||||
#expect(PostStore.splitFrontmatter(ladder).body == "# Chapter\n## one\n### nested")
|
||||
|
||||
// a vanished piece throws, never resurrects
|
||||
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
|
||||
try PostStore.convert(id: "no-such-piece", headingsLadder: true, home: home)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `convert works on an archived piece without moving it`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Filed\n- one", type: .outline, home: home)
|
||||
try PostStore.archive(post, home: home)
|
||||
|
||||
try PostStore.convert(id: post.id, headingsLadder: true, home: home)
|
||||
|
||||
let onDisk = try String(contentsOf: home.appendingPathComponent("archive/posts/\(post.id)/post.md"), encoding: .utf8)
|
||||
#expect(onDisk.hasPrefix("---\ntype: post\n"))
|
||||
#expect(onDisk.contains("## one"))
|
||||
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path))
|
||||
}
|
||||
@@ -295,3 +295,176 @@ private func writeMixedOutline(home: URL) throws -> Post {
|
||||
#expect(model.outlineGuardPieceID == nil)
|
||||
#expect(model.session?.postID == prose.id)
|
||||
}
|
||||
|
||||
// #114 (S4): Convert to Post — the session re-route.
|
||||
|
||||
@Test @MainActor func `convert reopens the open piece routed to prose`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
model.stageConversion(post, home: home)
|
||||
#expect(model.pendingConversion?.id == post.id)
|
||||
#expect(model.pendingConversion?.lossy == false) // clean outline
|
||||
model.convertToPost(headingsLadder: true, home: home)
|
||||
|
||||
#expect(model.pendingConversion == nil)
|
||||
#expect(model.session?.postID == post.id) // reopened on the converted body
|
||||
#expect(model.proseOverridePostID == post.id) // prose over the lagging rescan
|
||||
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("type: post"))
|
||||
#expect(onDisk.contains("## one"))
|
||||
}
|
||||
|
||||
@Test @MainActor func `convert of an unopened piece leaves the session alone`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let open = try PostStore.writeNew(body: "# Stay\n", home: home)
|
||||
let outline = try PostStore.writeNew(body: "- a\n - b", type: .outline, home: home)
|
||||
model.select(open.id, home: home)
|
||||
|
||||
model.stageConversion(outline, home: home)
|
||||
model.convertToPost(headingsLadder: false, home: home)
|
||||
|
||||
#expect(model.session?.postID == open.id) // untouched
|
||||
#expect(model.selectedPostID == open.id)
|
||||
#expect(model.proseOverridePostID == nil) // no reopen, no override
|
||||
#expect(try PostStore.readBody(id: outline.id, home: home) == "- a\n - b")
|
||||
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(outline.id)/post.md"), encoding: .utf8)
|
||||
#expect(onDisk.hasPrefix("---\ntype: post\n"))
|
||||
}
|
||||
|
||||
@Test @MainActor func `verbatim convert flips the posts list after the rescan`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home)
|
||||
// bind rescan first so posts knows the piece — then the pin is the
|
||||
// live-report contract: the sidebar type flips once the rescan lands
|
||||
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(model.posts.first(where: { $0.id == post.id })?.type == .outline)
|
||||
|
||||
model.select(post.id, home: home)
|
||||
model.stageConversion(post, home: home)
|
||||
model.convertToPost(headingsLadder: false, home: home) // VERBATIM
|
||||
|
||||
#expect(model.proseOverridePostID == post.id)
|
||||
#expect(model.session?.postID == post.id)
|
||||
// poll for the rescan to land (the same Task { await rescan() } the app runs)
|
||||
for _ in 0 ..< 250 where model.posts.first(where: { $0.id == post.id })?.type != .post {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(model.posts.first(where: { $0.id == post.id })?.type == .post)
|
||||
}
|
||||
|
||||
// #114 audit pins: the hardening round (finish-audit).
|
||||
|
||||
@Test @MainActor func `dirty open piece flushes before the convert`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
model.session?.edit("# Chapter\n- one\n - typed child") // unflushed edit
|
||||
model.stageConversion(post, home: home)
|
||||
model.convertToPost(headingsLadder: false, home: home)
|
||||
|
||||
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("type: post"))
|
||||
#expect(onDisk.contains("- typed child")) // the flush landed BEFORE the transform
|
||||
}
|
||||
|
||||
@Test @MainActor func `staging warns from the session text when the piece is dirty`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
// prose typed since the last flush — disk still clean, session is not
|
||||
model.session?.edit("# Clean\n- one\nA paragraph between bullets.\n- two")
|
||||
model.stageConversion(post, home: home)
|
||||
|
||||
#expect(model.pendingConversion?.lossy == true) // from session.text, not stale disk
|
||||
}
|
||||
|
||||
@Test @MainActor func `mixed body stages a lossy warning from disk`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try writeMixedOutline(home: home) // closed piece — disk is the truth
|
||||
|
||||
model.stageConversion(post, home: home)
|
||||
|
||||
#expect(model.pendingConversion?.lossy == true)
|
||||
}
|
||||
|
||||
@Test @MainActor func `headings aborts when the body went lossy behind the ask`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home)
|
||||
|
||||
model.stageConversion(post, home: home) // staged clean, no warning shown
|
||||
// a foreign write makes the body mixed while the sheet was up
|
||||
let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
|
||||
try PostStore.stamped(body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline)
|
||||
.write(to: file, atomically: true, encoding: .utf8)
|
||||
|
||||
model.convertToPost(headingsLadder: true, home: home)
|
||||
|
||||
#expect(model.lastError?.contains("nothing was converted") == true)
|
||||
#expect(model.session?.postID == nil || model.session?.postID != post.id)
|
||||
let onDisk = try String(contentsOf: file, encoding: .utf8)
|
||||
#expect(onDisk.contains("type: outline")) // untouched — no unconsented drop
|
||||
#expect(onDisk.contains("A paragraph between bullets."))
|
||||
|
||||
// the consented path still converts: a WARNED mixed piece + Headings proceeds
|
||||
model.stageConversion(post, home: home) // now stages lossy from disk
|
||||
model.convertToPost(headingsLadder: true, home: home)
|
||||
let converted = try String(contentsOf: file, encoding: .utf8)
|
||||
#expect(converted.contains("type: post"))
|
||||
#expect(!converted.contains("A paragraph between bullets.")) // dropped, as consented
|
||||
}
|
||||
|
||||
@Test @MainActor func `unanswered conflict aborts the convert`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Clean\n- one", type: .outline, home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
// #67 conflict up: disk holds foreign text, the editor's version unwritten
|
||||
model.session?.diskDidChange(diskText: "# Foreign rewrite\nbody")
|
||||
#expect(model.session?.conflictAlert == true)
|
||||
|
||||
model.stageConversion(post, home: home)
|
||||
model.convertToPost(headingsLadder: false, home: home)
|
||||
|
||||
#expect(model.lastError?.contains("reload question") == true)
|
||||
#expect(model.session?.conflictAlert == true) // still answerable, not trampled
|
||||
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("type: outline")) // nothing converted underneath the alert
|
||||
}
|
||||
|
||||
@Test @MainActor func `failed flush aborts the convert`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home)
|
||||
model.select(post.id, home: home)
|
||||
model.session?.edit("# Chapter\n- one\n - child") // dirty
|
||||
// vanish the piece: the flush throws (never resurrects), convert must abort
|
||||
try FileManager.default.removeItem(at: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true))
|
||||
|
||||
model.stageConversion(post, home: home)
|
||||
model.convertToPost(headingsLadder: true, home: home)
|
||||
|
||||
#expect(model.lastError?.contains("nothing was changed") == true)
|
||||
#expect(model.session?.postID == post.id) // session stays up, dirty and honest
|
||||
}
|
||||
|
||||
@Test @MainActor func `convert dismisses a held guard ask on the same piece`() throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try writeMixedOutline(home: home)
|
||||
|
||||
model.select(post.id, home: home) // guard fires, open held
|
||||
#expect(model.outlineGuardPieceID == post.id)
|
||||
|
||||
model.stageConversion(post, home: home)
|
||||
model.convertToPost(headingsLadder: false, home: home)
|
||||
|
||||
#expect(model.outlineGuardPieceID == nil) // the stale ask died with the outline
|
||||
#expect(model.selectedPostID == nil) // cancel teardown: nothing was open
|
||||
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("type: post"))
|
||||
#expect(onDisk.contains("A paragraph between bullets.")) // verbatim kept everything
|
||||
}
|
||||
Reference in new issue
Block a user