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
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **museion** (3209 symbols, 9400 relationships, 267 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **museion** (3258 symbols, 9633 relationships, 279 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
|
||||
@@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) |
|
||||
| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) |
|
||||
| 2026-10-15 | [20261015-issue111-outline-guard_log.md](docs/devlog/20261015-issue111-outline-guard_log.md) |
|
||||
| 2026-10-15 | [20261015-issue109-outline-type-outliner_log.md](docs/devlog/20261015-issue109-outline-type-outliner_log.md) |
|
||||
@@ -186,5 +187,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
| 2026-10-09 | [20261009-issue88-calibration-gate_log.md](docs/devlog/20261009-issue88-calibration-gate_log.md) |
|
||||
| 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) |
|
||||
| 2026-10-08 | [20261008-issue84-view-menu-doubled_log.md](docs/devlog/20261008-issue84-view-menu-doubled_log.md) |
|
||||
| 2026-10-08 | [20261008-issue83-save-indicator-honesty_log.md](docs/devlog/20261008-issue83-save-indicator-honesty_log.md) |
|
||||
| 2026-09-25 | [20260925-issue50-profile-backup-s2-6_log.md](docs/devlog/20260925-issue50-profile-backup-s2-6_log.md) |<!-- write-log: window-end -->
|
||||
| 2026-10-08 | [20261008-issue83-save-indicator-honesty_log.md](docs/devlog/20261008-issue83-save-indicator-honesty_log.md) |<!-- write-log: window-end -->
|
||||
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **outline:** Convert to Post (v1.2 S4) — a Convert to Post… command on outline pieces (library row menu, Archive pane included): the piece keeps its name, project, and Pass State while `type` flips to post; at the ask the writer picks the body — Verbatim Bullets (default, keeps every line) or Headings (top-level blocks become section headings, deeper levels step down to the `######` floor, deeper still stays bullets; the ask warns when the ladder would drop paragraph lines between bullets); the open session flushes first and reopens in prose; an outline changed on disk behind the ask aborts the convert rather than dropping unconsented prose; one-way in v1 (issue #114)
|
||||
|
||||
- **outline:** drag-reorder + zoom-in (v1.2 S6) — pointer-drag a block run into any sibling seam or onto a block to nest as its child (the block selection rides the drag, a 30/40/30 fat-gap hit test resolves seams vs onto, and a dropped run on an invalid target leaves the document untouched); Esc cancels mid-drag, the moved run becomes the selection; double-click any bullet zooms to its children with breadcrumbs back out, and zoom keeps only fully-visible selections (issue #112)
|
||||
|
||||
- **outline:** mixed-content open guard (v1.2 S7) — opening a `type: outline` piece whose body has paragraph lines between bullets (the parse would drop them on the next save) now asks first: Open in Prose (default — everything visible, nothing drops), Open as Outline (explicit consent — saves normalize as before), or Cancel; the ask presents over an empty editor so nothing can edit before the choice, re-clicking the open piece never re-asks, and a draft or guest staged during the ask displaces it cleanly (issue #111)
|
||||
|
||||
+5
-5
@@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
## Workspace shell (M1, #17 + #18 / S1.1)
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `<project>` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included).
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `<project>` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(hLine truncated
|
||||
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. Folds live in the view, keyed by node UUID — never modeled here.
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
|
||||
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
|
||||
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
|
||||
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
|
||||
|
||||
@@ -72,6 +72,25 @@ nonisolated enum OutlineTree {
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
/// #114 (S4): the headings-ladder conversion body — outline body in,
|
||||
/// post body out. Roots become `##`, each deeper level steps one
|
||||
/// heading down to the `######` floor; deeper levels stay bullets
|
||||
/// (indent re-based so the first bullet level sits flush under the
|
||||
/// floor). Preamble rides verbatim above — `# Title` survives.
|
||||
/// Mixed content: parse drops prose lines (the convert ask warns).
|
||||
static func headingsLadderBody(_ markdown: String) -> String {
|
||||
let (preamble, items) = scan(markdown)
|
||||
var lines = preamble
|
||||
for (depth, text) in items {
|
||||
if depth <= 4 {
|
||||
lines.append(String(repeating: "#", count: depth + 2) + " " + text)
|
||||
} else {
|
||||
lines.append(String(repeating: " ", count: depth - 5) + "- " + text)
|
||||
}
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
/// Lines → (verbatim preamble, flat clamped items). Trailing blank lines
|
||||
/// are noise — dropping them makes "" parse to ([], []).
|
||||
private static func scan(_ markdown: String) -> (preamble: [String], items: [(depth: Int, text: String)]) {
|
||||
|
||||
+32
-5
@@ -272,17 +272,32 @@ nonisolated enum PostStore {
|
||||
/// vanished post throws — `writeNew` is the only creator; saving must
|
||||
/// never resurrect a deleted post with reset metadata.
|
||||
static func overwrite(id: String, body: String, home: URL) throws {
|
||||
let piece = try existingStamp(id: id, home: home)
|
||||
try stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
|
||||
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
/// #114: the shared read behind `overwrite` and `convert` — resolve the
|
||||
/// folder, read the file (vanished → throw: a write never resurrects,
|
||||
/// #18), derive the preserved stamp values. The caller stamps its own
|
||||
/// type and body.
|
||||
// swiftlint:disable:next large_tuple
|
||||
private static func existingStamp(id: String, home: URL) throws -> (
|
||||
dir: URL, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType, body: String,
|
||||
) {
|
||||
guard let dir = folder(of: id, home: home),
|
||||
let existing = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
|
||||
else {
|
||||
throw CocoaError(.fileReadNoSuchFile)
|
||||
}
|
||||
let matter = Post.frontmatter(of: existing)
|
||||
let passState = Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft
|
||||
let origin = Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer
|
||||
let type = Post.ContentType(rawValue: matter["type"] ?? "") ?? .post
|
||||
try stamped(body: body, passState: passState, origin: origin, type: type)
|
||||
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
return (
|
||||
dir,
|
||||
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft,
|
||||
Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer,
|
||||
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post,
|
||||
splitFrontmatter(existing).body,
|
||||
)
|
||||
}
|
||||
|
||||
/// Body text (frontmatter stripped) for editing; nil when unreadable.
|
||||
@@ -294,6 +309,18 @@ nonisolated enum PostStore {
|
||||
return splitFrontmatter(text).body
|
||||
}
|
||||
|
||||
/// #114 (S4): Convert to Post — the one-time in-place transform. The
|
||||
/// file's own `pass_state`/`origin` are kept (the stamp re-derives
|
||||
/// them from the file, same as overwrite), id and folder never move,
|
||||
/// `type` flips to `post`, the body transforms once. Ladder = the
|
||||
/// headings mapping; verbatim = body unchanged. One-way in v1.
|
||||
static func convert(id: String, headingsLadder: Bool, home: URL) throws {
|
||||
let piece = try existingStamp(id: id, home: home)
|
||||
let transformed = headingsLadder ? OutlineTree.headingsLadderBody(piece.body) : piece.body
|
||||
try stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
|
||||
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
// MARK: Cursor-state sidecar (#66)
|
||||
|
||||
/// Cursor state for one post: selection + scroll, `.museion-state.json`
|
||||
|
||||
@@ -131,6 +131,12 @@ final class PostsModel {
|
||||
/// a routing override with lastDraftWasOutline's exact lifecycle (dies
|
||||
/// on the next open/draft/guest; the rescan lag window is covered).
|
||||
private(set) var proseOverridePostID: String?
|
||||
|
||||
/// #114 (S4): the staged Convert to Post ask (row menu → sheet). The
|
||||
/// ask targets a piece id, not the session — it survives background
|
||||
/// selects; the sheet is modal in its window, and the convert itself
|
||||
/// re-derives everything (flush, disk read) at answer time.
|
||||
private(set) var pendingConversion: PendingConversion?
|
||||
/// Last failed-op message surfaced in the editor (nil = clean).
|
||||
private(set) var lastError: String?
|
||||
/// Home the watcher is bound to; also the rescan target.
|
||||
@@ -170,6 +176,10 @@ final class PostsModel {
|
||||
// Scan + the #67 disk read both run off-main (a synced large post.md
|
||||
// must never stall the UI on a watcher burst).
|
||||
let openPostID = session?.postID
|
||||
// #114 audit: identity, not id — a same-id reopen (convert/restore/
|
||||
// move) must not receive the OLD session's stale disk text as a
|
||||
// spurious #67 conflict.
|
||||
let openSession = session
|
||||
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
|
||||
let posts = Post.scan(home: home)
|
||||
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
|
||||
@@ -186,8 +196,8 @@ final class PostsModel {
|
||||
}
|
||||
// #67: watcher echo check on the open post — equality against the
|
||||
// session's lastFlushedText suppresses our own writes exactly.
|
||||
if let session, let openDiskText {
|
||||
session.diskDidChange(diskText: openDiskText)
|
||||
if openSession === session, let openDiskText {
|
||||
openSession?.diskDidChange(diskText: openDiskText)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,10 +424,18 @@ final class PostsModel {
|
||||
/// lastError set; the session stays up, dirty and honest.
|
||||
private 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 {
|
||||
lastError = "This piece changed on disk underneath you — answer the reload question first."
|
||||
return false
|
||||
}
|
||||
if !session.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 moved."
|
||||
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -673,3 +691,74 @@ extension PostsModel {
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
|
||||
// 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, home: URL) {
|
||||
guard post.type == .outline else { return }
|
||||
let body: String = if let session, session.postID == post.id {
|
||||
session.text
|
||||
} else {
|
||||
PostStore.readBody(id: post.id, home: home) ?? ""
|
||||
}
|
||||
pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body))
|
||||
}
|
||||
|
||||
/// #114 (S4): the ask's Cancel (binding dismissal).
|
||||
func cancelConversion() {
|
||||
pendingConversion = nil
|
||||
}
|
||||
|
||||
/// #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.
|
||||
func convertToPost(headingsLadder: Bool, home: URL) {
|
||||
guard let pending = pendingConversion else { return }
|
||||
pendingConversion = nil
|
||||
guard flushOrAbort(pending.id) else { return }
|
||||
do {
|
||||
// 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 — abort, nothing converted (#114 audit).
|
||||
if headingsLadder, !pending.lossy,
|
||||
let body = PostStore.readBody(id: pending.id, home: home),
|
||||
OutlineTree.parsesWithLoss(body)
|
||||
{
|
||||
lastError = "The outline changed since the sheet opened — nothing was converted."
|
||||
return
|
||||
}
|
||||
try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home)
|
||||
if session?.postID == pending.id {
|
||||
session?.teardown(flushFirst: false) // flushOrAbort already wrote
|
||||
session = nil
|
||||
proseOverridePostID = pending.id
|
||||
openUnguarded(pending.id, home: home)
|
||||
}
|
||||
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()
|
||||
}
|
||||
lastError = nil
|
||||
Task { await rescan() }
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,6 +272,13 @@ struct PostsLibraryColumn: View {
|
||||
}
|
||||
.contextMenu {
|
||||
Button("Rename…") { renamingPost = post }
|
||||
// #114 (S4): outline pieces only — the ask picks the
|
||||
// body transform, then the piece becomes a prose post.
|
||||
if post.type == .outline {
|
||||
Button("Convert to Post…") {
|
||||
model.stageConversion(post, home: home)
|
||||
}
|
||||
}
|
||||
Button("Move to Project…") { movingPost = post }
|
||||
Button("Move to Archive") {
|
||||
model.archivePost(post, home: home)
|
||||
|
||||
@@ -100,6 +100,14 @@ struct WorkspaceView: View {
|
||||
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
|
||||
}
|
||||
}
|
||||
// #114 (S4): the Convert to Post ask — which body the outline
|
||||
// piece becomes (verbatim bullets vs headings ladder). Verbatim
|
||||
// is the default: lossless. Esc/Cancel converts nothing.
|
||||
.sheet(isPresented: convertAskBinding) {
|
||||
ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in
|
||||
gate.posts.convertToPost(headingsLadder: headingsLadder, home: gate.museionHome)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
|
||||
.frame(minWidth: 480, minHeight: 320)
|
||||
@@ -160,6 +168,18 @@ struct WorkspaceView: View {
|
||||
)
|
||||
}
|
||||
|
||||
/// #114 (S4): the Convert to Post ask — dismissal is the cancel.
|
||||
private var convertAskBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: { gate.posts.pendingConversion != nil },
|
||||
set: {
|
||||
if !$0 {
|
||||
gate.posts.cancelConversion()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func paneContent(_ geo: GeometryProxy) -> some View {
|
||||
@Bindable var gate = gate
|
||||
@@ -309,6 +329,13 @@ private struct ArchivePaneView: View {
|
||||
model.restorePost(post, home: home)
|
||||
}
|
||||
Button("Rename…") { renamingPost = post }
|
||||
// #114 (S4): works archived too — the piece
|
||||
// stays where it is, only type + body flip.
|
||||
if post.type == .outline {
|
||||
Button("Convert to Post…") {
|
||||
model.stageConversion(post, home: home)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -420,6 +447,51 @@ private struct OutlineGuardSheet: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
|
||||
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
|
||||
/// to headings. On mixed content the ladder would drop prose lines —
|
||||
/// the sheet says so.
|
||||
private struct ConvertSheet: View {
|
||||
let lossy: Bool
|
||||
/// false = verbatim bullets, true = headings ladder — one decision,
|
||||
/// one model call.
|
||||
let convert: (Bool) -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Convert to Post")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
if lossy {
|
||||
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
// Dismissal itself is the cancel (binding set(false) →
|
||||
// cancelConversion) — Esc and ⌘. land here too.
|
||||
Button("Cancel", role: .cancel) {}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Headings") {
|
||||
convert(true)
|
||||
}
|
||||
Button("Verbatim Bullets") {
|
||||
convert(false)
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 440)
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
|
||||
/// future materialize path). Create runs through the model's raw op; the
|
||||
/// thrown reason is shown inline and the sheet stays up.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Build S4: Convert to Post — in-place, transform choice at conversion
|
||||
|
||||
> **Date:** 2026-10-16
|
||||
> **Type:** issue
|
||||
> **Reference:** [#114](https://git.babylondreams.de/AlexKucera/Museion/issues/114) (map [#110](https://git.babylondreams.de/AlexKucera/Museion/issues/110))
|
||||
|
||||
## Goal
|
||||
|
||||
Land S4 of the Outliner II map: a Convert to Post command on outline pieces — id, folder, Pass State, origin kept; `type` frontmatter flips to `post`; the body transforms once, with the writer picking the transform at conversion (verbatim bullets vs headings ladder). Open session flushes first, then re-routes to the prose surface. One-way in v1.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- **`OutlineTree.headingsLadderBody(_:)`** — the pure ladder transform: roots → `##`, each deeper level steps one heading down to the `######` floor; deeper levels stay bullets, indent re-based flush under the floor; preamble (`# Title`) rides verbatim above. Reuses the private `scan`, so ladder depths and the outliner's depths can never disagree.
|
||||
- **`PostStore.convert(id:headingsLadder:home:)`** — the one-time in-place write: re-derives `pass_state`/`origin` from the file's own frontmatter (same as `overwrite`), stamps `type: post`, writes the (possibly transformed) body atomically. id and folder never move. Vanished piece throws, never resurrects.
|
||||
- **`PostsModel`** — `PendingConversion { id, lossy }` staged by `stageConversion(_:home:)` (outline pieces only; `lossy` = `OutlineTree.parsesWithLoss`, driving the sheet's warning), `cancelConversion()`, and `convertToPost(headingsLadder:home:)`: flush-first via the existing `flushOrAbort` (a failed write aborts with the strip message), convert, then — only when the piece was the open session — teardown-no-flush + `openUnguarded` reopen with `proseOverridePostID` set for the rescan lag window (literally the `lastDraftWasOutline` machinery reversed; the existing override slot, no new routing state). An unopened piece just converts on disk.
|
||||
- **UI** — `ConvertSheet` (house ask pattern, WorkspaceView): Verbatim Bullets (default action — lossless) · Headings · Cancel (dismissal = cancel, binding pattern); a warning paragraph when the ladder would drop prose lines. Row-menu `Convert to Post…` on outline pieces in the Posts library AND the Archive pane (archived piece stays archived — only type + body flip).
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Verbatim default, ladder opt-in | Verbatim is lossless on mixed content (body unchanged); the ladder is the one that drops prose lines — the default must never destroy. |
|
||||
| Ladder floor at `######`, deeper stay bullets | Markdown has six heading levels; depth > 4 outlines are rare — bullets under the floor keep their relative nesting without inventing `#######`. The simplest honest rule the ticket named. |
|
||||
| Reuse `proseOverridePostID` for the re-route | It already has `lastDraftWasOutline`'s exact lifecycle (dies on next open/draft/guest) and already flows through PostsPaneView's routing expression — the ticket's "flip the machinery the other way" is this slot. Zero new routing state. |
|
||||
| Flush-first via `flushOrAbort`, teardown-no-flush after | Convert reads disk; unflushed outliner edits must land before the transform. A failed flush aborts the convert (rename's pattern). After a good flush the teardown must NOT flush again — the file has moved on to converted content; a second flush would overwrite the conversion. |
|
||||
| Ask is id-scoped, not session-scoped | The ask survives background selects (multi-window) — conversion targets a piece, and `convertToPost` re-derives everything (flush, disk read) at answer time. No displacement wiring needed. |
|
||||
| Sheet, not inline picker | House pattern (OriginAsk / OutlineGuard / NewProject): model stages, WorkspaceView presents, answers call the model. |
|
||||
| Convert lives in the row menu | The menu is already per-piece and type-aware (✳ suffix); the editing surface stays untouched — routing flips it to prose the moment the answer lands. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| `patch` fuzzy-match mangled `OutlineGuardSheet`'s closing braces (over-indented closers, ConvertSheet nested-looking) | old_string indentation didn't byte-match the file; fuzzy match accepted a wrong anchor | Region rewritten deterministically by line index (execute_code), verified by build |
|
||||
| Test append landed INSIDE the last `@Test` function ("Attribute 'Test' cannot be applied to a function within function") | `PostStoreTests.swift` uses file-scope `@Test` funcs — the file's final `}` closed the function, not a type; stripping it swallowed the pin into the body | Restored the function close before the pin; compiler confirmed |
|
||||
| swiftlint: 10 warnings across changed files | All pre-existing ceilings (file/type-length, the `up` param, the NFD comment line) — files already over the limits at HEAD | None owed; lint scoped to changed files only (no blanket run — #112 trap) |
|
||||
| Live report: verbatim convert "doesn't update the sidebar — row keeps ✳" (works with Headings) | Could not reproduce: model-level pin shows posts flips to `.post` and routing goes prose once the async rescan lands; headings vs verbatim share one code path | Read as rescan-lag/stale-instance on first look; user confirmed fixed on retest. Pinned as `verbatim convert flips the posts list after the rescan` |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/OutlineTree.swift` | `headingsLadderBody(_:)` — the pure ladder transform |
|
||||
| `Museion/PostStore.swift` | `convert(id:headingsLadder:home:)` — the in-place type flip + one-time body transform |
|
||||
| `Museion/PostsModel.swift` | `PendingConversion`, `pendingConversion` slot, `stageConversion`/`cancelConversion`/`convertToPost` (#114 extension) |
|
||||
| `Museion/WorkspaceView.swift` | `ConvertSheet` + `convertAskBinding` (4th house ask); Archive row menu entry |
|
||||
| `Museion/PostsPaneView.swift` | Posts library row menu: `Convert to Post…` on outline pieces |
|
||||
| `MuseionTests/OutlineTreeTests.swift` | Ladder pin: ladder shape, bullet floor, preamble, mixed-content drop |
|
||||
| `MuseionTests/PostStoreTests.swift` | Convert round-trip: verbatim keeps body + flips type + scan reads post; ladder shape; vanished-piece throw |
|
||||
| `MuseionTests/PostsModelTests.swift` | Lifecycle pins: open piece reopens routed prose (override set, disk converted); unopened piece converts without touching the session |
|
||||
|
||||
## Verification
|
||||
|
||||
- `xcodebuild build` — SUCCEEDED
|
||||
- `xcodebuild test` — SUCCEEDED (206 unit incl. 13 new pins + UI smoke, post-audit count)
|
||||
- `swiftformat` on changed files (2 reformatted), `swiftlint` — 0 new violations (10 pre-existing ceiling warnings, verified at HEAD)
|
||||
- GitNexus: impact before edits (PostsModel 59 / OutlineTree 57 dependants — all changes additive); `detect-changes` after: 8 files, risk critical by line-shift heuristic (`stateURL` flagged by position; body untouched) — discharged by full build + full suite green, #112 posture.
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Commit + push pending authorization (house rule: never commit autonomously).
|
||||
- [ ] Map #110 continues: S5 prose-list shortcuts (#115) remains open on the frontier.
|
||||
- [ ] One-way in v1: Post → Outline is not built (per the ticket; reverse convert is a fresh decision if ever wanted).
|
||||
- [ ] Known ceiling: converting a piece open in ANOTHER window reopens the session there too (app-scoped model) — same-window convert is the tested path.
|
||||
|
||||
## Session audit (finish-audit pass)
|
||||
|
||||
Three fresh-context reviewers (ponytail / security / general) over the working-tree diff. Accepted and fixed, each behind a pin (`MuseionTests/PostsModelTests.swift` audit section):
|
||||
|
||||
- **Answer-time consent recheck (security MEDIUM, merged with general's stale-`lossy` finding)** — the sheet's warning covered the STAGED body; a foreign write behind the ask could make Headings drop unconsented prose. `convertToPost` now re-reads post-flush: `headingsLadder && nowLossy && !warned` aborts with "nothing was converted". Staging also derives `lossy` from `session.text` when the piece is open (disk lags the debounce). Pinned both ways (unwarned abort + warned-consent proceeds).
|
||||
- **Unanswered #67 conflict aborts the op (general MEDIUM, pre-existing class)** — `flushOrAbort` now treats `conflictAlert` like a failed flush: abort with the reload-question message, alert stays answerable. Fixes the class for rename/move/archive/restore too. Pinned.
|
||||
- **Spurious conflict after same-id reopen (general MEDIUM, pre-existing class)** — `rescan` captured the open post's ID; an in-flight rescan delivered the OLD session's stale disk text to the NEW session as a #67 conflict. Gate is now session identity (`openSession === session`). Fix landed un-pinned: the race window isn't harness-reproducible; the gate is an identity comparison.
|
||||
- **Held #111 guard ask cleared on convert (general LOW)** — multi-window: converting a piece whose guard ask is held now dismisses the ask as a cancel (`cancelOutlineGuard`). Pinned.
|
||||
- **`flushOrAbort` failure copy** — "— nothing was moved." → "— nothing was changed." (fits convert; no test pinned the old string).
|
||||
- **Ponytail round** — `PostStore.existingStamp` extracted (overwrite/convert shared 6 near-copy lines); `PendingConversion: Equatable` cut (dead); `ConvertSheet` two closures → one `(Bool) -> Void`; the test's hand-copy of PostsPaneView's routing expression cut (goes stale the moment #115 reshapes routing). Freebies taken: archived-piece convert pin, ladder identity edges (empty/prose-only), dirty-flush-before-convert pin, failed-flush-abort pin.
|
||||
- Pin discrimination verified: the three new guards flipped off once → their pins failed (3 for 3), restored, suite green.
|
||||
|
||||
Deferred explicitly: security INFO-2 (unreadable body stages lossy-false + misleading missing-file error — house pattern, same shape as `overwrite`); disk-type re-derivation in `stageConversion` (the destructive half is covered by the answer-time recheck; verbatim re-stamp of an externally-flipped piece is harmless); `"## "` trailing space on empty ladder items (mirrors the outliner's own `"- "` serialization).
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-10-16 | issue | [20261016-issue114-convert-to-post_log.md](20261016-issue114-convert-to-post_log.md) | #114 Convert to Post: in-place type flip + verbatim/headings-ladder ask, prose re-route via proseOverridePostID — 206 tests green (audit round included) |
|
||||
| 2026-10-16 | issue | [20261016-issue112-outline-interaction-ii_log.md](20261016-issue112-outline-interaction-ii_log.md) | S6 landed: drag-reorder + zoom in the outliner per wf113 verdict A; AppKit-tree hit-testing; tests un-broken for target 27.0 |
|
||||
| 2026-10-15 | issue | [20261015-issue111-outline-guard_log.md](20261015-issue111-outline-guard_log.md) | #111 mixed-content outline guard: parsesWithLoss + open ask, audit round (reselect/displacement holes pinned) — 179 tests green |
|
||||
| 2026-10-15 | issue | [20261015-issue109-outline-type-outliner_log.md](20261015-issue109-outline-type-outliner_log.md) | #109 outliner: OutlineTree + block surface, LogSeq keys, natural-line-box typography; 170 tests green |
|
||||
|
||||
Reference in new issue
Block a user