diff --git a/AGENTS.md b/AGENTS.md index cce2c5b..93c4e06 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (2535 symbols, 6668 relationships, 166 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (2654 symbols, 7109 relationships, 192 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 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-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) | | 2026-10-09 | [20261009-issue88-calibration-gate_log.md](docs/devlog/20261009-issue88-calibration-gate_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 851caf6..cc76dac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **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 storage substrate (v1.1 S1) — pieces live under `projects///post.md` with finished work folding into `archive//` (ADR-0012): the library scans both roots, New Piece and Import land in the selected project (else the default `posts`), slugs stay globally unique across projects and archive so an archived name is never reused, and every piece carries `type: post` frontmatter (absent or unknown types read as post; the file stays `post.md` for every type) (issue #107) - **editor:** spellcheck posture (#77, Neo triage input) — Edit ▸ Check Spelling While Typing now toggles continuous spell checking in the editor; off by default (markdown on disk carries the spelling, squiggles on request), per-launch with no persistence diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 490d911..a4c806b 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Local Contracts -- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. +- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires). - `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project). - Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 26.5; bundle id `com.babylondreams.Museion`. - App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file. @@ -21,11 +21,11 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Workspace shell (M1, #17 + #18 / S1.1) - `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette. -- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. -- `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. +- `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 `` + 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). +- `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///post.md` AND `archive///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), `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:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; stamp now `type: post` + `pass_state: First Draft` + `origin: writer`), `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). -- `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`; `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. +- `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:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; stamp now `type: post` + `pass_state: First Draft` + `origin: writer`), `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 disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — 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//`), 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`; `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). - 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/` 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). - Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. diff --git a/Museion/EditorSession.swift b/Museion/EditorSession.swift index d4ba49a..ccffc1b 100644 --- a/Museion/EditorSession.swift +++ b/Museion/EditorSession.swift @@ -176,20 +176,25 @@ final class EditorSession { // MARK: Flush (#64/#65/#66) /// Write body (+ post sidecar) now. ⌘S, debounce fire, selection change, - /// window close, and app quit all land here. No-op when clean or when - /// the document never loaded (a failed read must not become a write - /// that destroys the file). - func flush() { + /// window close, and app quit all land here. No-op when clean or when the + /// document never loaded (a failed read must not become a write + /// that destroys the file). #108 audit: reports success — the flush-first + /// ops (move/archive/rename/restore) abort on false instead of moving a + /// piece whose edits failed to land. + @discardableResult + func flush() -> Bool { debounceTask?.cancel() - guard !loadFailed, text != lastFlushedText else { return } + guard !loadFailed, text != lastFlushedText else { return true } do { try writeDocument() lastFlushedText = text saveState = .saved onError?(nil) + return true } catch { saveState = .failed onError?(error.localizedDescription) + return false } } diff --git a/Museion/MuseionApp.swift b/Museion/MuseionApp.swift index f370120..e26b5dd 100644 --- a/Museion/MuseionApp.swift +++ b/Museion/MuseionApp.swift @@ -88,6 +88,10 @@ struct MuseionApp: App { // File menu after New — never CommandMenu("File"), which doubles // it (#84 trap). CommandGroup(after: .newItem) { + // #108: New Post / New Project… go FIRST in the group — the + // menu reads New Post / New Project… / Open… / Import… + NewPostButton(gate: gate) + NewProjectButton(gate: gate) OpenExternalButton(gate: gate) ImportFilesButton(gate: gate) } @@ -160,6 +164,29 @@ private struct FocusModeToggle: View { } } +/// #108: File ▸ New Post (⌘N) — same draft path as the library's + button. +/// The stock new-window item may swallow or duplicate ⌘N in some macOS +/// builds; the action still fires from the menu either way. +private struct NewPostButton: View { + let gate: AppGateState + + var body: some View { + Button("New Post") { gate.posts.newPost() } + .keyboardShortcut("n", modifiers: .command) + } +} + +/// #108: File ▸ New Project… (⌥⌘N) — stages the ask; WorkspaceView presents +/// the sheet (commands views can't; the pendingImportURLs pattern, #94). +private struct NewProjectButton: View { + let gate: AppGateState + + var body: some View { + Button("New Project…") { gate.posts.stageNewProject() } + .keyboardShortcut("n", modifiers: [.command, .option]) + } +} + /// #91: File ▸ Open… (⌘O) — NSOpenPanel (the Settings Home picker pattern), /// .md/.markdown only (#96). Opens into the single external guest slot. private struct OpenExternalButton: View { diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index 6c0c7bc..9696b83 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -7,6 +7,8 @@ // = retitle + move (#60), Trash delete. Pure disk operations, no UI state. // #107 (ADR-0012): pieces live under projects/// (archive/ // mirrors the shape); the slug namespace is global across both roots. +// #108: project moves and archive/restore are plain folder moves between +// those roots — post.md bytes are never rewritten. // import Foundation @@ -41,7 +43,9 @@ nonisolated enum PostStore { // project counts; cache id→folder if it ever measures hot. // Audit: project-level guards mirror scan's skips (hidden dirs, // symlinks) so write paths and the library agree on what exists — - // a piece in a dot-project must never shadow a visible one. + // a piece in a dot-project must never shadow a visible one. The + // piece-level check resolves symlinks (only a stale-selection race + // reaches one — scan never lists symlinked pieces). static func folder(of id: String, home: URL) -> URL? { for root in Post.containerRoots { let rootURL = home.appendingPathComponent(root, isDirectory: true) @@ -91,12 +95,6 @@ nonisolated enum PostStore { return result.isEmpty ? "untitled" : result } - /// First free slug for a title: base slug, then `-2`, `-3`… (#60). - /// Case-insensitive existence check (#60): the slug namespace is GLOBAL - /// (#107) — every entry (dir or file) under `projects/*/` and `archive/*/` - /// is taken, lowercased — independent of the volume's case sensitivity, - /// and an archived slug is never reused. `excluding` skips an id (the - /// renamer's own, still present). /// First free slug for a title: base slug, then `-2`, `-3`… (#60), over /// the GLOBAL namespace (#107) — every entry under `projects/*/` and /// `archive/*/` (an archived slug must never be reused; restore would @@ -116,21 +114,34 @@ nonisolated enum PostStore { atPath: rootURL.appendingPathComponent(project, isDirectory: true).path, )) ?? [] for entry in entries { - taken.insert(entry.lowercased()) + // #108 audit: all slug-space comparisons through `folded` — + // NFC + lowercase. Swift's == and Set hashing already fold + // canonical equivalence, so this is the explicit, tested + // contract rather than a behavior change; the load-bearing + // part is the lowercase (APFS is case-insensitive). + taken.insert(folded(entry)) } } } - let base = slug(from: title) // slug() is already lowercase - if !taken.contains(base) || base == ownID?.lowercased() { + let base = slug(from: title) // as-produced — the folder matches the title's bytes + let key = folded(base) + if !taken.contains(key) || key == ownID.flatMap(folded) { return base } var suffix = 2 - while taken.contains("\(base)-\(suffix)") { + while taken.contains(folded("\(base)-\(suffix)")) { suffix += 1 } return "\(base)-\(suffix)" } + /// #108 audit: the canonical compare key — case-folded + Unicode-normalization + /// folded (NFC). APFS is normalization-insensitive, so two byte-sequences can + /// be one folder; every name-uniqueness check must compare through this. + private static func folded(_ name: String) -> String { + name.precomposedStringWithCanonicalMapping.lowercased() + } + /// First write (#62): lazily materialize `projects///post.md` /// with the #59 block stamped (plus `type: post`, #107). Pass State First /// Draft, origin writer — the only values #18 writes; the folder appears @@ -347,6 +358,147 @@ nonisolated enum PostStore { try FileManager.default.trashItem(at: dir, resultingItemURL: &trashed) } + // MARK: Project moves & archive (#108) + + /// #108: move an active piece to another project — projects// → + /// projects/// (folder move, post.md untouched, frontmatter + /// preserved). Destination project folder lazily created. Throws when the + /// piece is archived (restore is the archived move) or unresolvable, or + /// the destination already exists (disk anomaly — never clobber). A move + /// to the piece's own project is a no-op (the picker shows it, the writer + /// might confirm it — not an error). The current project derives from the + /// freshly resolved folder, not the scan snapshot (a Finder-side move + /// between scan and click must not misfile the piece). + static func move(_ post: Post, to project: String, home: URL) throws { + guard let dir = folder(of: post.id, home: home) else { + throw CocoaError(.fileReadNoSuchFile) + } + // #108 audit 2: the refusal derives from the resolved path, not the + // scan snapshot — a stale isArchived=false must not smuggle an + // archived piece back into projects/ (restore is the archived move). + let projectDir = dir.deletingLastPathComponent() + guard projectDir.deletingLastPathComponent().lastPathComponent != "archive" else { + throw CocoaError(.featureUnsupported) + } + let target = try validatedProject(project) + guard folded(target) != folded(projectDir.lastPathComponent) else { return } + try relocate(dir, id: post.id, toRoot: "projects", project: target, home: home) + } + + /// #108: archive one piece — projects/

/ → archive/

// (folder + /// move; lazily creates archive/

/). The project derives from the + /// freshly resolved folder (not the scan snapshot). + static func archive(_ post: Post, home: URL) throws { + guard let dir = folder(of: post.id, home: home) else { + throw CocoaError(.fileReadNoSuchFile) + } + try relocate(dir, id: post.id, toRoot: "archive", + project: dir.deletingLastPathComponent().lastPathComponent, home: home) + } + + /// #108: put an archived piece back — archive/

/ → projects/

//. + static func restore(_ post: Post, home: URL) throws { + guard let dir = folder(of: post.id, home: home) else { + throw CocoaError(.fileReadNoSuchFile) + } + try relocate(dir, id: post.id, toRoot: "projects", + project: dir.deletingLastPathComponent().lastPathComponent, home: home) + } + + /// #108: unarchive a whole project — archive// → projects//. + /// When projects// already exists, merge child-by-child instead of + /// failing (ids are globally unique, so real collisions are disk anomalies + /// that throw honestly). The emptied archive// is removed. + static func unarchiveProject(_ name: String, home: URL) throws { + var isDir: ObjCBool = false + let source = home.appendingPathComponent("archive", isDirectory: true) + .appendingPathComponent(name, isDirectory: true) + guard FileManager.default.fileExists(atPath: source.path, isDirectory: &isDir), isDir.boolValue else { + throw CocoaError(.fileReadNoSuchFile) + } + // One code path for both cases: dest created (or already there), every + // child moved, the emptied source removed. moveItem throws on an + // existing destination child — a duplicate id from a Finder copy + // surfaces loudly instead of being clobbered mid-merge. + let dest = home.appendingPathComponent("projects", isDirectory: true) + .appendingPathComponent(name, isDirectory: true) + try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true) + for child in try FileManager.default.contentsOfDirectory(atPath: source.path) { + // #108 audit: Finder metadata (.DS_Store) browsed into both halves + // would collide forever — dot-entries are invisible to the app + // everywhere else (scan, folder(of:)); skip them here too. + guard !child.hasPrefix(".") else { continue } + try FileManager.default.moveItem( + atPath: source.appendingPathComponent(child).path, + toPath: dest.appendingPathComponent(child).path, + ) + } + // #108 audit 2: removeItem is permanent — only take the source down + // when the loop emptied it. Dot-entries skipped above (and any hidden + // user folder, .git, .research) stay where they are instead of being + // silently destroyed with the folder. + if (try? FileManager.default.contentsOfDirectory(atPath: source.path))?.isEmpty != false { + try FileManager.default.removeItem(at: source) + } + } + + /// #108: materialize an empty projects//. Throws on a name that is + /// empty after trimming, contains "/", starts with ".", or collides with an + /// existing project under projects/ (case-insensitive, matching the volume). + static func createProject(named name: String, home: URL) throws { + let project = try validatedProject(name) + let projectsRoot = home.appendingPathComponent("projects", isDirectory: true) + // Case-insensitive (#60's rule for slugs, same reason): APFS is + // case-insensitive by default — "Foo" next to "foo" is one folder on + // disk but two projects in the UI. Independent of the volume's actual + // sensitivity, same as availableSlug. + let existing = (try? FileManager.default.contentsOfDirectory(atPath: projectsRoot.path)) ?? [] + // #108 audit: fold Unicode normalization before the case-insensitive + // compare — NFC vs NFD "café" reads identical but makes two folders + // on normalization-insensitive APFS (and two indistinguishable + // sections). availableSlug folds through the same `folded` key. + guard !existing.contains(where: { folded($0) == folded(project) }) else { + throw CocoaError(.fileWriteFileExists) + } + try FileManager.default.createDirectory( + at: projectsRoot.appendingPathComponent(project, isDirectory: true), + withIntermediateDirectories: true, + ) + } + + /// The shared #108 relocation: resolve once, then a plain FileManager move + /// of the whole piece folder into /// — lazy parent, + /// never clobbering, post.md bytes untouched. + private static func relocate( + _ dir: URL, id: String, toRoot root: String, project: String, home: URL, + ) throws { + let parent = home.appendingPathComponent(root, isDirectory: true) + .appendingPathComponent(project, isDirectory: true) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let dest = parent.appendingPathComponent(id, isDirectory: true) + // ids are globally unique — an existing destination is a disk anomaly + // (duplicate id from a Finder copy) or a self-move; fail loudly. + guard !FileManager.default.fileExists(atPath: dest.path) else { + throw CocoaError(.fileWriteFileExists) + } + try FileManager.default.moveItem(at: dir, to: dest) + } + + /// #108: a project name becomes a folder name — trim, then reject empty, + /// path separators (traversal), hidden names (scan skips dot-dirs), and + /// ":"/control characters (Finder displays ":" as "/" — a legal APFS name + /// that round-trips confusingly). + private static func validatedProject(_ name: String) throws -> String { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.hasPrefix("."), + !trimmed.contains(":"), + !trimmed.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + else { + throw CocoaError(.fileWriteInvalidFileName) + } + return trimmed + } + /// The #59 v1 block (+ `type`, #107) — flat keys, the exact shape the /// #17 reader parses. static func stamped(body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post) -> String { diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 45a66e5..0011718 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -6,6 +6,8 @@ // roots (projects/ + archive/, #107) 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. +// #108: project targeting + the move/archive/restore ops behind the +// variant-B library and the Archive pane. // import CoreServices @@ -96,6 +98,16 @@ final class PostsModel { /// answers, then the batch runs. private(set) var pendingImportURLs: [URL]? + /// #108: the explicit target for the NEXT new piece — set by New Project + /// once the folder exists; outranks selection. Cleared when the draft + /// lands (saveDraft) or the ask is canceled. + private(set) var pendingProject: String? + + /// #108: File ▸ New Project… stages its ask here — commands can't + /// present sheets, so the model holds the flag and WorkspaceView + /// presents (the pendingImportURLs pattern, #94). + private(set) var askNewProject = false + /// Last failed-op message surfaced in the editor (nil = clean). private(set) var lastError: String? @@ -163,11 +175,13 @@ final class PostsModel { // writes and same-volume moves; if a big Home ever stalls the UI, wrap // them in Task.detached like rescan. - /// #107: the project a NEW piece lands in — the selected non-archived - /// post's project, else the default. One home; newPost/importFiles must - /// not drift. + /// #107: the project a NEW piece lands in — #108: an explicit pending + /// target first, else the selected non-archived post's project, else the + /// default. One home; newPost/importFiles must not drift. private var targetProject: String { - posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project ?? Post.defaultProject + pendingProject + ?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project + ?? Post.defaultProject } /// Tear the watcher down on the main actor (its scheduling thread) — @@ -211,6 +225,7 @@ final class PostsModel { do { let post = try PostStore.writeNew(body: draft.text, project: draft.project, home: home) self.draft = nil + pendingProject = nil // #108: the explicit target landed with the draft selectedPostID = post.id session = EditorSession(postID: post.id, home: home) wireSession() @@ -233,6 +248,9 @@ final class PostsModel { } session = id == session?.postID ? session : EditorSession(postID: id, home: home) draft = nil + // #108: abandoning the draft kills its explicit project target too — + // a later New Post must not silently land in the abandoned project. + pendingProject = nil selectedPostID = id wireSession() } @@ -247,9 +265,10 @@ final class PostsModel { /// before the move), then reopens a session at the new id. Sets lastError /// on failure. func rename(_ post: Post, to title: String, home: URL) { - if let session, session.postID == post.id { - session.flush() // before PostStore.rename reads the old file - } + // #108 audit 2: rename reads the file from disk — a failed write + // aborts (moving the folder would strand unflushed edits), and the + // session stays up, dirty and honest. + guard flushOrAbort(post.id) else { return } do { let moved = try PostStore.rename(post, to: title, home: home) if selectedPostID == post.id { @@ -286,6 +305,159 @@ final class PostsModel { } } + // MARK: Projects (#108) + + /// #108: New Project's confirmed sheet — the folder exists, the next + /// draft targets it, and opens now. + func newProjectPending(named name: String) { + pendingProject = name + newPost() + } + + /// #108: raw create — the sheet composes on it. The failure reason on + /// false (shown inline in the sheet; never routed into lastError — the + /// strip behind the sheet must not double-message one error). + func createProject(named name: String, home: URL) -> String? { + do { + try PostStore.createProject(named: name, home: home) + return nil // success + } catch { + return error.localizedDescription + } + } + + /// #108: File ▸ New Project… — stage the ask (WorkspaceView presents). + func stageNewProject() { + askNewProject = true + } + + /// #108: the ask's Cancel. + func cancelNewProject() { + askNewProject = false + } + + /// #108 audit 2: the Move-to-Project list — every project on disk under + /// projects/ plus the default (bind creates the roots, not posts/ — an + /// empty Home must still offer it), localized-sorted to match the + /// library's section order. + func moveTargets(home: URL) -> [String] { + let root = home.appendingPathComponent("projects", isDirectory: true) + let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] + var names = Set(onDisk.filter { !$0.hasPrefix(".") }) + names.insert(Post.defaultProject) + return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } + } + + /// #108 audit: flush the open piece, aborting when the write failed — a + /// folder move must never carry away text that didn't land (the move + /// itself succeeds exactly when a file write fails). Returns false with + /// lastError set; the session stays up, dirty and honest. + private func flushOrAbort(_ postID: String) -> Bool { + guard let session, session.postID == postID else { return true } + if !session.flush() { + // Append, don't replace — the flush already routed the write's + // localizedDescription into lastError; only say what was skipped. + lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was moved." + return false + } + return true + } + + /// #108: Move to Project — flush first (move reads disk), then the + /// folder moves under projects/. Id stays the same; the session is + /// reopened anyway so folderURL re-resolves to the new parent. + func moveToProject(_ post: Post, project: String, home: URL) { + guard flushOrAbort(post.id) else { return } + do { + try PostStore.move(post, to: project, home: home) + if session?.postID == post.id { + session = EditorSession(postID: post.id, home: home) + wireSession() + } + lastError = nil + Task { await rescan() } + } catch { + lastError = error.localizedDescription + } + } + + /// #108: Move to Archive. Archiving the open piece clears it — the + /// editor is empty until the next selection (archived pieces open from + /// the Archive pane, where they're listed). + func archivePost(_ post: Post, home: URL) { + guard flushOrAbort(post.id) else { return } + do { + try PostStore.archive(post, home: home) + if selectedPostID == post.id { + selectedPostID = nil + } + if let open = session, open.postID == post.id { + open.teardown(flushFirst: false) // already flushed above + session = nil + } + lastError = nil + Task { await rescan() } + } catch { + lastError = error.localizedDescription + } + } + + /// #108: Move Back — the restored piece lands in its project and opens; + /// the writer stays in the piece they just revived. A session already + /// open on the piece survives `select` — reopen it so folderURL points + /// at projects/, not the archive path it was born with. + func restorePost(_ post: Post, home: URL) { + guard flushOrAbort(post.id) else { return } + do { + try PostStore.restore(post, home: home) + if let open = session, open.postID == post.id { + session = EditorSession(postID: post.id, home: home) + wireSession() + } else { + select(post.id, home: home) + } + lastError = nil + Task { await rescan() } + } catch { + lastError = error.localizedDescription + } + } + + /// #108: whole-project unarchive from the Archive pane's section header. + /// Flush-first like every folder move (a dirty open piece inside the + /// project would otherwise race the move), and its session is reopened so + /// folderURL re-resolves off archive/ (same reason as restorePost). + func unarchiveProject(_ name: String, home: URL) { + /// #108 audit 2: disk-derived membership — the posts snapshot is stale + /// the moment a Finder move lands. Captured BEFORE the move: after it + /// the piece resolves under projects/ and its archive membership is + /// invisible. dir − 1 = project dir (…/archive/), − 2 = root. + func openPieceInArchivedProject() -> String? { + guard let id = session?.postID, + let projectDir = PostStore.folder(of: id, home: home)?.deletingLastPathComponent(), + projectDir.lastPathComponent == name, + projectDir.deletingLastPathComponent().lastPathComponent == "archive" + else { return nil } + return id + } + let openID = openPieceInArchivedProject() + if let openID { + // #108 audit 2: the only #108 folder move that skipped the gate. + guard flushOrAbort(openID) else { return } + } + do { + try PostStore.unarchiveProject(name, home: home) + if let openID { + session = EditorSession(postID: openID, home: home) + wireSession() + } + lastError = nil + Task { await rescan() } + } catch { + lastError = error.localizedDescription + } + } + // MARK: External buffer (#91–#93) + Import (#94/#95) /// #91/#92: open an external markdown file in the guest slot — one at a @@ -302,6 +474,7 @@ final class PostsModel { session?.teardown(flushFirst: true) // #92: the guest takes the column session = nil draft = nil + pendingProject = nil // #108 audit: the draft died here too — its target dies with it externalSession = EditorSession(target: .externalFile(target)) if externalSession?.loadFailed == true { lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 1ad1973..6d970dd 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -6,6 +6,9 @@ // projects/ (and archive/) on disk. #18: lifecycle — New Post draft, ⌘S first-write/save, rename, // trash. #19: the TextKit2 editor core (PostEditorView) replaces the stub; // mentor column (#14). +// #108 (variant B, ref/prototypes/wf104-library-ui-prototype.html): sections +// per project (serif-15 head + mono count), Pass-State groups inside, and a +// 2px accent edge bar on the selected row. // import SwiftUI @@ -124,12 +127,23 @@ struct PostsPaneView: View { } /// #21: the library column, shared by the unfocused layout and the focus-mode -/// left reveal overlay — one implementation, both surfaces. Owns the rename -/// sheet + context menu (they travel with the post rows). +/// left reveal overlay — one implementation, both surfaces. Owns the rename + +/// move sheets and the context menu (they travel with the post rows). +/// #108 variant B: sections per project, Pass-State groups inside. struct PostsLibraryColumn: View { let home: URL var model: PostsModel @State private var renamingPost: Post? + @State private var movingPost: Post? + /// #108: collapsed project sections — per-view state, not persisted (a + /// fresh open shows everything; the prototype behaved the same). + @State private var collapsed: Set = [] + + /// Non-archived pieces keyed by project (scan order = title order holds + /// inside each group — filter preserves it). + private var activeByProject: [String: [Post]] { + Dictionary(grouping: model.posts.filter { !$0.isArchived }, by: \.project) + } var body: some View { VStack(spacing: 0) { @@ -144,32 +158,51 @@ struct PostsLibraryColumn: View { .help("New Post") .accessibilityLabel("New Post") } - if model.posts.isEmpty { + if activeByProject.isEmpty { emptyState } else { ScrollView { LazyVStack(alignment: .leading, spacing: 4) { - ForEach(Post.PassState.allCases, id: \.self) { state in - let grouped = model.posts.filter { $0.passState == state } - if !grouped.isEmpty { - Text(state.rawValue.uppercased()) - .font(.system(size: 11, design: DesignTokens.mono)) - .kerning(0.6) - .foregroundStyle(DesignTokens.muted) - .padding(.horizontal, 14) - .padding(.top, 18) - .padding(.bottom, 7) - ForEach(grouped) { post in - PostRow(post: post, selected: post.id == model.selectedPostID) { - model.select(post.id, home: home) - } - .contextMenu { - Button("Rename…") { renamingPost = post } - Button("Move to Trash", role: .destructive) { - model.trash(post, home: home) - } + // #108 audit: Finder order (scan's own sort), not Unicode-scalar + // order — the heads render lowercased, "Beta" must not read before "apple". + ForEach(activeByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in + let pieces = activeByProject[project] ?? [] + // #108: the head is the prototype's toggle — click + // collapses the project's pieces (chevron rotates). + Button { + withAnimation { + if collapsed.contains(project) { + collapsed.remove(project) + } else { + collapsed.insert(project) } } + } label: { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: "chevron.down") + .font(.system(size: 9, weight: .semibold)) + .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) + .foregroundStyle(DesignTokens.muted) + Text(project) + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + .textCase(.lowercase) // #108: display-only — the folder name keeps its case + .lineLimit(1) + .truncationMode(.tail) + Text("· \(pieces.count)") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + Spacer(minLength: 0) + } + } + .buttonStyle(.plain) + .foregroundStyle(DesignTokens.foreground) + .accessibilityLabel("\(project), \(pieces.count) pieces") + .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") + .padding(.top, 16) + .padding(.horizontal, 14) + .padding(.bottom, 6) + if !collapsed.contains(project) { + passStateGroups(pieces) } } } @@ -183,6 +216,47 @@ struct PostsLibraryColumn: View { model.rename(post, to: title, home: home) } } + .sheet(item: $movingPost) { post in + // #108 audit 2: disk-derived list, localized-sorted — same order + // the library renders (Unicode-scalar sort split them), and it + // includes empty projects (a fresh New Project has no pieces yet — + // it must already be a move target). + MoveToProjectSheet(post: post, projects: model.moveTargets(home: home)) { project in + model.moveToProject(post, project: project, home: home) + } + } + } + + /// Pass-State groups inside one project (`.vB .group-label`: smaller, + /// softer, indented under the section head). + private func passStateGroups(_ pieces: [Post]) -> some View { + ForEach(Post.PassState.allCases, id: \.self) { state in + let grouped = pieces.filter { $0.passState == state } + if !grouped.isEmpty { + Text(state.rawValue.uppercased()) + .font(.system(size: 10, design: DesignTokens.mono)) + .kerning(0.6) + .foregroundStyle(DesignTokens.muted.opacity(0.8)) + .padding(.horizontal, 22) + .padding(.top, 8) + .padding(.bottom, 5) + ForEach(grouped) { post in + LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { + model.select(post.id, home: home) + } + .contextMenu { + Button("Rename…") { renamingPost = post } + Button("Move to Project…") { movingPost = post } + Button("Move to Archive") { + model.archivePost(post, home: home) + } + Button("Move to Trash", role: .destructive) { + model.trash(post, home: home) + } + } + } + } + } } private var emptyState: some View { @@ -199,8 +273,54 @@ struct PostsLibraryColumn: View { } } +/// #108: Move to Project ask — radio list of the non-archived projects, +/// default = the piece's current project. Matches RenamePostSheet's shape. +struct MoveToProjectSheet: View { + let post: Post + let projects: [String] + let move: (String) -> Void + @Environment(\.dismiss) private var dismiss + @State private var target: String + + init(post: Post, projects: [String], move: @escaping (String) -> Void) { + self.post = post + self.projects = projects + self.move = move + _target = State(initialValue: post.project) + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Move to Project") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text("“\(post.title)” moves into the chosen project. The file stays post.md.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + Picker("Project", selection: $target) { + ForEach(projects, id: \.self) { name in + Text(name).tag(name) + } + } + .pickerStyle(.radioGroup) + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Move") { + move(target) + dismiss() + } + .keyboardShortcut(.defaultAction) + .disabled(target == post.project) + } + } + .padding(20) + .frame(width: 360) + } +} + /// #60: Explicit Rename dialog — asks the new Title (not a slug). -private struct RenamePostSheet: View { +struct RenamePostSheet: View { let rename: (String) -> Void @Environment(\.dismiss) private var dismiss @State private var title: String @@ -242,44 +362,70 @@ private struct RenamePostSheet: View { } /// One post row per the export: title, Pass State + Origin in mono 11. -private struct PostRow: View { +/// #108 (variant B): 2px accent edge bar on the leading side when selected +/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`, +/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the +/// Archive pane reuses it. +struct LibraryPostRow: View { let post: Post let selected: Bool let select: () -> Void @State private var hover = false var body: some View { - Button(action: select) { - VStack(alignment: .leading, spacing: 5) { - Text(post.title) + // `.vB .post-row { border-left: 2px solid transparent; + // border-radius: 0 8px 8px 0 }` — every row: leading corners square + // (the 2px strip below), trailing rounded 8. Only the strip's COLOR + // changes on selection. + let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) + return Button(action: select) { + HStack(spacing: 0) { + // `.vB .post-row { border-left: 2px solid transparent }` — + // the leading strip is always 2px wide so hover/selection + // never shifts the title. + Rectangle() + .fill(selected ? DesignTokens.accent : .clear) + .frame(width: 2) + VStack(alignment: .leading, spacing: 5) { + HStack(alignment: .firstTextBaseline, spacing: 0) { + Text(post.title) + if post.type == .outline { + Text(" ✳") + .foregroundStyle(DesignTokens.muted) + } + } .font(.callout.weight(.semibold)) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) - HStack { - Text(post.passState.rawValue) - Text(post.origin.rawValue) + HStack { + Text(post.passState.rawValue) + Text(post.origin.rawValue) + } + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .frame(maxWidth: .infinity, alignment: .leading) } - .font(.system(size: 11, design: DesignTokens.mono)) - .foregroundStyle(DesignTokens.muted) - .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) } - .padding(10) + .clipShape(shape) } .buttonStyle(.plain) .foregroundStyle(DesignTokens.foreground) .background { if selected || hover { - RoundedRectangle(cornerRadius: DesignTokens.radius) + shape .fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) .overlay( - RoundedRectangle(cornerRadius: DesignTokens.radius) - .strokeBorder(selected ? DesignTokens.border : .clear), + shape.strokeBorder(selected ? DesignTokens.border : .clear), ) } } .padding(.horizontal, 8) .onHover { hover = $0 } + // help sits on the row — the ✳ span isn't individually hoverable in + // SwiftUI (prototype: `title="outline"` on the star). + .help(post.type == .outline ? "\(post.title) — outline" : post.title) .accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)") } } diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index e751338..8f4cb08 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -5,6 +5,8 @@ // #17 (S1.1): the workspace shell — nav rail + panes, built from the design // contract's grid geometry (ref/Web-Prototype/museion-workspace.html): // rail 56 | library 232 | editor min 420 | mentor 356. +// #108: the Archive rail destination (box icon, above Settings) + the +// New Project ask both live here. // import SwiftUI @@ -20,6 +22,10 @@ struct WorkspaceView: View { case posts case sessions case learnings + /// #108: the archive rail destination — archive/ as a first-class + /// pane (prototype variant B/C verdict: a destination, not a + /// library disclosure). + case archive case settings } @@ -72,6 +78,17 @@ struct WorkspaceView: View { gate.posts.importFiles(origin: origin, home: gate.museionHome) } } + // #108: File ▸ New Project… ask — commands can't present sheets, so + // the model stages and this window presents (OriginAsk pattern). + .sheet(isPresented: newProjectAskBinding) { + NewProjectSheet { name in + if let reason = gate.posts.createProject(named: name, home: gate.museionHome) { + return reason + } + gate.posts.newProjectPending(named: name) + return nil + } + } } // Collapsed floor: rail 56 + editor placeholder (export ≤920 layout). .frame(minWidth: 480, minHeight: 320) @@ -82,6 +99,13 @@ struct WorkspaceView: View { selection = .posts } } + // #108 audit: ⌘N/New Project open a DRAFT — session is nil, so the + // selectedPostID onChange below can't hop. Hop on the draft itself. + .onChange(of: gate.posts.draft != nil) { _, isDraft in + if isDraft { + selection = .posts + } + } .onChange(of: gate.posts.selectedPostID) { _, _ in if gate.posts.session != nil { selection = .posts @@ -101,6 +125,18 @@ struct WorkspaceView: View { ) } + /// #108: the New Project ask presents while staged. + private var newProjectAskBinding: Binding { + Binding( + get: { gate.posts.askNewProject }, + set: { + if !$0 { + gate.posts.cancelNewProject() + } + }, + ) + } + @ViewBuilder private func paneContent(_ geo: GeometryProxy) -> some View { @Bindable var gate = gate @@ -120,6 +156,12 @@ struct WorkspaceView: View { PlaceholderPane(title: "Sessions", detail: "Session lifecycle arrives with S2.3 (#28).") case .learnings: PlaceholderPane(title: "Learnings", detail: "Promote, consult, and decay arrive with S4 (#26, #27).") + case .archive: + // #108: list-only pane — clicking a row selects the piece and + // hops to Posts where its editor lives. + ArchivePaneView(home: gate.museionHome, model: gate.posts) { + selection = .posts + } case .settings: SettingsPaneView(home: $gate.museionHome) } @@ -146,6 +188,9 @@ struct WorkspaceView: View { RailButton(pane: .sessions, selection: $selection, label: "Sessions", systemImage: "bubble.left") RailButton(pane: .learnings, selection: $selection, label: "Learnings", systemImage: "cube") Spacer() + // #108: Archive at the rail bottom, above Settings (prototype's + // box icon). + RailButton(pane: .archive, selection: $selection, label: "Archive", systemImage: "archivebox") RailButton(pane: .settings, selection: $selection, label: "Settings", systemImage: "gearshape") } .padding(.horizontal, 4) @@ -155,6 +200,124 @@ struct WorkspaceView: View { } } +/// #108: the Archive pane — archive/ as a rail destination (prototype +/// verdict: a destination, not a library disclosure). List-only: clicking a +/// piece selects it and hops to Posts, where the editor column lives. +private struct ArchivePaneView: View { + let home: URL + var model: PostsModel + /// Fired after a row select — the pane can't reach WorkspaceView's + /// selection itself. + let onOpenPiece: () -> Void + @State private var renamingPost: Post? + /// #108: collapsed project sections — per-view state, not persisted + /// (mirrors the library column). + @State private var collapsed: Set = [] + + private var archivedByProject: [String: [Post]] { + Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project) + } + + /// #108: the prototype's toggle — click the project name (or chevron). + private func toggle(_ project: String) { + if collapsed.contains(project) { + collapsed.remove(project) + } else { + collapsed.insert(project) + } + } + + var body: some View { + VStack(spacing: 0) { + // No New button — things arrive here by being moved, not created. + PaneHeader(title: "Archive") + if archivedByProject.isEmpty { + emptyState + } else { + ScrollView { + LazyVStack(alignment: .leading, spacing: 4) { + // #108 audit: Finder order, matching the library's sort. + ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in + let pieces = archivedByProject[project] ?? [] + // Same section-head shape as the library (#108 + // variant B), plus the project-level way out. + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: "chevron.down") + .font(.system(size: 9, weight: .semibold)) + .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) + .foregroundStyle(DesignTokens.muted) + .onTapGesture { + withAnimation { toggle(project) } + } + .accessibilityLabel("Toggle \(project)") + .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") + Text(project) + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + .textCase(.lowercase) // #108: display-only — the folder name keeps its case + .lineLimit(1) + .truncationMode(.tail) + .onTapGesture { + withAnimation { toggle(project) } + } + Text("· \(pieces.count)") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + Spacer(minLength: 0) + Button("Unarchive") { + model.unarchiveProject(project, home: home) + } + .buttonStyle(.plain) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .help("Move the whole project back to projects/") + .accessibilityLabel("Unarchive \(project)") + } + .padding(.top, 16) + .padding(.horizontal, 14) + .padding(.bottom, 6) + if !collapsed.contains(project) { + ForEach(pieces) { post in + LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { + model.select(post.id, home: home) + onOpenPiece() + } + .contextMenu { + Button("Move Back to \(post.project)") { + model.restorePost(post, home: home) + } + Button("Rename…") { renamingPost = post } + } + } + } + } + } + .padding(.bottom, 12) + } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(DesignTokens.background) + .sheet(item: $renamingPost) { post in + RenamePostSheet(post: post) { title in + model.rename(post, to: title, home: home) + } + } + } + + private var emptyState: some View { + VStack(spacing: 8) { + Text("Nothing archived") + .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) + Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + .multilineTextAlignment(.center) + } + .padding(38) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + /// #94: the ONE Origin ask per import batch — writer (default) / ai, with the /// immutability line (CONTEXT.md: Origin). Answering runs the batch. private struct OriginAskSheet: View { @@ -196,6 +359,56 @@ private struct OriginAskSheet: View { } } +/// #108: New Project ask — the sheet behind File ▸ New Project… (and any +/// future materialize path). Create runs through the model's raw op; the +/// thrown reason is shown inline and the sheet stays up. +private struct NewProjectSheet: View { + /// Create + open a draft in it; nil = success, a string = the failure + /// reason to show inline (keeps the sheet up). + let create: (String) -> String? + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var failure: String? + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("New Project") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text("Pieces land here when it's selected.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + TextField("Name", text: $name) + .textFieldStyle(.roundedBorder) + .onSubmit { confirm() } + if let failure { + Text(failure) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.accent) + } + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Create", action: confirm) + .keyboardShortcut(.defaultAction) + .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding(20) + .frame(width: 360) + } + + private func confirm() { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + if let reason = create(trimmed) { + failure = reason + } else { + dismiss() + } + } +} + /// Rail button per the export: 44×44 muted icon, hover wash, and the current /// pane raised as a surface card with a 2px selection bar on the rail's edge. private struct RailButton: View { diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index ddd1585..2cc01e9 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -21,7 +21,8 @@ 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 `/profiles/` (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///` + `archive///` (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///` + #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. +- `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///` + #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. **#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) — 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). - `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 `

    `, 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. diff --git a/MuseionTests/EditorSessionTests.swift b/MuseionTests/EditorSessionTests.swift index 3221050..9eae22e 100644 --- a/MuseionTests/EditorSessionTests.swift +++ b/MuseionTests/EditorSessionTests.swift @@ -39,7 +39,12 @@ struct EditorSessionTests { session.edit("# Alpha\n\nOne. Two.") #expect(session.saveState == .changed) // #83: dirty shows while the debounce holds - try await Task.sleep(for: .milliseconds(200)) + // Await the flush rather than sleeping a fixed window — under suite + // load the main actor can starve the debounce Task past any constant. + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while session.saveState != .saved, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(20)) + } #expect(session.saveState == .saved) // Changed → flush → Saved lands here #expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.") diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index cb969e3..284231c 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -6,6 +6,7 @@ // projects/ and archive/, writeNew re-rooted to projects///, // the #59 stamp with type first, rename = retitle + move within the same // project (#60), Trash delete, save-time normalization. +// #108: project moves, archive/restore, project unarchive + creation. // import Foundation @@ -289,3 +290,205 @@ private func readPost(_ home: URL, _ id: String) throws -> String { _ = try PostStore.writeNew(body: "# Blocked\n", home: home) } } + +// MARK: Project moves & archive (#108) + +/// readPost's path-aware sibling: any piece under any root/project. +private func readPiece(_ home: URL, root: String, project: String, _ id: String) throws -> String { + try String( + contentsOf: home.appendingPathComponent("\(root)/\(project)/\(id)/post.md", isDirectory: false), + encoding: .utf8, + ) +} + +@Test func `move sends piece to another project`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Traveler\n\nBody.", project: "essays", home: home) + let original = try readPiece(home, root: "projects", project: "essays", post.id) + + try PostStore.move(post, to: "posts", home: home) + + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/\(post.id)").path)) + #expect(try readPiece(home, root: "projects", project: "posts", post.id) == original) // bytes untouched + let scanned = try #require(Post.scan(home: home).first) + #expect(scanned.project == "posts") + #expect(!scanned.isArchived) + + // Same-project confirm in the picker is a no-op, not a "file exists" error. + try PostStore.move(post, to: "posts", home: home) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path)) +} + +@Test func `archive and restore round-trip a piece`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Round Trip\n", home: home) + + try PostStore.archive(post, home: home) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/posts/\(post.id)/post.md").path)) + var scanned = try #require(Post.scan(home: home).first) + #expect(scanned.isArchived) + #expect(scanned.project == "posts") + + try PostStore.restore(post, home: home) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path)) + scanned = try #require(Post.scan(home: home).first) + #expect(!scanned.isArchived) + #expect(scanned.project == "posts") +} + +@Test func `move refuses an archived piece`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# No Escape\n", home: home) + try PostStore.archive(post, home: home) + #expect(throws: CocoaError(.featureUnsupported)) { + try PostStore.move(post, to: "essays", home: home) + } + // Still where archive left it. + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/posts/\(post.id)/post.md").path)) +} + +@Test func `unarchiveProject moves the whole project folder`() throws { + let home = try storeHome { home in + try FileManager.default.createDirectory( + at: home.appendingPathComponent("archive/awards/laurel", isDirectory: true), + withIntermediateDirectories: true, + ) + try "# Laurel\n".write( + to: home.appendingPathComponent("archive/awards/laurel/post.md"), + atomically: true, + encoding: .utf8, + ) + } + + try PostStore.unarchiveProject("awards", home: home) + + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/laurel/post.md").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards").path)) + let scanned = try #require(Post.scan(home: home).first) + #expect(scanned.id == "laurel") + #expect(scanned.project == "awards") + #expect(!scanned.isArchived) +} + +@Test func `unarchiveProject merges when the project exists`() throws { + let home = try storeHome { home in + for path in ["projects/awards/kept", "archive/awards/back"] { + try FileManager.default.createDirectory( + at: home.appendingPathComponent(path, isDirectory: true), + withIntermediateDirectories: true, + ) + try "# Piece\n".write( + to: home.appendingPathComponent("\(path)/post.md"), + atomically: true, + encoding: .utf8, + ) + } + } + + try PostStore.unarchiveProject("awards", home: home) + + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/kept/post.md").path)) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/back/post.md").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards").path)) + #expect(Post.scan(home: home).count == 2) + #expect(Post.scan(home: home).allSatisfy { !$0.isArchived && $0.project == "awards" }) +} + +@Test func `unarchiveProject skips finder dotfiles in the merge`() throws { + let home = try storeHome { home in + for path in ["projects/awards/kept", "archive/awards/back"] { + try FileManager.default.createDirectory( + at: home.appendingPathComponent(path, isDirectory: true), + withIntermediateDirectories: true, + ) + try "# Piece\n".write( + to: home.appendingPathComponent("\(path)/post.md"), + atomically: true, + encoding: .utf8, + ) + // Finder drops these when it browses a folder. + try "junk".write( + to: home.appendingPathComponent("\(path)/.DS_Store"), + atomically: true, + encoding: .utf8, + ) + } + } + + try PostStore.unarchiveProject("awards", home: home) + + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/back/post.md").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards").path)) // the .DS_Stores didn't wedge it open + #expect(Post.scan(home: home).count == 2) +} + +@Test func `unarchiveProject keeps hidden user folders instead of destroying them`() throws { + // removeItem is permanent — a Finder-hidden folder inside the archived + // project must survive the unarchive, not die with the emptied source. + let home = try storeHome { home in + for path in ["projects/awards/kept", "archive/awards/back"] { + try FileManager.default.createDirectory( + at: home.appendingPathComponent(path, isDirectory: true), + withIntermediateDirectories: true, + ) + try "# Piece\n".write( + to: home.appendingPathComponent("\(path)/post.md"), + atomically: true, + encoding: .utf8, + ) + } + try FileManager.default.createDirectory( + at: home.appendingPathComponent("archive/awards/.research", isDirectory: true), + withIntermediateDirectories: true, + ) + } + + try PostStore.unarchiveProject("awards", home: home) + + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/back/post.md").path)) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards/.research").path)) // survived +} + +@Test func `slug collisions fold unicode normalization`() throws { + // Decomposed-jamo folder on disk vs a precomposed title — one folder to + // normalization-insensitive APFS; the fold makes the -2 fire instead of + // the TOCTOU guard surfacing a baffling "file exists". + let decomposed = "한국".decomposedStringWithCanonicalMapping + let home = try storeHome { home in + try FileManager.default.createDirectory( + at: home.appendingPathComponent("projects/posts/\(decomposed)", isDirectory: true), + withIntermediateDirectories: true, + ) + } + #expect(!decomposed.utf8.elementsEqual("한국".utf8)) // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract + #expect(PostStore.availableSlug(for: "한국", home: home) == "한국-2") +} + +@Test func `createProject materializes and validates`() throws { + let home = try storeHome() + + try PostStore.createProject(named: "foo", home: home) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/foo").path)) + + #expect(throws: CocoaError(.fileWriteFileExists)) { + try PostStore.createProject(named: "FOO", home: home) // case-insensitive duplicate + } + // #108 audit 2: NFD duplicate — "café" typed/pasted decomposed reads + // identical but is one folder on normalization-insensitive APFS. + try PostStore.createProject(named: "café", home: home) // NFC variant first + #expect(throws: CocoaError(.fileWriteFileExists)) { + try PostStore.createProject(named: "cafe\u{0301}", home: home) // NFD twin + } + #expect(throws: CocoaError(.fileWriteInvalidFileName)) { + try PostStore.createProject(named: "a:b", home: home) // Finder shows ":" as "/" + } + #expect(throws: CocoaError(.fileWriteInvalidFileName)) { + try PostStore.createProject(named: " ", home: home) // empty after trimming + } + #expect(throws: CocoaError(.fileWriteInvalidFileName)) { + try PostStore.createProject(named: "a/b", home: home) // path separator + } + #expect(throws: CocoaError(.fileWriteInvalidFileName)) { + try PostStore.createProject(named: ".x", home: home) // hidden — scan skips dot-dirs + } +} diff --git a/MuseionTests/PostsModelTests.swift b/MuseionTests/PostsModelTests.swift new file mode 100644 index 0000000..3236977 --- /dev/null +++ b/MuseionTests/PostsModelTests.swift @@ -0,0 +1,121 @@ +// +// PostsModelTests.swift +// MuseionTests +// +// #108 audit: the model-layer lifecycle the store tests can't see — +// archive clearing the open session, move reopening it at the new parent, +// restore keeping the writer in the piece, New Project's draft targeting. +// + +import Foundation +@testable import Museion +import Testing + +/// Throwaway Home + model (EditorSessionTests convention: direct @MainActor +/// instantiation, no app gate). +@MainActor +private func makeModelHome() throws -> (PostsModel, URL) { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("postsmodel-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + let model = PostsModel() + model.bind(home: home) + return (model, home) +} + +@Test @MainActor func `archiving the open piece clears selection and session`() throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home) + model.select(post.id, home: home) + #expect(model.session?.postID == post.id) + + model.archivePost(post, home: home) + + #expect(model.selectedPostID == nil) + #expect(model.session == nil) + #expect(model.lastError == nil) + #expect(Post.scan(home: home).first?.isArchived == true) +} + +@Test @MainActor func `moving the open piece reopens its session at the new parent`() throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Traveler\n", project: "essays", home: home) + model.select(post.id, home: home) + #expect(model.session?.folderURL.path.contains("projects/essays") == true) + + model.moveToProject(post, project: "posts", home: home) + + #expect(model.session?.postID == post.id) // same piece, fresh session + #expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true) + #expect(model.lastError == nil) +} + +@Test @MainActor func `restore reopens the session off the archive path`() throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Revived\n", home: home) + try PostStore.archive(post, home: home) + model.select(post.id, home: home) // opened from the Archive pane + #expect(model.session?.folderURL.path.contains("archive/") == true) + + model.restorePost(post, home: home) + + #expect(model.selectedPostID == post.id) // the writer stays in it + #expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true) + #expect(model.lastError == nil) +} + +@Test @MainActor func `new project draft lands in the named project`() throws { + let (model, home) = try makeModelHome() + try PostStore.createProject(named: "essays", home: home) + + model.newProjectPending(named: "essays") + #expect(model.draft?.project == "essays") + + model.updateDraft("# Fresh\n") + model.saveDraft(home: home) + + let scanned = Post.scan(home: home) + #expect(scanned.first?.project == "essays") + #expect(scanned.first?.id == "fresh") +} + +@Test @MainActor func `abandoning the draft for an external file drops the pending target`() throws { + let (model, home) = try makeModelHome() + try PostStore.createProject(named: "essays", home: home) + model.newProjectPending(named: "essays") + #expect(model.draft?.project == "essays") + + // The external guest takes the column; the draft dies — its target must too. + let external = home.appendingPathComponent("outside.md") + try "# foreign\n".write(to: external, atomically: true, encoding: .utf8) + model.openExternal(external) + + #expect(model.draft == nil) + model.newPost() + #expect(model.draft?.project == Post.defaultProject) // not the abandoned essays +} + +@Test @MainActor func `unarchive flushes the dirty open piece before moving`() throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Keeper\n", home: home) + try PostStore.archive(post, home: home) + model.select(post.id, home: home) + model.session?.edit("# Keeper\n\nDirty.") // inside the debounce window + + model.unarchiveProject("posts", home: home) + + // The edits landed on disk (readBody resolves by id — through the move). + #expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nDirty.") + #expect(model.lastError == nil) + // The reopen swapped in a fresh session over the same piece. + #expect(model.session?.postID == post.id) + #expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true) +} + +@Test @MainActor func `moveTargets lists empty projects from disk`() throws { + let (model, home) = try makeModelHome() + try PostStore.createProject(named: "essays", home: home) // empty — no pieces + + #expect(model.moveTargets(home: home) == ["essays", "posts"]) + // "posts" exists too (bind created it); a dot-project never shows. +} diff --git a/docs/devlog/20261013-issue108-library-ui-archive-audits_log.md b/docs/devlog/20261013-issue108-library-ui-archive-audits_log.md new file mode 100644 index 0000000..6c7b228 --- /dev/null +++ b/docs/devlog/20261013-issue108-library-ui-archive-audits_log.md @@ -0,0 +1,87 @@ +# Issue #108 — Library UI S2 (projects, archive, commands) + two audit rounds + +> **Date:** 2026-10-13 +> **Type:** issue +> **Reference:** Museion #108 (child of wayfinder map #97), prototype verdict #104 (variant B) + +## Goal + +Ship #108: the variant-B library UI — project-grouped library with section heads, the Archive rail pane, move/archive/restore/unarchive/createProject ops across PostStore + PostsModel, New Post/New Project commands — then harden it with reviewer fanouts and close every finding. + +## What Was Done + +**Core implementation (#108, variant B per #104):** +- `PostStore` (nonisolated): `move` / `archive` / `restore` / `unarchiveProject` / `createProject` over private `relocate` — pure folder moves, post.md bytes never rewritten; `validatedProject` (empty/slash/dot rejected, later +`:`/control-chars); never-clobber guards throughout. +- `PostsModel`: `pendingProject`/`targetProject`, `moveToProject`, `archivePost`, `restorePost`, `unarchiveProject`, `createProject`, `stageNewProject`/`cancelNewProject`/`askNewProject`, `newProjectPending`. +- UI: serif-15 semibold lowercase project heads + mono-11 `· N` counts, Pass-State groups inside, collapse toggle (chevron rotation, per-view state), 2px rust edge-bar selection on `LibraryPostRow` (extracted, shared with Archive), ✳ on outlines; `ArchivePaneView` (rail destination, Unarchive per project, Move Back per piece, row-click hops to Posts); File ▸ New Post ⌘N + New Project… ⌥⌘N via `CommandGroup(after: .newItem)` — never `CommandMenu("File")` (#84 trap). + +**Audit round 1 (three-reviewer fanout, 10 fixes):** +- `EditorSession.flush()` → `@discardableResult Bool`; `flushOrAbort` in PostsModel — move/archive/restore abort when a write fails ("nothing was moved"). +- Dotfile skip in `unarchiveProject` merge (.DS_Store wedged unarchive forever). +- Draft pane-hop `onChange(of: draft != nil)` in WorkspaceView. +- Session reopen after `restorePost`/`unarchiveProject` (stale `folderURL`). +- NFD/NFC duplicate guard in `createProject` → shared `folded(_:)` (NFC + lowercase). +- `openExternal` clears `pendingProject`; `localizedStandardCompare` project sort in both panes; deleted dead `clearPendingProject` + `moveTargets` property (later reborn as a function, see audit 2); new `PostsModelTests.swift` (5 tests). + +**Fold follow-up:** `availableSlug` compares through `folded` (taken-set build, own-ID exclusion, suffix loop); rewrote the fold test to decomposed-jamo-vs-precomposed (`한국-2`); a Swift probe proved Swift `==`/Set hashing already fold canonical equivalence — the original "Set lookups don't fold" rationale was wrong and all doc text was corrected (the `folded` key stays as the explicit, tested contract; lowercase is the load-bearing half). + +**Audit round 2 (three-reviewer fanout over the post-audit tree, 12 accepted findings):** +- **HIGH:** `unarchiveProject` skipped the flush gate (flagged by 2 reviewers) → gate added, disk-derived membership via `folder(of:)`, captured BEFORE the move (after it, archive membership is invisible). +- **MEDIUM:** `rename` ignored flush failure and `lastError = nil` erased the signal → `flushOrAbort` gate. +- **MEDIUM:** `unarchiveProject`'s `removeItem` permanently destroyed hidden children (`.git/`, `.research/`) → source removed only when the loop emptied it. +- **MEDIUM:** empty projects unreachable as move targets + Unicode-scalar sort in the picker → `moveTargets(home:)` — disk listing + default project, localized-sorted. +- Stale-snapshot trust in `move`/`archive`/`restore` (`post.project`, `isArchived` flag) → all derive from the freshly resolved disk path; the archived-refusal in `move` now derives from the resolved path too. +- Ops return Void (nobody consumed the `Post` returns); `createProject(named:) -> String?` with the failure reason inline in the sheet (no double-message into `lastError`); `flushOrAbort` appends "— nothing was moved." instead of replacing the flush-routed reason; `validatedProject` rejects `:`/control chars; stale `availableSlug` doc block deleted; `folder(of:)` comment corrected (piece-level check resolves symlinks); 4 new tests + fixed the `debounce flushes` suite flake (wall-clock sleep → bounded await). + +**Verification:** full suite green at every stage — 134 → 139 → 140 → 141 → 144 (run twice consecutively at the end); swiftformat/swiftlint clean on all touched files; GitNexus re-indexed (2,654 nodes / 7,109 edges / 192 flows). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Variant B library layout | #104 prototype verdict — measured A/B/C, B won | +| Project heads render lowercase via `.textCase(.lowercase)` | Live user verdict; small caps tried and rejected — "don't work as UI element for projects" (folder keeps its case) | +| Archive head keeps two tap targets (chevron + name), no whole-head Button | Live verdict: the Unarchive button shares the row and must not be swallowed; only the missing a11y hint was added | +| Section collapse = per-view `@State`, not persisted | Prototype behavior; a fresh open shows everything | +| `folded` stays despite behavioral redundancy for NFC/NFD | Explicit tested contract; lowercase half is load-bearing (APFS case-insensitivity); deleting it saves 3 lines and loses the pin | +| Ops return Void | Only tests consumed the returns and they assert the same facts via `Post.scan`; rescan re-derives posts from disk | +| Disk-derived state over scan snapshots everywhere | A Finder-side move between scan and click must not misfile pieces or smuggle archived pieces back into projects/ | +| Flush gate before every folder move (incl. rename, unarchive) | The move succeeds exactly when a file write fails; text must land before the folder moves | +| `debounce flushes` test rewritten to bounded await | Flaked twice in one day under suite load — fixed 200 ms sleep starves when the main actor is busy | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Fold test failed: `#expect(decomposed != "한국")` | Swift `==` folds canonical equivalence — NFD/NFC compare equal | Premise pinned on byte inequality: `utf8.elementsEqual` | +| "Passes isolated" was a phantom | `-only-testing:` on a free `@Test` function (no suite class) ran ZERO tests and still said TEST SUCCEEDED | Read the pass count, not just the verdict; use xcresulttool for failure text | +| Unarchive-flush test failed in suite | Two bugs in my helper: one `deletingLastPathComponent()` too many (compared the home folder's name against "archive"), and membership re-evaluated after the move when it's already invisible | Correct depth (dir−1 = project dir, dir−2 = root); membership captured before the move | +| `move refuses an archived piece` failed after the Void cut | Refusal trusted the snapshot `isArchived` flag; test passed the original struct | Refusal derives from the resolved disk path | +| patch tool mangled these files repeatedly (eaten declaration lines, duplicated functions, mangled MARK) | Fuzzy matching on long structurally-similar regions | Always `read_file` to verify after patching; re-read before retrying | +| Reviewers re-litigated a settled live verdict (Archive head shape) | I under-briefed the exclusion list | Keep the adjudicated shape; add exclusion items as they're ruled | +| Security reviewer's doc note contradicted my fold rationale | My claim "Set lookups don't fold" was wrong — probe proved hashes are canonical-consistent | Corrected all rationale text in code comments, tests, AGENTS.md | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostStore.swift` | #108 ops + `relocate` + `validatedProject` + `folded` + disk-derived paths + Void returns + remove-only-when-empty | +| `Museion/PostsModel.swift` | project ops, `flushOrAbort` everywhere, `moveTargets`, `createProject -> String?`, disk-derived unarchive membership | +| `Museion/PostsPaneView.swift` | variant-B library column, `LibraryPostRow`, `MoveToProjectSheet`, `RenamePostSheet` | +| `Museion/WorkspaceView.swift` | Archive rail destination + `ArchivePaneView`, New Project ask, draft pane-hop | +| `Museion/MuseionApp.swift` | ⌘N / ⌥⌘N commands | +| `Museion/EditorSession.swift` | `flush() -> Bool` | +| `MuseionTests/PostStoreTests.swift` | #108 op tests, fold pin, hidden-folder survival, NFD twin, `:` rejection | +| `MuseionTests/PostsModelTests.swift` | new — model lifecycle tests incl. unarchive flush gate + moveTargets | +| `MuseionTests/EditorSessionTests.swift` | debounce test de-flaked | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass — contracts, tests, fold rationale corrected | + +## Open Items & Next Steps + +- [ ] Empty projects remain invisible in the library sections (they appear in the move picker now) — product-copy question, later slice +- [ ] Unarchive mid-loop rollback stays parked (adjudicated: throws honestly on genuine duplicate ids) +- [ ] ⌘N may be shadowed by the stock new-window item on some builds (menu item always fires) — known, watching + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index ec94eaa..5fc206b 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 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-12 | issue | [20261012-issue22-import-external_log.md](20261012-issue22-import-external_log.md) | #22 import & external markdown: SessionTarget, guest slot, Origin ask, drag-drop — full suite green | | 2026-10-09 | issue | [20261009-issue87-focus-mode_log.md](20261009-issue87-focus-mode_log.md) | #87 focus mode landed + audit fixes + ⌥⌘F shortcut; calibration gate #88 next |