feat(workspace): land Post lifecycle (S1.1)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Posts become writable end to end per the #18 map decisions: New Post holds an in-memory draft (folder appears only on first save), first save stamps the flat frontmatter block the #17 reader already parses (pass_state First Draft, origin writer, immutable after stamping), and the Post ID is the Title slug with case-insensitive collision suffixes. Explicit Rename retitles the # Title line and moves the folder (post.md stays); Delete goes to Trash. A recursive FSEvents stream keeps the list mirroring posts/ — external Finder edits included. Editor is a deliberate TextEditor stub; #19's TextKit2 editor replaces it in place while the lifecycle machinery below the view survives the swap. Two review rounds (standards/spec + finish-audit fanout) fixed: watcher start-order bug, writeNew clobber race, overwrite resurrecting vanished posts with reset origin, rename destroying non-heading first lines, draft hijacking the editor, debounce starvation under churn. Tests: 75/75 (17 new). Closes #18.
This commit is contained in:
1 parent
de76a50cc6
commit
530f852f75
13 files changed
+871
-27
No files matched your search
@@ -178,6 +178,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-03 | [20261003-issue18-post-lifecycle_log.md](docs/devlog/20261003-issue18-post-lifecycle_log.md) |
|
||||
| 2026-10-01 | [20261001-issue17-home-posts-list_log.md](docs/devlog/20261001-issue17-home-posts-list_log.md) |
|
||||
| 2026-10-01 | [20261001-issue55-verdict-substrate-adr-0010_log.md](docs/devlog/20261001-issue55-verdict-substrate-adr-0010_log.md) |
|
||||
| 2026-09-25 | [20260925-issue50-profile-backup-s2-6_log.md](docs/devlog/20260925-issue50-profile-backup-s2-6_log.md) |
|
||||
|
||||
@@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **workspace:** M1 Post lifecycle (PRD S1.1) — Posts are now writable end to end: New Post holds an in-memory draft (no folder until first save), ⌘S lazily materializes `posts/<slug>/post.md` stamped with flat frontmatter (`pass_state: First Draft`, `origin: writer`), the slug is the Title's (lowercased, diacritic-folded, CJK-keeping) form with case-insensitive `-2`/`-3` collision suffixes, Explicit Rename retitles the `# Title` line and moves the folder (file stays `post.md`), and Delete moves the folder to the Trash; a recursive FSEvents watcher keeps the list mirroring `posts/` (external Finder edits included), and a plain-TextEditor stub stands in for the S1.2 editor (issue #18)
|
||||
- **workspace:** M1 Home & Posts list (PRD S1.1) — the post-gate main surface is now the workspace shell from the design contract: nav rail (Posts, Sessions, Learnings, Settings), a Posts pane that mirrors the Museion Home's `posts/` folder on disk (Pass State groups, origin meta, empty state, lazy folders skipped), a Settings pane where the Home can be repointed (repoint-only — Museion never moves content; NSOpenPanel picker, UserDefaults persistence, default `~/Documents/Museion`), and placeholder panes for Sessions/Learnings until their milestones; the M0 mentor pane becomes the workspace's fourth column (issue #17)
|
||||
|
||||
- **backup:** S2.6 daily profile backup — on launch, once per 24 h and only while the engine is idle (gateway.pid liveness + `ps` scan), Museion snapshots `~/.hermes/profiles/museion/` into a timestamped folder under `~/Library/Application Support/Museion/Backups/` (credentials included, logs/caches/locks excluded, last 7 kept); restore is manual Finder copy-back — Help → Open Backup Folder, `RESTORE.md` beside the snapshots (issue #50)
|
||||
|
||||
+6
-3
@@ -17,12 +17,15 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's `state.json` (see below).
|
||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
|
||||
|
||||
## Workspace shell (M1, #17 / 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. Light-only — the export defines 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.
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor placeholder until #19–#21, mentor column (`MentorPaneView`, fixed 356). Selecting a post sets `selectedPostID` (editor shows its title; no editing yet).
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts/<id>/post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; 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 — corpus posts ship bare; write-side key format pinned by #18). Read-only — lifecycle is #18. Scan runs off-main via `Task.detached` in PostsPaneView (big Homes must not freeze the UI).
|
||||
- `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, mentor column (`MentorPaneView`, fixed 356). Selecting a post renders it in the editor stub; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`).
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts/<id>/post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; 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): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on `posts/`, rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan); `bind(home:)` from `.task(id: home)` creates `posts/` if missing + rebinds on repoint; `shutdown()` tears the watcher down on quit (main actor); selecting a post abandons an unsaved draft; lifecycle ops (`saveDraft`/`saveSelected`/`rename`/`trash`) set `lastError` on failure, never alert.
|
||||
- Editor stub (`EditorStub` in PostsPaneView, #62): plain `TextEditor`, ⌘S triggers save (first write fires lazy folder + slug + stamp); typed text is local `@State` keyed by `.id(post.id)`/`.id("draft")` — disk read at init, write on save only. Explicitly throwaway at the view layer: #19's TextKit2 editor replaces it in place; the lifecycle machinery below the view survives the swap. Rename sheet asks the new Title; delete via context menu → Trash.
|
||||
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI.
|
||||
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
|
||||
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
|
||||
|
||||
@@ -22,6 +22,8 @@ final class AppGateState {
|
||||
let backup = BackupModel()
|
||||
/// #14: the app-scoped mentor bridge — the pane renders it; quit tears it down.
|
||||
let mentor = MentorSessionModel()
|
||||
/// #18: the app-scoped Posts state — FSEvents watcher + lifecycle ops.
|
||||
let posts = PostsModel()
|
||||
/// #17: the Museion Home — repoint-only (ADR-0004). Defaults to
|
||||
/// `~/Documents/Museion`; UserDefaults is the persistence floor: a Home is
|
||||
/// a plain folder, nothing app-owned to put in a database. Non-file URLs
|
||||
@@ -59,6 +61,7 @@ struct MuseionApp: App {
|
||||
// focus loss, which would kill the engine on every app switch.
|
||||
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in
|
||||
gate.mentor.shutdown()
|
||||
gate.posts.shutdown()
|
||||
}
|
||||
}
|
||||
Window("About \(AppMetadata.name)", id: "about") {
|
||||
|
||||
@@ -102,7 +102,7 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated extension Substring {
|
||||
nonisolated extension Substring {
|
||||
func trimmed() -> String {
|
||||
trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//
|
||||
// PostStore.swift
|
||||
// Museion
|
||||
//
|
||||
// #18 (S1.1): the write side of the Post lifecycle — slug naming, lazy folder
|
||||
// materialization on first write, frontmatter stamping (#59), Explicit Rename
|
||||
// = retitle + move (#60), Trash delete. Pure disk operations, no UI state.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Write-side Post lifecycle (#18 map decisions #59/#60). One canonical write
|
||||
/// path: every file that leaves here carries the flat frontmatter block the
|
||||
/// #17 reader already parses.
|
||||
nonisolated enum PostStore {
|
||||
/// The shared slug function (#60): lowercase, diacritic-fold, strip
|
||||
/// punctuation, whitespace runs → single hyphens, keep CJK, cap 80.
|
||||
/// A slugless title (blank, punctuation-only) is `untitled` (CONTEXT.md).
|
||||
static func slug(from title: String) -> String {
|
||||
let folded = title
|
||||
.folding(options: .diacriticInsensitive, locale: Locale(identifier: "en_US_POSIX"))
|
||||
.lowercased()
|
||||
var result = ""
|
||||
var lastWasHyphen = true // swallows leading hyphens
|
||||
for scalar in folded.unicodeScalars {
|
||||
if CharacterSet.whitespacesAndNewlines.contains(scalar) {
|
||||
if !lastWasHyphen {
|
||||
result.append("-"); lastWasHyphen = true
|
||||
}
|
||||
} else if CharacterSet.alphanumerics.contains(scalar) {
|
||||
result.unicodeScalars.append(scalar)
|
||||
lastWasHyphen = false
|
||||
}
|
||||
// Everything else (punctuation, symbols) is dropped.
|
||||
}
|
||||
result = String(result.prefix(80))
|
||||
while result.hasSuffix("-") {
|
||||
result.removeLast()
|
||||
}
|
||||
return result.isEmpty ? "untitled" : result
|
||||
}
|
||||
|
||||
/// First free slug for a title: base slug, then `-2`, `-3`… (#60).
|
||||
/// Case-insensitive existence check (#60): enumerates `posts/` and
|
||||
/// compares lowercased — independent of the volume's case sensitivity.
|
||||
/// `excluding` skips a folder (the renamer's own, still present).
|
||||
static func availableSlug(for title: String, in postsRoot: URL, excluding ownID: String? = nil) -> String {
|
||||
let taken = Set(
|
||||
((try? FileManager.default.contentsOfDirectory(atPath: postsRoot.path)) ?? [])
|
||||
.map { $0.lowercased() },
|
||||
)
|
||||
let base = slug(from: title) // slug() is already lowercase
|
||||
if !taken.contains(base) || base == ownID?.lowercased() {
|
||||
return base
|
||||
}
|
||||
var suffix = 2
|
||||
while taken.contains("\(base)-\(suffix)") {
|
||||
suffix += 1
|
||||
}
|
||||
return "\(base)-\(suffix)"
|
||||
}
|
||||
|
||||
/// First write (#62): lazily materialize `posts/<slug>/post.md` with the
|
||||
/// #59 block stamped. Pass State First Draft, origin writer — the only
|
||||
/// values #18 writes; the folder appears here, never on New Post.
|
||||
static func writeNew(body: String, home: URL) throws -> Post {
|
||||
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: postsRoot, withIntermediateDirectories: true)
|
||||
let title = Post.title(of: body)
|
||||
let id = availableSlug(for: title, in: postsRoot)
|
||||
let dir = postsRoot.appendingPathComponent(id, isDirectory: true)
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
// TOCTOU guard (audit): a folder appearing between slug pick and write
|
||||
// must fail loudly, never clobber another post's content.
|
||||
guard !FileManager.default.fileExists(atPath: fileURL.path) else {
|
||||
throw CocoaError(.fileWriteFileExists)
|
||||
}
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try stamped(body: body, passState: .firstDraft, origin: .writer)
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
// Don't strand an empty slug folder on partial failure (it would
|
||||
// occupy the slug and push the retry to -2).
|
||||
if !FileManager.default.fileExists(atPath: fileURL.path) {
|
||||
try? FileManager.default.removeItem(at: dir)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
return Post(id: id, title: title, passState: .firstDraft, origin: .writer)
|
||||
}
|
||||
|
||||
/// Save an existing Post: body-only text in, file normalized out. The
|
||||
/// file's present `pass_state`/`origin` are preserved (origin immutable,
|
||||
/// CONTEXT.md; bare corpus posts normalize on save, #59). A vanished
|
||||
/// post throws — `writeNew` is the only creator; saving must never
|
||||
/// resurrect a deleted post with reset metadata.
|
||||
static func overwrite(id: String, body: String, home: URL) throws {
|
||||
let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
|
||||
guard let existing = try? String(contentsOf: fileURL, encoding: .utf8) else {
|
||||
throw CocoaError(.fileReadNoSuchFile)
|
||||
}
|
||||
let matter = Post.frontmatter(of: existing)
|
||||
let passState = Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft
|
||||
let origin = Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer
|
||||
try stamped(body: body, passState: passState, origin: origin)
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
/// Body text (frontmatter stripped) for editing; nil when unreadable.
|
||||
/// Bare corpus posts return whole — they normalize on save (#59).
|
||||
static func readBody(id: String, home: URL) -> String? {
|
||||
let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return nil }
|
||||
return splitFrontmatter(text).body
|
||||
}
|
||||
|
||||
/// Explicit Rename (#60): rewrite the `# Title` line as the first
|
||||
/// non-empty body line, then move the folder to the new slug. The file
|
||||
/// stays `post.md`; a title that slugs to the current id only retitles.
|
||||
static func rename(_ post: Post, to title: String, home: URL) throws -> Post {
|
||||
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
|
||||
let dir = postsRoot.appendingPathComponent(post.id, isDirectory: true)
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
let text = try String(contentsOf: fileURL, encoding: .utf8)
|
||||
let (block, body) = splitFrontmatter(text)
|
||||
try (block + replacingTitleLine(of: body, with: "# \(title)"))
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
|
||||
// availableSlug excludes our own (still-present) folder: a retitle
|
||||
// whose slug matches the current id (any case) keeps the clean name
|
||||
// (no -2 against ourselves); a genuine collision lands on -2 (#60).
|
||||
let newID = availableSlug(for: title, in: postsRoot, excluding: post.id)
|
||||
guard newID != post.id else {
|
||||
return Post(id: post.id, title: title, passState: post.passState, origin: post.origin)
|
||||
}
|
||||
try FileManager.default.moveItem(at: dir, to: postsRoot.appendingPathComponent(newID, isDirectory: true))
|
||||
return Post(id: newID, title: title, passState: post.passState, origin: post.origin)
|
||||
}
|
||||
|
||||
/// Delete = move the Post folder to the Trash (recoverable in Finder) —
|
||||
/// never permanent removal (#18 AC).
|
||||
static func trash(_ post: Post, home: URL) throws {
|
||||
var trashed: NSURL?
|
||||
try FileManager.default.trashItem(
|
||||
at: home.appendingPathComponent("posts/\(post.id)", isDirectory: true),
|
||||
resultingItemURL: &trashed,
|
||||
)
|
||||
}
|
||||
|
||||
/// The #59 v1 block — flat keys, the exact shape the #17 reader parses.
|
||||
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin) -> String {
|
||||
"---\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
|
||||
}
|
||||
|
||||
/// Splits a file into its verbatim frontmatter block (with both `---`
|
||||
/// lines) and the body; no block → ("", whole text).
|
||||
static func splitFrontmatter(_ text: String) -> (block: String, body: String) {
|
||||
let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
|
||||
guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }),
|
||||
all[open].trimmed() == "---",
|
||||
let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" })
|
||||
else { return ("", text) }
|
||||
let block = all[open ... close].joined(separator: "\n") + "\n"
|
||||
return (block, all[(close + 1)...].joined(separator: "\n"))
|
||||
}
|
||||
|
||||
/// Replace the body's Title heading with `line`; a body whose first
|
||||
/// non-empty line is NOT a heading keeps that line (it's content) and
|
||||
/// gets the heading inserted above it. An empty body becomes just `line`.
|
||||
private static func replacingTitleLine(of body: String, with line: String) -> String {
|
||||
var lines = body.split(separator: "\n", omittingEmptySubsequences: false)
|
||||
if let titleIndex = lines.firstIndex(where: { !$0.trimmed().isEmpty }) {
|
||||
if lines[titleIndex].trimmed().hasPrefix("#") {
|
||||
lines[titleIndex] = Substring(line)
|
||||
} else {
|
||||
lines.insert(Substring(line), at: titleIndex)
|
||||
}
|
||||
} else {
|
||||
lines = [Substring(line)]
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//
|
||||
// PostsModel.swift
|
||||
// Museion
|
||||
//
|
||||
// #18 (S1.1): the Posts pane's write side — FSEvents watcher on posts/ with
|
||||
// a ~0.5 s debounced rescan (#61), selection, and the New Post draft
|
||||
// lifecycle (#62). Own ops route through the same rescan: one path.
|
||||
//
|
||||
|
||||
import CoreServices
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// The New Post draft: body text only, no folder until first save (#62).
|
||||
struct PostDraft {
|
||||
var text = "# Untitled\n\n"
|
||||
}
|
||||
|
||||
/// Recursive FSEvents stream on one directory (#61): file-level events, so
|
||||
/// nested `posts/<id>/post.md` edits from Finder fire too — a plain dir-FD
|
||||
/// dispatch source only sees direct children and misses them.
|
||||
final nonisolated class PostsWatcher: @unchecked Sendable {
|
||||
/// Fired on the main actor when anything under the watched path changes.
|
||||
var onEvent: (@MainActor @Sendable () -> Void)?
|
||||
|
||||
private var stream: FSEventStreamRef?
|
||||
|
||||
func start(url: URL) {
|
||||
stop()
|
||||
var context = FSEventStreamContext(
|
||||
version: 0,
|
||||
info: Unmanaged.passUnretained(self).toOpaque(),
|
||||
retain: nil,
|
||||
release: nil,
|
||||
copyDescription: nil,
|
||||
)
|
||||
// C function pointer — no captures; `self` rides the info pointer.
|
||||
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
|
||||
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
|
||||
Task { @MainActor in watcher.onEvent?() }
|
||||
}
|
||||
guard let stream = FSEventStreamCreate(
|
||||
kCFAllocatorDefault,
|
||||
callback,
|
||||
&context,
|
||||
[url.path] as CFArray,
|
||||
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
|
||||
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
|
||||
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
|
||||
) else { return }
|
||||
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
||||
FSEventStreamStart(stream)
|
||||
self.stream = stream
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard let stream else { return }
|
||||
FSEventStreamStop(stream)
|
||||
FSEventStreamInvalidate(stream)
|
||||
FSEventStreamRelease(stream)
|
||||
self.stream = nil
|
||||
}
|
||||
|
||||
deinit { stop() }
|
||||
}
|
||||
|
||||
/// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern).
|
||||
/// The watcher runs while the workspace is open (app-scoped, #61).
|
||||
@MainActor
|
||||
@Observable
|
||||
final class PostsModel {
|
||||
/// The scanned, title-sorted list — mirrors `posts/` at all times.
|
||||
private(set) var posts: [Post] = []
|
||||
|
||||
/// The selected Post's id; nil = nothing selected (empty editor).
|
||||
private(set) var selectedPostID: String?
|
||||
|
||||
/// The in-memory draft for New Post (#62): no folder until first save.
|
||||
private(set) var draft: PostDraft?
|
||||
|
||||
/// Last failed-op message surfaced in the editor (nil = clean).
|
||||
private(set) var lastError: String?
|
||||
|
||||
/// Home the watcher is bound to; also the rescan target.
|
||||
private var watchedHome: URL?
|
||||
private var watcher = PostsWatcher()
|
||||
|
||||
/// Bind a Home: ensure `posts/` exists (FSEvents on a missing path is
|
||||
/// unreliable; the AC's lazy rule is about post folders, not this root),
|
||||
/// initial scan + start (or restart) the watcher. Called from
|
||||
/// `.task(id: home)` — re-fires on Home repoint.
|
||||
func bind(home: URL) {
|
||||
startWatching(home: home)
|
||||
Task { await rescan() }
|
||||
}
|
||||
|
||||
// MARK: Watcher (#61)
|
||||
|
||||
private func startWatching(home: URL) {
|
||||
guard watchedHome != home else { return }
|
||||
watchedHome = home
|
||||
try? FileManager.default.createDirectory(
|
||||
at: home.appendingPathComponent("posts", isDirectory: true),
|
||||
withIntermediateDirectories: true,
|
||||
)
|
||||
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
|
||||
watcher.start(url: home.appendingPathComponent("posts", isDirectory: true))
|
||||
}
|
||||
|
||||
/// Off-main scan; keeps selection valid across the fresh refresh.
|
||||
/// FSEvents already coalesces bursts within its 0.5 s latency window —
|
||||
/// no second debounce on top.
|
||||
private func rescan() async {
|
||||
guard let home = watchedHome else { return }
|
||||
let scanned = await Task.detached(priority: .userInitiated) { Post.scan(home: home) }.value
|
||||
guard !Task.isCancelled else { return }
|
||||
posts = scanned
|
||||
if let id = selectedPostID, !posts.contains(where: { $0.id == id }) {
|
||||
selectedPostID = nil // the post vanished (deleted in Finder or here)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Own ops (route through the same rescan, #61)
|
||||
|
||||
// ponytail: the PostStore calls here run on MainActor — small single-file
|
||||
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
|
||||
// them in Task.detached like rescan.
|
||||
|
||||
/// Tear the watcher down on the main actor (its scheduling thread) —
|
||||
/// deinit of a @MainActor-held object may run elsewhere.
|
||||
func shutdown() {
|
||||
watcher.stop()
|
||||
}
|
||||
|
||||
/// New Post (#62): fresh in-memory draft, no folder, editor takes it.
|
||||
func newPost() {
|
||||
draft = PostDraft()
|
||||
selectedPostID = nil
|
||||
}
|
||||
|
||||
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
|
||||
/// here. Rescans immediately (the watcher would too, after its window).
|
||||
func saveDraft(home: URL) {
|
||||
guard let draft else { return }
|
||||
do {
|
||||
let post = try PostStore.writeNew(body: draft.text, home: home)
|
||||
self.draft = nil
|
||||
selectedPostID = post.id
|
||||
lastError = nil
|
||||
Task { await rescan() }
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// Save an edited body for the selected post (preserves its frontmatter).
|
||||
func saveSelected(body: String, home: URL) {
|
||||
guard let id = selectedPostID else { return }
|
||||
do {
|
||||
try PostStore.overwrite(id: id, body: body, home: home)
|
||||
lastError = nil
|
||||
Task { await rescan() }
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// Select a Post; selecting anything abandons an unsaved draft (the
|
||||
/// draft otherwise hijacks the editor — its only exits are save or
|
||||
/// selecting away).
|
||||
func select(_ id: String) {
|
||||
draft = nil
|
||||
selectedPostID = id
|
||||
}
|
||||
|
||||
/// Draft typing from the editor stub (private(set) barrier).
|
||||
func updateDraft(_ text: String) {
|
||||
draft?.text = text
|
||||
}
|
||||
|
||||
/// Explicit Rename = retitle + move (#60). Sets lastError on failure.
|
||||
func rename(_ post: Post, to title: String, home: URL) {
|
||||
do {
|
||||
let moved = try PostStore.rename(post, to: title, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = moved.id
|
||||
}
|
||||
lastError = nil
|
||||
Task { await rescan() }
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
|
||||
/// was the post.
|
||||
func trash(_ post: Post, home: URL) {
|
||||
do {
|
||||
try PostStore.trash(post, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = nil
|
||||
}
|
||||
lastError = nil
|
||||
Task { await rescan() }
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
+161
-21
@@ -3,7 +3,8 @@
|
||||
// Museion
|
||||
//
|
||||
// #17 (S1.1): the Posts pane — library column mirroring the Home's posts/
|
||||
// on disk, editor placeholder until #19–#21, mentor column (#14).
|
||||
// on disk. #18: lifecycle — New Post draft, ⌘S first-write/save, rename,
|
||||
// trash; TextEditor stub until #19–#21, mentor column (#14).
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
@@ -15,11 +16,12 @@ struct PostsPaneView: View {
|
||||
/// #14: the app-scoped mentor model + the gate's winning binary (no re-probe).
|
||||
var mentor: MentorSessionModel
|
||||
var mentorBinaryPath: String?
|
||||
/// #18: app-scoped Posts state (watcher + lifecycle ops).
|
||||
var model: PostsModel
|
||||
/// Width budget after the rail — drives column collapse (export media queries:
|
||||
/// library hides ≤1100, mentor hides ≤920).
|
||||
var availableWidth: CGFloat
|
||||
@State private var posts: [Post] = []
|
||||
@State private var selectedPostID: String?
|
||||
@State private var renamingPost: Post?
|
||||
|
||||
private var showsLibrary: Bool {
|
||||
availableWidth >= 1100 - DesignTokens.railWidth
|
||||
@@ -35,15 +37,20 @@ struct PostsPaneView: View {
|
||||
libraryColumn
|
||||
paneBorder
|
||||
}
|
||||
editorPlaceholder
|
||||
editorColumn
|
||||
if showsMentor {
|
||||
paneBorder
|
||||
mentorColumn
|
||||
}
|
||||
}
|
||||
.task(id: home) {
|
||||
// Scan off-main: .task inherits MainActor; a big Home must not freeze the UI.
|
||||
posts = await Task.detached(priority: .userInitiated) { Post.scan(home: home) }.value
|
||||
// Bind: initial off-main scan + (re)start the FSEvents watcher (#61).
|
||||
model.bind(home: home)
|
||||
}
|
||||
.sheet(item: $renamingPost) { post in
|
||||
RenamePostSheet(post: post) { title in
|
||||
model.rename(post, to: title, home: home)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,15 +64,24 @@ struct PostsPaneView: View {
|
||||
|
||||
private var libraryColumn: some View {
|
||||
VStack(spacing: 0) {
|
||||
// New Post arrives with #18 (Post lifecycle: lazy folder + slug).
|
||||
PaneHeader(title: "Posts")
|
||||
if posts.isEmpty {
|
||||
PaneHeader(title: "Posts") {
|
||||
Button {
|
||||
model.newPost()
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.help("New Post")
|
||||
.accessibilityLabel("New Post")
|
||||
}
|
||||
if model.posts.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
ForEach(Post.PassState.allCases, id: \.self) { state in
|
||||
let grouped = posts.filter { $0.passState == state }
|
||||
let grouped = model.posts.filter { $0.passState == state }
|
||||
if !grouped.isEmpty {
|
||||
Text(state.rawValue.uppercased())
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
@@ -75,8 +91,14 @@ struct PostsPaneView: View {
|
||||
.padding(.top, 18)
|
||||
.padding(.bottom, 7)
|
||||
ForEach(grouped) { post in
|
||||
PostRow(post: post, selected: post.id == selectedPostID) {
|
||||
selectedPostID = post.id
|
||||
PostRow(post: post, selected: post.id == model.selectedPostID) {
|
||||
model.select(post.id)
|
||||
}
|
||||
.contextMenu {
|
||||
Button("Rename…") { renamingPost = post }
|
||||
Button("Move to Trash", role: .destructive) {
|
||||
model.trash(post, home: home)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,17 +124,46 @@ struct PostsPaneView: View {
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
// MARK: Editor + mentor columns
|
||||
// MARK: Editor column (stub until #19)
|
||||
|
||||
private var editorPlaceholder: some View {
|
||||
VStack(spacing: 10) {
|
||||
if let post = posts.first(where: { $0.id == selectedPostID }) {
|
||||
Text(post.title)
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
private var editorColumn: some View {
|
||||
VStack(spacing: 0) {
|
||||
if let draft = model.draft {
|
||||
EditorStub(
|
||||
initialText: draft.text,
|
||||
crumb: "unsaved draft — no folder until first save",
|
||||
save: { text in
|
||||
model.updateDraft(text)
|
||||
model.saveDraft(home: home)
|
||||
},
|
||||
)
|
||||
.id("draft")
|
||||
} else if let post = model.posts.first(where: { $0.id == model.selectedPostID }) {
|
||||
// ponytail: readBody is one small file, sync, per selection
|
||||
// change — #19's editor owns async loading when it lands.
|
||||
EditorStub(
|
||||
initialText: PostStore.readBody(id: post.id, home: home) ?? "",
|
||||
crumb: "posts / \(post.id) / post.md",
|
||||
save: { text in model.saveSelected(body: text, home: home) },
|
||||
)
|
||||
.id(post.id)
|
||||
} else {
|
||||
VStack(spacing: 10) {
|
||||
Image(systemName: "square.and.pencil")
|
||||
.font(.largeTitle)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Text("Select a post, or start a new one.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
if let error = model.lastError {
|
||||
Text(error)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.accent)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
Text("The editor arrives with S1.2 (#19–#21).")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(DesignTokens.surface)
|
||||
@@ -124,6 +175,95 @@ struct PostsPaneView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// #18 stub editor (#62): plain TextEditor in the placeholder slot; ⌘S is
|
||||
/// the first-write trigger (lazy folder + slug + stamp). Throwaway at the
|
||||
/// view layer — #19's TextKit2 editor replaces it in place; the lifecycle
|
||||
/// machinery lives in PostsModel/PostStore and survives the swap.
|
||||
private struct EditorStub: View {
|
||||
/// Typed text is local @State — disk is written only on save; `.id()` at
|
||||
/// the call site swaps identity (and thus reloads) per post/draft.
|
||||
let crumb: String
|
||||
let save: (String) -> Void
|
||||
@State private var text: String
|
||||
|
||||
init(
|
||||
initialText: String,
|
||||
crumb: String,
|
||||
save: @escaping (String) -> Void,
|
||||
) {
|
||||
self.crumb = crumb
|
||||
self.save = save
|
||||
_text = State(initialValue: initialText)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text(crumb)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.head)
|
||||
Spacer()
|
||||
Button("Save") { save(text) }
|
||||
.keyboardShortcut("s", modifiers: .command)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.frame(minHeight: 40)
|
||||
.overlay(alignment: .bottom) {
|
||||
Rectangle().fill(DesignTokens.border).frame(height: 1)
|
||||
}
|
||||
TextEditor(text: $text)
|
||||
.font(.system(size: 15, design: DesignTokens.serif))
|
||||
.scrollContentBackground(.hidden)
|
||||
.padding(EdgeInsets(top: 20, leading: 24, bottom: 20, trailing: 24))
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
/// #60: Explicit Rename dialog — asks the new Title (not a slug).
|
||||
private struct RenamePostSheet: View {
|
||||
let rename: (String) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var title: String
|
||||
|
||||
init(post: Post, rename: @escaping (String) -> Void) {
|
||||
self.rename = rename
|
||||
_title = State(initialValue: post.title)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Rename Post")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("The folder moves to match the new Title. The file stays post.md.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
TextField("Title", text: $title)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit { confirm() }
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel) { dismiss() }
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Rename", action: confirm)
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 360)
|
||||
}
|
||||
|
||||
private func confirm() {
|
||||
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return }
|
||||
rename(trimmed)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
/// One post row per the export: title, Pass State + Origin in mono 11.
|
||||
private struct PostRow: View {
|
||||
let post: Post
|
||||
|
||||
@@ -39,6 +39,7 @@ struct WorkspaceView: View {
|
||||
home: gate.museionHome,
|
||||
mentor: gate.mentor,
|
||||
mentorBinaryPath: gate.gateModel.currentBinaryPath,
|
||||
model: gate.posts,
|
||||
availableWidth: geo.size.width - DesignTokens.railWidth,
|
||||
)
|
||||
case .sessions:
|
||||
@@ -125,9 +126,15 @@ private struct RailButton: View {
|
||||
}
|
||||
|
||||
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
|
||||
/// Trailing slot returns with #18's New Post button.
|
||||
struct PaneHeader: View {
|
||||
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
|
||||
struct PaneHeader<Trailing: View>: View {
|
||||
let title: String
|
||||
@ViewBuilder var trailing: () -> Trailing
|
||||
|
||||
init(title: String, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) {
|
||||
self.title = title
|
||||
self.trailing = trailing
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
@@ -135,6 +142,7 @@ struct PaneHeader: View {
|
||||
Text(title)
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Spacer()
|
||||
trailing()
|
||||
}
|
||||
.padding(.horizontal, 14)
|
||||
.frame(minHeight: 52)
|
||||
|
||||
@@ -21,6 +21,7 @@ Owned by the root AGENTS.md contract.
|
||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17) — throwaway Homes via `makeHome`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`), lazy folders / hidden dirs / symlinks / noise not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostStoreTests.swift` (#18) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write + #59 stamp round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes, rename (retitle + move, insert-title path, same-slug retitle-only, collision -2), trash removes from posts/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-posts failure path.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//
|
||||
// PostStoreTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #18: the Post lifecycle write side — slug naming, lazy first write with
|
||||
// the #59 stamp, rename = retitle + move (#60), Trash delete, save-time
|
||||
// normalization.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
/// Throwaway Home in a temp dir (PostLibraryTests convention).
|
||||
private func storeHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("poststore-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
try write(home)
|
||||
return home
|
||||
}
|
||||
|
||||
private func readPost(_ home: URL, _ id: String) throws -> String {
|
||||
try String(contentsOf: home.appendingPathComponent("posts/\(id)/post.md"), encoding: .utf8)
|
||||
}
|
||||
|
||||
@Test func `slug algorithm per #60`() {
|
||||
#expect(PostStore.slug(from: "The Cartographer's Error") == "the-cartographers-error")
|
||||
#expect(PostStore.slug(from: "A Short Defence of Footnotes") == "a-short-defence-of-footnotes")
|
||||
#expect(PostStore.slug(from: "Café naïve résumé") == "cafe-naive-resume") // diacritic-fold
|
||||
#expect(PostStore.slug(from: "Hello — World!") == "hello-world") // em-dash dropped, space hyphenated
|
||||
#expect(PostStore.slug(from: " leading and trailing ") == "leading-and-trailing")
|
||||
#expect(PostStore.slug(from: "Multiple spaces") == "multiple-spaces") // runs → one hyphen
|
||||
#expect(PostStore.slug(from: "北京 Notes") == "北京-notes") // CJK kept
|
||||
#expect(PostStore.slug(from: String(repeating: "a", count: 100)) == String(repeating: "a", count: 80)) // 80-char cap
|
||||
#expect(PostStore.slug(from: "!!!") == "untitled")
|
||||
#expect(PostStore.slug(from: "") == "untitled")
|
||||
}
|
||||
|
||||
@Test func `first write is lazy stamps frontmatter and slugs the folder`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# My First Post\n\nBody.", home: home)
|
||||
|
||||
#expect(post.id == "my-first-post")
|
||||
#expect(post.passState == .firstDraft)
|
||||
#expect(post.origin == .writer)
|
||||
#expect(post.title == "My First Post")
|
||||
let file = try readPost(home, "my-first-post")
|
||||
#expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# My First Post\n\nBody.")
|
||||
|
||||
// The #17 reader round-trips what the write side stamps.
|
||||
let scanned = Post.scan(home: home)
|
||||
#expect(scanned.count == 1)
|
||||
#expect(scanned.first?.title == "My First Post")
|
||||
#expect(scanned.first?.passState == .firstDraft)
|
||||
#expect(scanned.first?.origin == .writer)
|
||||
}
|
||||
|
||||
@Test func `untitled draft first save uses untitled fallback`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "\n\n", home: home)
|
||||
#expect(post.id == "untitled")
|
||||
#expect(post.title == "untitled")
|
||||
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/untitled/post.md").path))
|
||||
}
|
||||
|
||||
@Test func `collision appends -2 -3 case-insensitively`() throws {
|
||||
let home = try storeHome { home in
|
||||
try FileManager.default.createDirectory(
|
||||
at: home.appendingPathComponent("posts/my-post", isDirectory: true),
|
||||
withIntermediateDirectories: true,
|
||||
)
|
||||
try FileManager.default.createDirectory(
|
||||
at: home.appendingPathComponent("posts/My-Post-2", isDirectory: true),
|
||||
withIntermediateDirectories: true,
|
||||
)
|
||||
try "x".write(to: home.appendingPathComponent("posts/my-post/post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
// existing: my-post, My-Post-2 → next free: my-post-3
|
||||
#expect(PostStore.availableSlug(for: "My Post", in: home.appendingPathComponent("posts")) == "my-post-3")
|
||||
|
||||
let post = try PostStore.writeNew(body: "# My Post\n", home: home)
|
||||
#expect(post.id == "my-post-3")
|
||||
}
|
||||
|
||||
@Test func `rename retitles moves folder and keeps frontmatter`() throws {
|
||||
let home = try storeHome()
|
||||
let original = try PostStore.writeNew(body: "# Old Name\n\nBody.", home: home)
|
||||
let moved = try PostStore.rename(original, to: "New Name", home: home)
|
||||
|
||||
#expect(moved.id == "new-name")
|
||||
#expect(moved.title == "New Name")
|
||||
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/old-name").path))
|
||||
let file = try readPost(home, "new-name")
|
||||
#expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# New Name\n\nBody.")
|
||||
}
|
||||
|
||||
@Test func `rename inserts title line when body had none`() throws {
|
||||
let home = try storeHome()
|
||||
let original = try PostStore.writeNew(body: "\n\n", home: home)
|
||||
#expect(original.id == "untitled")
|
||||
let moved = try PostStore.rename(original, to: "Given Title", home: home)
|
||||
#expect(moved.id == "given-title")
|
||||
let file = try readPost(home, "given-title")
|
||||
#expect(file.hasPrefix("---\npass_state: First Draft\norigin: writer\n---\n# Given Title"))
|
||||
}
|
||||
|
||||
@Test func `rename keeps non-heading first line and inserts title above`() throws {
|
||||
let home = try storeHome()
|
||||
let original = try PostStore.writeNew(body: "Call mom tomorrow\n\nSecond line.", home: home)
|
||||
let moved = try PostStore.rename(original, to: "Errands", home: home)
|
||||
#expect(moved.id == "errands")
|
||||
let file = try readPost(home, "errands")
|
||||
#expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# Errands\nCall mom tomorrow\n\nSecond line.")
|
||||
}
|
||||
|
||||
@Test func `overwrite on vanished post throws instead of resurrecting`() throws {
|
||||
let home = try storeHome()
|
||||
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
|
||||
try PostStore.overwrite(id: "ghost", body: "# Ghost\n", home: home)
|
||||
}
|
||||
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/ghost").path))
|
||||
}
|
||||
|
||||
@Test func `collision routing consults a fresh listing`() throws {
|
||||
let home = try storeHome()
|
||||
_ = try PostStore.writeNew(body: "# Mine\n", home: home) // mine
|
||||
_ = try PostStore.writeNew(body: "# Mine\n", home: home) // mine-2
|
||||
// An external write lands a folder the app didn't create — the next
|
||||
// slug pick must see it. (The in-writeNew existence guard covers the
|
||||
// race where the folder appears after the pick; that window isn't
|
||||
// deterministically reachable from a black-box test.)
|
||||
let racedDir = home.appendingPathComponent("posts/mine-3", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: racedDir, withIntermediateDirectories: true)
|
||||
try "external".write(to: racedDir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
#expect(PostStore.availableSlug(for: "Mine", in: home.appendingPathComponent("posts")) == "mine-4")
|
||||
_ = try PostStore.writeNew(body: "# Mine\n", home: home)
|
||||
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/mine-4/post.md").path))
|
||||
}
|
||||
|
||||
@Test func `rename to same slug only retitles`() throws {
|
||||
let home = try storeHome()
|
||||
let original = try PostStore.writeNew(body: "# Same Name\n\nBody.", home: home)
|
||||
// Title slugs to same id → rewrite # line, no move.
|
||||
let moved = try PostStore.rename(original, to: "Same name!", home: home)
|
||||
#expect(moved.id == "same-name")
|
||||
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/same-name/post.md").path))
|
||||
}
|
||||
|
||||
@Test func `rename collision takes -2`() throws {
|
||||
let home = try storeHome()
|
||||
let alpha = try PostStore.writeNew(body: "# Alpha\n", home: home)
|
||||
try PostStore.writeNew(body: "# Beta\n", home: home)
|
||||
let moved = try PostStore.rename(alpha, to: "Beta", home: home)
|
||||
#expect(moved.id == "beta-2")
|
||||
let renamed = try readPost(home, "beta-2")
|
||||
#expect(renamed.hasPrefix("---\npass_state: First Draft\norigin: writer\n---\n# Beta"))
|
||||
}
|
||||
|
||||
@Test func `trash moves folder out of posts recoverably`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home)
|
||||
try PostStore.trash(post, home: home)
|
||||
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/\(post.id)").path))
|
||||
#expect(Post.scan(home: home).isEmpty)
|
||||
}
|
||||
|
||||
@Test func `overwrite preserves pass_state and origin normalizing bare posts`() throws {
|
||||
let home = try storeHome()
|
||||
// A bare corpus post on disk (no frontmatter).
|
||||
let dir = home.appendingPathComponent("posts/bare-one", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try "# Bare\n\nCorpus body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
|
||||
try PostStore.overwrite(id: "bare-one", body: "# Bare\n\nEdited body.", home: home)
|
||||
|
||||
let file = try readPost(home, "bare-one")
|
||||
#expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# Bare\n\nEdited body.")
|
||||
let scanned = try #require(Post.scan(home: home).first)
|
||||
#expect(scanned.passState == .firstDraft)
|
||||
#expect(scanned.origin == .writer)
|
||||
}
|
||||
|
||||
@Test func `overwrite preserves existing pass_state and origin values`() throws {
|
||||
let home = try storeHome { home in
|
||||
let dir = home.appendingPathComponent("posts/stamped", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try "---\npass_state: Pass-1 Done\norigin: ai\n---\n# Stamped\n\nBody."
|
||||
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
try PostStore.overwrite(id: "stamped", body: "# Stamped\n\nNew body.", home: home)
|
||||
|
||||
let post = try #require(Post.scan(home: home).first)
|
||||
#expect(post.passState == .pass1Done)
|
||||
#expect(post.origin == .ai)
|
||||
}
|
||||
|
||||
@Test func `readBody strips frontmatter for editing`() throws {
|
||||
let home = try storeHome()
|
||||
_ = try PostStore.writeNew(body: "# Editable\n\nSome text.", home: home)
|
||||
#expect(PostStore.readBody(id: "editable", home: home) == "# Editable\n\nSome text.")
|
||||
#expect(PostStore.readBody(id: "missing", home: home) == nil)
|
||||
}
|
||||
|
||||
@Test func `writeNew failure does not leave a half post`() throws {
|
||||
// A file where the posts dir should go: writeNew must fail cleanly.
|
||||
let home = try storeHome()
|
||||
let postsPath = home.appendingPathComponent("posts").path
|
||||
try "blocker".write(to: URL(fileURLWithPath: postsPath), atomically: true, encoding: .utf8)
|
||||
#expect(throws: Error.self) {
|
||||
_ = try PostStore.writeNew(body: "# Blocked\n", home: home)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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<Trailing>` 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/<id>/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*
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-10-03 | issue | [20261003-issue18-post-lifecycle_log.md](20261003-issue18-post-lifecycle_log.md) | #18 shipped + audits: Post write side, FSEvents watcher, editor stub — 75 tests green |
|
||||
| 2026-10-01 | issue | [20261001-issue17-home-posts-list_log.md](20261001-issue17-home-posts-list_log.md) | #17 shipped + finish-audit: workspace shell, Posts mirror, Home repoint — 56 tests green |
|
||||
| 2026-10-01 | issue | [20261001-issue55-verdict-substrate-adr-0010_log.md](20261001-issue55-verdict-substrate-adr-0010_log.md) | #55 + map #16 closed: TextKit2 mode B wins, ADR-0010 drafted, typography/rendering stances locked |
|
||||
| 2026-09-25 | issue | [20260925-issue50-profile-backup-s2-6_log.md](20260925-issue50-profile-backup-s2-6_log.md) | #50 S2.6 daily profile backup: liveness gate, curated copy, retention 7, RESTORE.md — 8 tests green |
|
||||
|
||||
Reference in new issue
Block a user