# M1: Post lifecycle (#18) > **Date:** 2026-10-03 > **Type:** issue > **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/18 ## Goal Run the #18 build session: turn the four map decisions (#59 first-save frontmatter, #60 rename = retitle + move, #61 FSEvents refresh, #62 New Post backing editor) into working code meeting the S1.1 acceptance criteria — lazy folder, slug Post ID with collision suffixes, rename-moves-folder, Trash delete, Finder-verifiable round-trips. ## What Was Done - `PostStore.swift` (new, nonisolated) — write side: shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:in:excluding:)` with case-insensitive collision suffixes via enumerated lowercase set, `writeNew` (lazy folder + #59 flat stamp), `overwrite` (preserves pass_state/origin, normalizes bare posts), `rename` (retitle + move, file stays `post.md`), `trash` (`FileManager.trashItem`), `readBody`, `splitFrontmatter`. - `PostsModel.swift` (new, @MainActor @Observable, app-scoped via `AppGateState.posts`) — `PostsWatcher`: recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency) on `posts/`; rescan off-main via `Post.scan`; `bind(home:)` creates `posts/` if missing + rebinds on repoint; `shutdown()` on quit; selection/draft state; lifecycle ops set `lastError`, never alert. - `PostsPaneView.swift` — New Post button in `PaneHeader` trailing slot (export `.pane-head .icon-btn`), `EditorStub` (plain `TextEditor`, ⌘S = first write/save, typed text local `@State` keyed by `.id()`), context menu (Rename…/Move to Trash), `RenamePostSheet` (asks Title, not slug), error footer. - `WorkspaceView.swift` — `PaneHeader` generic; hands `gate.posts` into the pane. - `MuseionApp.swift` — `AppGateState.posts`; `posts.shutdown()` beside mentor teardown on quit. - `PostLibrary.swift` — `trimmed()` widened fileprivate→internal (PostStore uses it). - Tests: `PostStoreTests.swift` — 17 tests: slug table, first-write stamp round-trip through `Post.scan`, untitled fallback, collisions, rename (heading replace, non-heading insert, same-slug retitle-only, collision -2), vanished-post throw, trash, overwrite preservation + bare normalization, readBody, blocked-posts failure, fresh-listing collision routing. - Two review rounds: mid-build two-axis review (standards+spec) and finish-audit fanout (ponytail/security/general). ## Decisions & Rationale | Decision | Rationale | |----------|-----------| | Real FSEvents stream, not a dir-FD DispatchSource | #61 pins FSEvents; a dir-FD source only sees direct children — nested `posts//post.md` edits from Finder never fire. File-events flag makes the stream recursive. | | FSEvents latency IS the debounce (0.5 s) | The stream coalesces bursts within its latency window; a Swift-side debounce on top added a cancel-race (starvation under churn) and ~10 lines for nothing. One window, one mechanism. | | `bind` creates `posts/` if missing | FSEvents on a missing path is unreliable at picking it up later; the AC's lazy rule is about post folders, never this root. External creation of the first post now surfaces. | | `writeNew` existence guard + partial-failure cleanup | Audit MEDIUM: slug enumeration error or a raced folder could clobber another post's post.md (`createDirectory(intermediates:)` succeeds on existing). Guard throws; empty slug folders don't strand (they'd push retries to -2). | | `overwrite` throws on vanished post | Audit: saving after Finder-delete within the watcher window resurrected the post with reset origin — violates CONTEXT.md immutability. `writeNew` is the only creator. | | Rename inserts `# Title` above non-heading first lines | Audit MEDIUM: replacing the first line destroyed content when a bare corpus post had no heading. | | Selecting a post abandons the draft | Audit HIGH: a draft hijacked the editor (checked before selection) with no discard affordance — dead end for every changed mind. | | Case-insensitive collisions via enumeration + lowercase compare | `fileExists` rides the volume's case sensitivity; #60 pins case-insensitive regardless of disk format. | | Editor stub owns typed text as local `@State`, `.id()` per post | A Binding whose get re-read disk wiped in-progress edits on every rescan; identity swap reloads on selection change, disk writes only on ⌘S. | | Watcher teardown via `shutdown()` on quit (main actor) | FSEvents stop/invalidate should run on the scheduling thread; deinit of a @MainActor-held object may run elsewhere. Same pattern as the mentor bridge. | ## Gotchas & Fixes | Problem | Root Cause | Fix | |---------|------------|-----| | Watcher never started (dead code) | `bind` pre-assigned `watchedHome`; `startWatching`'s same-home guard always returned | `startWatching` owns the assignment | | `tea`-side: none — local only | — | — | | `FSEventStreamCreate` literal type errors | `kFSEventStreamEventIdSinceNow` is UInt (needs UInt64 cast); flags constant needs `FSEventStreamCreateFlags(...)` | explicit type constructions | | SwiftUI buttons unaddressable via AX names | `Button { Image }` has no AX title | `accessibilityLabel` on New Post; AXPress by index/description for the rest | | AppleScript `keystroke "a\nb"` types literal nothing for `\n` | AppleScript strings don't interpret `\n` | cosmetic only (one-line slug in smoke test) | | Smoke test wrote to the Obsidian IdeaVault | Persisted `museionHome` override from user testing | artifacts deleted; override removed (`plutil -remove` + `killall cfprefsd` — `defaults delete` from an agent shell silently fails, known cfprefsd context trap); Home back to `~/Documents/Museion` | | `guard let draft` shadowing made `draft = nil` a compile error | local constant shadows property | `self.draft = nil` | | `#expect(throws:)` with `CocoaError.fileReadNoSuchFile` | `.Code` isn't `Error` | wrap: `CocoaError(.fileReadNoSuchFile)` | ## Files Changed | File | Change Summary | |------|----------------| | `Museion/PostStore.swift` | New — write side (slug, stamp, rename, trash, guards) | | `Museion/PostsModel.swift` | New — FSEvents watcher, rescan, selection/draft, ops | | `Museion/PostsPaneView.swift` | New Post button, context menu, rename sheet, EditorStub | | `Museion/WorkspaceView.swift` | `PaneHeader` trailing slot; model handoff | | `Museion/MuseionApp.swift` | `AppGateState.posts` + quit teardown | | `Museion/PostLibrary.swift` | `trimmed()` visibility widen | | `MuseionTests/PostStoreTests.swift` | New — 17 tests | | `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass | ## Verification - Build: `xcodebuild … build` → BUILD SUCCEEDED - Tests: full suite → TEST SUCCEEDED, **75/75** (58 pre-existing + 17 new) - Lint: SwiftLint + SwiftFormat clean on all changed files - Live GUI smoke (macos-ui-automation): gate dismissed via AX → New Post → typed → ⌘S → folder + exact #59 stamp on disk → row appears; **external shell-side create appeared in the list** (watcher proven live); row click loads body in editor; smoke artifacts removed from the (user's test) Home - GitNexus re-indexed; `detect-changes` risk HIGH = the feature's own 37-symbol footprint, pre-edit blast radius confirmed low by text search ## Open Items & Next Steps - [ ] #19 editor core replaces `EditorStub` in place (lifecycle machinery below the view survives; async body loading lands there — the stub's sync `readBody` carries a ponytail note) - [ ] PostsModel itself untested (selection/draft state machine) — candidates for #19's test pass - [ ] Rename non-atomic (retitle persists if the move fails; surfaces via lastError) — acceptable, revisit with #19's save pipeline --- *Log written by write-log skill*