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

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

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

Closes #111

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

No files matched your search

+2 -1
View File
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (2945 symbols, 8292 relationships, 223 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. This project is indexed by GitNexus as **museion** (2998 symbols, 8543 relationships, 240 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). > 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 --> <!-- write-log: window-start -->
| Date | Log | | Date | Log |
|------|-----| |------|-----|
| 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) | | 2026-10-15 | [20261015-issue109-outline-type-outliner_log.md](docs/devlog/20261015-issue109-outline-type-outliner_log.md) |
| 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) | | 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) |
| 2026-10-13 | [20261013-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) | | 2026-10-13 | [20261013-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) |
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added ### Added
- **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)
- **outline:** outliner surface & outline type (v1.1 S3, ADR-0013 per #105 variant B) — File ▸ New Outline ⇧⌘N stages a `type: outline` piece; the outliner is a dedicated block surface: nested bullets with LogSeq-style keys (Tab/⇧Tab indent/outdent, ⌥↑/⌥↓ move subtree, ↑/↓ hop visible blocks, ⇧↑/⇧↓ block-select runs, ⌘↑/⌘↓ fold/unfold, Enter splits at the caret), one live caret row over inert rows, session-scoped folds, and the same debounced autosave / ⌘S / external-change alert as prose; hand-edited files parse leniently and normalize on save (issue #109) - **outline:** outliner surface & outline type (v1.1 S3, ADR-0013 per #105 variant B) — File ▸ New Outline ⇧⌘N stages a `type: outline` piece; the outliner is a dedicated block surface: nested bullets with LogSeq-style keys (Tab/⇧Tab indent/outdent, ⌥↑/⌥↓ move subtree, ↑/↓ hop visible blocks, ⇧↑/⇧↓ block-select runs, ⌘↑/⌘↓ fold/unfold, Enter splits at the caret), one live caret row over inert rows, session-scoped folds, and the same debounced autosave / ⌘S / external-change alert as prose; hand-edited files parse leniently and normalize on save (issue #109)
- **library:** projects & archive UI (v1.1 S2, variant B per #104) — the library column groups pieces by project under serif lowercase section heads (collapse toggle, `· N` counts, Pass-State groups inside); Move to Project / Move to Archive / Move Back / whole-project Unarchive as folder moves (post.md bytes untouched, never clobbering, ids globally unique); an Archive rail destination lists archived pieces grouped by project with row-click back to Posts; File ▸ New Post ⌘N and New Project… ⌥⌘N; New Project opens a draft targeted at it, and every folder move flushes pending edits first — a failed write aborts the move with nothing relocated (issue #108) - **library:** projects & archive UI (v1.1 S2, variant B per #104) — the library column groups pieces by project under serif lowercase section heads (collapse toggle, `· N` counts, Pass-State groups inside); Move to Project / Move to Archive / Move Back / whole-project Unarchive as folder moves (post.md bytes untouched, never clobbering, ids globally unique); an Archive rail destination lists archived pieces grouped by project with row-click back to Posts; File ▸ New Post ⌘N and New Project… ⌥⌘N; New Project opens a draft targeted at it, and every folder move flushes pending edits first — a failed write aborts the move with nothing relocated (issue #108)
+3 -3
View File
@@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Workspace shell (M1, #17 + #18 / S1.1) ## 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. - `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). - `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. - `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.
- `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). - `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). - `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. **#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(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). - `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. 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. Folds live in the view, keyed by node UUID — never modeled here. - `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. 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), 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) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` (borderless NSTextView subclass, native undo/IME, rust caret) on the focused row, static inline-markdown text elsewhere (tap focuses, caret at end — v1 ceiling, ponytail-marked); typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box — the prose CSS-1.8 `lineHeightMultiple` is deliberately absent: an inflated fragment grows the focused row and detaches the bullet; test-pinned), static rows render the same NSFont (no face swap on focus), the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — exactly the bullet-cell height, no focus jump. Key set (AppKit traps documented at the `keyDown` head: 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 (anchor↔focus highlight, batch structural ops; bare arrows/click/typing clear) · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Folds are session-scoped view state (`folded: Set<UUID>`, reset on every load — never serializes, ADR-0013). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` (debounce/⌘S/#67 conflict unchanged) or `onDraftEdit` for drafts; focus follows node IDs (they travel through ops), caret lands via `pendingCaret` at next mount. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner (⌘S/toolbar/conflict/reading toggle all keep working — reading renders the serialized markdown via apex unchanged); `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions (`PostsModel.lastDraftWasOutline` covers the rescan lag after a fresh save; cleared in newPost/select/openExternal wherever the draft dies). - `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), 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) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` (borderless NSTextView subclass, native undo/IME, rust caret) on the focused row, static inline-markdown text elsewhere (tap focuses, caret at end — v1 ceiling, ponytail-marked); typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box — the prose CSS-1.8 `lineHeightMultiple` is deliberately absent: an inflated fragment grows the focused row and detaches the bullet; test-pinned), static rows render the same NSFont (no face swap on focus), the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — exactly the bullet-cell height, no focus jump. Key set (AppKit traps documented at the `keyDown` head: 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 (anchor↔focus highlight, batch structural ops; bare arrows/click/typing clear) · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Folds are session-scoped view state (`folded: Set<UUID>`, reset on every load — never serializes, ADR-0013). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` (debounce/⌘S/#67 conflict unchanged) or `onDraftEdit` for drafts; focus follows node IDs (they travel through ops), caret lands via `pendingCaret` at next mount. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner (⌘S/toolbar/conflict/reading toggle all keep working — reading renders the serialized markdown via apex unchanged); `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions (`PostsModel.lastDraftWasOutline` covers the rescan lag after a fresh save; cleared in newPost/select/openExternal wherever the draft dies).
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css). - `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
+16
View File
@@ -32,6 +32,22 @@ nonisolated struct OutlineNode: Identifiable, Equatable {
/// All ops are path-addressed (`[Int]` root→leaf indices) and return the /// All ops are path-addressed (`[Int]` root→leaf indices) and return the
/// moved node's new path, or nil when the op is a boundary no-op. /// moved node's new path, or nil when the op is a boundary no-op.
nonisolated enum OutlineTree { nonisolated enum OutlineTree {
/// #111: would parse drop content? True when any NON-BLANK line after
/// the first item isn't an item line — the prose the outliner can't
/// show and the next save would silently drop. Blank lines don't count:
/// they're formatting, not prose, and normalize quietly.
static func parsesWithLoss(_ markdown: String) -> Bool {
var sawItem = false
for line in markdown.split(separator: "\n", omittingEmptySubsequences: false) {
if parseItem(String(line)) != nil {
sawItem = true
} else if sawItem, !line.trimmed().isEmpty {
return true
}
}
return false
}
/// Lenient parse. Returns verbatim preamble lines (before the first item) /// Lenient parse. Returns verbatim preamble lines (before the first item)
/// + the node tree. `-`/`*` markers followed by whitespace, any indent /// + the node tree. `-`/`*` markers followed by whitespace, any indent
/// (tab = 2 spaces, depth = width/2), depth clamps to previous + 1; /// (tab = 2 spaces, depth = width/2), depth clamps to previous + 1;
+108 -9
View File
@@ -122,6 +122,15 @@ final class PostsModel {
/// prose editor. True only between saveDraft and the next selection. /// prose editor. True only between saveDraft and the next selection.
private(set) var lastDraftWasOutline = false private(set) var lastDraftWasOutline = false
/// #111 (S7): a mixed-content outline piece whose open is held for the
/// guard ask. Non-nil = the ask is up (no session — the ask presents
/// over an empty editor); cleared by any answer.
private(set) var outlineGuardPieceID: String?
/// #111 (S7): the piece the guard's Prose answer opened in prose mode —
/// 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?
/// Last failed-op message surfaced in the editor (nil = clean). /// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String? private(set) var lastError: String?
/// Home the watcher is bound to; also the rescan target. /// Home the watcher is bound to; also the rescan target.
@@ -218,6 +227,8 @@ final class PostsModel {
session = nil session = nil
draft = PostDraft(project: target) draft = PostDraft(project: target)
lastDraftWasOutline = false // #109: the afterglow died with the draft lastDraftWasOutline = false // #109: the afterglow died with the draft
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil selectedPostID = nil
} }
@@ -231,6 +242,8 @@ final class PostsModel {
session = nil session = nil
draft = PostDraft(text: "- ", project: target, type: .outline) draft = PostDraft(text: "- ", project: target, type: .outline)
lastDraftWasOutline = false // #109: a new draft resets the afterglow lastDraftWasOutline = false // #109: a new draft resets the afterglow
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil selectedPostID = nil
} }
@@ -269,19 +282,37 @@ final class PostsModel {
/// selecting away). #19: opening a post ends the previous session /// selecting away). #19: opening a post ends the previous session
/// (flush-on-selection-change, #64) and starts a new one. #92: it also /// (flush-on-selection-change, #64) and starts a new one. #92: it also
/// dismisses the external guest (flush first). /// dismisses the external guest (flush first).
/// #111 (S7): a `type: outline` piece that parses with dropped prose
/// fires the mixed-content guard — the open is held (routing stays
/// prose) until the writer picks. The old session still ends here:
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String, home: URL) { func select(_ id: String, home: URL) {
dismissExternal() dismissExternal()
if let session, session.postID != id { // A reselect of the already-open piece is a no-op — INCLUDING a
// guarded one: the piece is open under a prior answer, and firing
// the ask again would nil its session without teardown (the armed
// debounce would then flush mid-ask, outside any owned session).
if let session, session.postID == id {
return
}
if let session {
session.teardown(flushFirst: true) session.teardown(flushFirst: true)
} }
session = id == session?.postID ? session : EditorSession(postID: id, home: home) if isGuardedOutline(id, home: home) {
draft = nil outlineGuardPieceID = id
// #108: abandoning the draft kills its explicit project target too — proseOverridePostID = nil
// a later New Post must not silently land in the abandoned project. session = nil
pendingProject = nil draft = nil
lastDraftWasOutline = false // #109: opening a post is a fresh context pendingProject = nil
selectedPostID = id lastDraftWasOutline = false
wireSession() selectedPostID = id
return
}
// The prior session was torn down above; openUnguarded's guards
// are dead code on this path (session is nil or a different id) —
// kept: one open body answers select and the ask alike.
openUnguarded(id, home: home)
proseOverridePostID = nil // #111: the override died with the open it covered
} }
/// Draft typing from the editor (private(set) barrier). /// Draft typing from the editor (private(set) barrier).
@@ -505,6 +536,8 @@ final class PostsModel {
draft = nil draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask
externalSession = EditorSession(target: .externalFile(target)) externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true { if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
@@ -574,3 +607,69 @@ final class PostsModel {
externalSession?.onError = route externalSession?.onError = route
} }
} }
// MARK: Mixed-content outline guard (#111, S7)
extension PostsModel {
/// A `type: outline` piece that parses with dropped prose — the guard's
/// target. The old session already ended by the time this runs; its
/// flush was prose-mode, so it couldn't drop anything.
/// Type: the scan's word when the list knows it (archive pane opens,
/// app-start selection), the frontmatter's word during the rescan lag
/// (the same window lastDraftWasOutline covers) — ONE disk read derives
/// both. No watched home yet (pre-bind) = post: nothing to guard.
private func isGuardedOutline(_ id: String, home: URL) -> Bool {
guard let dir = PostStore.folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type {
known
} else {
Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
}
return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body)
}
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
/// outliner never mounts, nothing drops); Outline = explicit consent,
/// opens the outliner (saves normalize/drop as today). Cancel = back
/// out (no session); the piece stays guarded on the next open.
func openGuardedOutlineInProse(home: URL) {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
proseOverridePostID = id // routing: prose until the next open
openUnguarded(id, home: home)
}
func openGuardedOutlineAsOutline(home: URL) {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
openUnguarded(id, home: home)
}
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
/// nothing stays selected over the empty editor).
func cancelOutlineGuard() {
outlineGuardPieceID = nil
if session == nil {
selectedPostID = nil
}
}
/// #111 (S7): the open with the guard passed (either answer or a clean
/// parse) — the plain select body. No re-check: the answer is the
/// explicit choice the ruling requires.
private func openUnguarded(_ id: String, home: URL) {
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
}
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
draft = nil
pendingProject = nil
lastDraftWasOutline = false
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
}
}
+17 -2
View File
@@ -102,13 +102,28 @@ struct PostsPaneView: View {
// #109: outline routing — the scan's type when the list knows the // #109: outline routing — the scan's type when the list knows the
// piece, plus the just-saved-draft afterglow (the posts list lags // piece, plus the just-saved-draft afterglow (the posts list lags
// one rescan; without the flag the fresh outline flashes prose). // one rescan; without the flag the fresh outline flashes prose).
// #111 (S7): the guard's Prose answer overrides to prose (same
// lag window); the guard hold never reaches here (no session).
PostEditorView( PostEditorView(
session: session, session: session,
draftText: nil, draftText: nil,
outline: model.lastDraftWasOutline outline: session.postID != model.proseOverridePostID
|| model.posts.first(where: { $0.id == session.postID })?.type == .outline, && (model.lastDraftWasOutline
|| model.posts.first(where: { $0.id == session.postID })?.type == .outline),
) )
.id(session.postID ?? "post") .id(session.postID ?? "post")
} else if model.outlineGuardPieceID != nil {
// #111 (S7): the guard ask is up — empty editor, nothing
// editable until the choice lands.
VStack(spacing: 10) {
Image(systemName: "list.bullet")
.font(.largeTitle)
.foregroundStyle(DesignTokens.muted)
Text("This outline has lines the outliner can't show.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else { } else {
VStack(spacing: 10) { VStack(spacing: 10) {
Image(systemName: "square.and.pencil") Image(systemName: "square.and.pencil")
+61
View File
@@ -89,6 +89,17 @@ struct WorkspaceView: View {
return nil return nil
} }
} }
// #111 (S7): the mixed-content outline guard ask — presents over an
// empty editor (select held the open; nothing can edit while it's
// up). Prose = safe open; Outline = explicit consent to the save
// drop; Esc/Cancel backs out with nothing opened.
.sheet(isPresented: outlineGuardBinding) {
OutlineGuardSheet {
gate.posts.openGuardedOutlineInProse(home: gate.museionHome)
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
}
}
} }
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout). // Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320) .frame(minWidth: 480, minHeight: 320)
@@ -137,6 +148,18 @@ struct WorkspaceView: View {
) )
} }
/// #111 (S7): the outline guard ask presents while an open is held.
private var outlineGuardBinding: Binding<Bool> {
Binding(
get: { gate.posts.outlineGuardPieceID != nil },
set: {
if !$0 {
gate.posts.cancelOutlineGuard()
}
},
)
}
@ViewBuilder @ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View { private func paneContent(_ geo: GeometryProxy) -> some View {
@Bindable var gate = gate @Bindable var gate = gate
@@ -359,6 +382,44 @@ private struct OriginAskSheet: View {
} }
} }
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
/// lines the outliner can't show — opening it as an outline would drop
/// them on the next save. Prose = nothing drops; Outline = the explicit
/// choice the ruling requires.
private struct OutlineGuardSheet: View {
let openInProse: () -> Void
let openAsOutline: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Open as outline or prose?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelOutlineGuard) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Open as Outline") {
openAsOutline()
}
Button("Open in Prose") {
openInProse()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 420)
}
}
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any /// #108: New Project ask — the sheet behind File ▸ New Project… (and any
/// future materialize path). Create runs through the model's raw op; the /// future materialize path). Create runs through the model's raw op; the
/// thrown reason is shown inline and the sheet stays up. /// thrown reason is shown inline and the sheet stays up.
+2 -2
View File
@@ -22,13 +22,13 @@ Owned by the root AGENTS.md contract.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests. - `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`. - `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). - `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. - `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call.
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. - `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. - `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. - `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. - `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). - `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107).
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). - `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet.
- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). - `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting).
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (the monitor itself can't run in the test host — no running NSApp loop). - `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (the monitor itself can't run in the test host — no running NSApp loop).
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013). - ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
+16
View File
@@ -254,4 +254,20 @@ struct OutlineTreeTests {
#expect(rootResult == .newNode(path: [2], caret: 0)) #expect(rootResult == .newNode(path: [2], caret: 0))
#expect(rooted.map(\.text) == ["a", "", ""]) #expect(rooted.map(\.text) == ["a", "", ""])
} }
// #111 (S7): the mixed-content detector behind the open guard.
@Test func `parsesWithLoss flags prose between bullets and stays quiet otherwise`() {
// The exact hazard: prose after the first item would drop on save.
#expect(OutlineTree.parsesWithLoss("- one\nan stray paragraph\n- two"))
// Deep prose counts anywhere after the first item.
#expect(OutlineTree.parsesWithLoss("- a\n - b\n prose under b"))
// Clean canonical outline — no loss.
#expect(!OutlineTree.parsesWithLoss("- one\n- two\n - nested"))
// Preamble is verbatim by design — never a loss.
#expect(!OutlineTree.parsesWithLoss("# Title\n\n- one\n- two"))
// Blank lines between items are formatting, not prose.
#expect(!OutlineTree.parsesWithLoss("- one\n\n- two\n"))
#expect(!OutlineTree.parsesWithLoss(""))
}
} }
+136
View File
@@ -159,3 +159,139 @@ private func makeModelHome() throws -> (PostsModel, URL) {
#expect(model.moveTargets(home: home) == ["essays", "posts"]) #expect(model.moveTargets(home: home) == ["essays", "posts"])
// "posts" exists too (bind created it); a dot-project never shows. // "posts" exists too (bind created it); a dot-project never shows.
} }
// #111 (S7): the mixed-content outline guard — no silent prose loss.
/// A `type: outline` piece whose body parses with dropped prose.
@discardableResult
private func writeMixedOutline(home: URL) throws -> Post {
try PostStore.writeNew(
body: "# Mixed\n\n- one\nA paragraph between bullets.\n- two\n",
type: .outline,
home: home,
)
}
@Test @MainActor func `mixed outline fires the guard and holds the open`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id) // the ask is up
#expect(model.session == nil) // nothing editable while it's up
#expect(model.selectedPostID == post.id)
// The file is untouched — the choice precedes any save.
#expect(try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
.contains("A paragraph between bullets."))
}
@Test @MainActor func `guard prose answer opens prose and never drops`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineInProse(home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
#expect(model.proseOverridePostID == post.id) // routes prose despite type
// A full edit+flush cycle in prose mode: nothing drops.
model.session?.edit("- one\nA paragraph between bullets.\n- two\nedited")
_ = model.session?.flush()
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
#expect(onDisk.contains("edited"))
#expect(onDisk.contains("A paragraph between bullets."))
}
@Test @MainActor func `guard outline answer is explicit consent`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
#expect(model.proseOverridePostID == nil) // outline routing stands
// The consented save drops the prose — as ruled, but only now.
model.session?.edit("- one\n- two")
_ = model.session?.flush()
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
#expect(!onDisk.contains("A paragraph between bullets."))
}
@Test @MainActor func `guard cancel backs out and stays guarded`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.cancelOutlineGuard()
#expect(model.outlineGuardPieceID == nil)
#expect(model.session == nil)
// Still guarded: the next open re-fires the ask, file untouched.
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id)
}
// Audit pins: the guard's lifecycle holes (reselect / displacement).
@Test @MainActor func `reselecting the open guarded piece is a no-op`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home) // consent; disk still mixed
let session = try #require(model.session)
session.edit("- one\n- two\nedited") // dirty; debounce armed
model.select(post.id, home: home) // muscle-memory re-click on the open row
#expect(model.outlineGuardPieceID == nil) // no re-ask over a prior answer
#expect(model.session === session) // the open session survives, dirty state intact
}
@Test @MainActor func `new draft during the ask displaces it and survives`() throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home) // ask up
model.newPost() // ⌘N fires while the sheet is up
#expect(model.outlineGuardPieceID == nil) // the ask died with the displacement
#expect(model.draft != nil)
model.updateDraft("# Keep me\n")
// Answering the (now-gone) ask is inert — the draft survives.
model.openGuardedOutlineInProse(home: home)
model.openGuardedOutlineAsOutline(home: home)
#expect(model.draft != nil)
#expect(model.selectedPostID == nil) // the draft still owns the editor
}
@Test @MainActor func `guard fires from the scan-known type too`() async throws {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
// Wait for the bind rescan so `posts` knows the piece (poll-loop convention).
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.posts.contains(where: { $0.id == post.id }))
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id) // the scan path guards too
}
@Test @MainActor func `clean outline and prose pieces open without the guard`() throws {
let (model, home) = try makeModelHome()
let clean = try PostStore.writeNew(body: "# Clean\n\n- one\n- two\n", type: .outline, home: home)
let prose = try PostStore.writeNew(body: "# Plain\n\nA paragraph.\n", home: home)
model.select(clean.id, home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == clean.id)
model.select(prose.id, home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == prose.id)
}
@@ -0,0 +1,76 @@
# Issue #111 — Build S7: mixed-content outline guard — no silent prose loss
> **Date:** 2026-10-15
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/111 (map #110)
## Goal
A `type: outline` piece whose body has paragraph lines between bullets loses those lines on the next in-app save — the outliner's parse drops non-item lines after the first item and serialize never writes them back. S7 puts a guard at open: warn, offer prose mode (nothing drops; outlines render acceptably in prose via the apex pipeline), and only drop after an explicit choice to open as outline.
## What Was Done
- **`OutlineTree.parsesWithLoss(_:)`** (OutlineTree.swift) — the detector: true when any non-blank line after the first item line isn't an item. Reuses `parseItem` so the detector and the parser can never disagree. Blank lines are formatting, not prose — quiet. Preamble is verbatim by design — never a loss.
- **`PostsModel.select` guard branch** — on open of a `type: outline` piece that parses with loss: ends the old session (flush-first; prose-mode flush can't drop), sets `outlineGuardPieceID`, nils the session, holds the open. The ask presents over an EMPTY editor — nothing can edit, so nothing can normalize on ⌘S, before the choice.
- **`postType(_:)`** — the piece's type from the scan when the list knows it, from frontmatter during the rescan lag (the same window `lastDraftWasOutline` covers for routing).
- **Guard answers** — `openGuardedOutlineInProse(home:)` sets `proseOverridePostID` (routing override, `lastDraftWasOutline`'s exact lifecycle: dies in newPost/newOutline/select/openExternal) and opens; `openGuardedOutlineAsOutline(home:)` opens with outline routing standing (consented drop); `cancelOutlineGuard()` backs out, no session, piece stays guarded on next open.
- **Routing** (PostsPaneView) — session routing adds `session.postID != model.proseOverridePostID`; a held-guard branch renders an inert notice (no editor) while the ask is up.
- **`OutlineGuardSheet`** (WorkspaceView) — third house ask (OriginAsk/NewProject pattern): Open in Prose (default) · Open as Outline · Cancel (binding `set(false)` → `cancelOutlineGuard`; Esc included).
- **Tests** — `parsesWithLoss` pin (6 cases: the hazard, deep prose, clean, preamble, blanks, empty) + 8 model tests (3 audit pins): guard fires + holds + file untouched, prose answer + edit/flush cycle never drops, outline answer = consented drop on save, cancel re-guards on next open, clean pieces open untouched.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Guard in `select`, not EditorSession/PostStore | `select` is the ONE open path (library, archive pane, restore, import) — one choke point; the ruling places the choice at load/route time where the type decision lives |
| Detector = non-blank non-item line after first item, via `parseItem` | Shares the parser's exact item definition — no drift between "would drop" and "drops"; blank lines normalize quietly everywhere already |
| Ask over an EMPTY editor (session nil'd) | The ticket's flush discipline: a piece being edited can't silently normalize on ⌘S — there is no session to ⌘S into while the ask is up |
| `proseOverridePostID` routing override with `lastDraftWasOutline`'s lifecycle | The piece's frontmatter still says `type: outline`; without the override the rescan-lagged routing would mount the outliner over the prose answer. Same clear-sites as the #109 afterglow |
| No write-path change (overwrite unchanged) | Loss is exclusively parse→serialize in the outliner surface; prose flushes write text verbatim — touching overwrite would guard nothing and touch every save |
| No `openExternal` guard | Imported externals are force-stamped `type: post` (#95 merge) — they route prose; an outline-drafted piece is authored in the surface |
| Guard machinery in a file-scope `extension PostsModel` | Kept the class body under swiftlint's type_body_length error threshold; same file, same actor |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| SwiftFormat/SwiftLint failures after hand-edits | Multi-line `if` guard-condition brace placement; long sheet copy; class body pushed past 350 lines | Extracted `isGuardedOutline` helper, split sheet text into two `Text`s, moved guard members into a file-scope extension |
| Extension accidentally nested inside the class (build error: declaration only valid at file scope) | A scripted block-move spliced it mid-class | Programmatic repair: cut the orphaned block, appended the extension after the class's closing brace |
| `-only-testing:MuseionTests/PostsModelTests` matched zero tests | PostsModelTests is free functions, not a named suite | Verified via xcresult enumeration on the full MuseionTests run: 176/176 passed, all 6 new tests present |
| xcresult `get test-results tests` returned an empty node tree | Summary-only shape for Swift Testing in this Xcode | Enumerated via `get test-results summary` counts + grep of test names |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/OutlineTree.swift` | + `parsesWithLoss(_:)` static detector |
| `Museion/PostsModel.swift` | + `outlineGuardPieceID`/`proseOverridePostID` state, guard branch in `select`, guard extension (postType, answers, openUnguarded), override lifecycle clears |
| `Museion/PostsPaneView.swift` | Routing: prose override check + held-guard inert branch |
| `Museion/WorkspaceView.swift` | + `outlineGuardBinding` + `OutlineGuardSheet` (house ask pattern) |
| `MuseionTests/OutlineTreeTests.swift` | + `parsesWithLoss` pin |
| `MuseionTests/PostsModelTests.swift` | + 8 guard lifecycle tests (5 + 3 audit pins) |
## Audit Round (finish-audit, same day)
Three parallel fresh-context reviewers (ponytail-review, security-review, review). Accepted findings, all fixed with pinning tests:
| Finding | Fix |
|---------|-----|
| HIGH: same-id reselect re-fired the guard over an already-open piece; session nil'd without teardown — armed debounce could flush prose-dropped text mid-ask (the exact loss the guard exists to prevent) | `select` returns early when the open piece is reselected (reselect was already a no-op pre-guard; the guard must not break that) |
| MEDIUM: menu commands during the ask (⌘N, drag-drop) left the hold live; answering destroyed the just-created draft/guest | `outlineGuardPieceID = nil` in `newPost`/`newOutline`/`openExternal`; `openUnguarded` clears it too (select's tail now routes through it — one open body) |
| LOW: Cancel left the row selected over an empty editor | `cancelOutlineGuard` clears `selectedPostID` when no session is up |
| ponytail: `openUnguarded` duplicated select's tail; `postType`+`readBody` read the file twice; test helper reinvented `writeNew`; placeholder branch had an always-true condition | select's tail calls `openUnguarded`; `isGuardedOutline` does ONE disk read deriving type + body (`splitFrontmatter`); helper is one `writeNew` call; condition is `!= nil` |
Deferred: remembered per-piece prose preference (per-open consent is the ruled safe direction); main-actor guard reads (existing house posture, ponytail-marked).
Both lifecycle pins verified to bite: reverting the two fixes fails exactly `reselecting the open guarded piece is a no-op` and `new draft during the ask displaces it and survives`; restored → 179/179 green.
## Open Items & Next Steps
- [x] S7 landed; map #110's next frontier tickets: P1 (#113) → S6 (#112), S4 (#114), S5 (#115)
- [ ] Convert to Post (#114) will give guarded pieces a structural way out; the ask's copy already points at it
- None — no known tech debt introduced
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index --> <!-- write-log: full-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 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 | | 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 |
| 2026-10-13 | issue | [20261013-issue108-library-ui-archive-audits_log.md](20261013-issue108-library-ui-archive-audits_log.md) | #108 variant-B library + Archive pane + commands, two audit rounds, fold corrected, 144 tests green | | 2026-10-13 | issue | [20261013-issue108-library-ui-archive-audits_log.md](20261013-issue108-library-ui-archive-audits_log.md) | #108 variant-B library + Archive pane + commands, two audit rounds, fold corrected, 144 tests green |
| 2026-10-13 | issue | [20261013-issue107-storage-substrate-projects-archive_log.md](20261013-issue107-storage-substrate-projects-archive_log.md) | #107 S1: pieces re-rooted to projects/ + archive/, global slugs, type frontmatter; audit dedupe fix | | 2026-10-13 | issue | [20261013-issue107-storage-substrate-projects-archive_log.md](20261013-issue107-storage-substrate-projects-archive_log.md) | #107 S1: pieces re-rooted to projects/ + archive/, global slugs, type frontmatter; audit dedupe fix |