diff --git a/AGENTS.md b/AGENTS.md index 1e5b1f6..cce2c5b 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** (2485 symbols, 6551 relationships, 161 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +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. > 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-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) | | 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e110dd..851caf6 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 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 - **editor:** M1 editor core (PRD S1.2) — posts open into a native TextKit2 editing surface (ADR-0010 mode B): styled source with scaled headings, paragraph spacing, and dimmed markdown syntax lifted from the proven spike; ~1 s debounced autosave with flush on selection change, window close, and app quit (⌘S stays immediate); an honest save-state dot — Changed while edits pend, Saved when clean, accent on failure (#83); cursor position and scroll restored across restarts via a per-post `.museion-state.json` sidecar that dies with the folder on Trash; and an explicit "File on Disk changed — Reload / Keep Local" alert on external edits, never a silent clobber (issue #19) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 05b9e86..490d911 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -23,10 +23,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `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. -- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts//post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). -- `PostStore.swift` — #18 write side (nonisolated): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:home:)` (copy never move; 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 `pass_state`/`origin` set-overwritten via `mergedFrontmatter`; absent keys inserted before the closing `---`; empty block → fresh #59 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); 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 `posts/`, 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 `posts/` 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. -- 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/folderURL computed per target; 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 posts/ 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 `posts//.museion-state.json` — 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). +- `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. +- 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. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `
    ` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
    diff --git a/Museion/EditorSession.swift b/Museion/EditorSession.swift
    index 7b6950f..d4ba49a 100644
    --- a/Museion/EditorSession.swift
    +++ b/Museion/EditorSession.swift
    @@ -52,18 +52,12 @@ final class EditorSession {
     		return nil
     	}
     
    -	/// The document's folder — `posts//` for posts (image resolution
    -	/// #71); the external file's containing folder, so relative images
    -	/// resolve beside the file.
    -	var folderURL: URL {
    -		switch target {
    -		case let .post(id, home):
    -			home.appendingPathComponent("posts", isDirectory: true)
    -				.appendingPathComponent(id, isDirectory: true)
    -		case let .externalFile(url):
    -			url.deletingLastPathComponent()
    -		}
    -	}
    +	/// The document's folder — the piece's resolved folder under projects/
    +	/// or archive/ for posts (image resolution #71; resolved once at init,
    +	/// ADR-0012 — a vanished piece still needs some path, so an unresolvable
    +	/// id falls back to the default-project path); the external file's
    +	/// containing folder, so relative images resolve beside the file.
    +	private(set) var folderURL: URL
     
     	/// Current body text (live, per keystroke).
     	private(set) var text: String
    @@ -101,6 +95,15 @@ final class EditorSession {
     	init(target: SessionTarget, debounce: Duration = .seconds(1)) {
     		self.target = target
     		self.debounce = debounce
    +		switch target {
    +		case let .post(id, home):
    +			folderURL = PostStore.folder(of: id, home: home)
    +				?? home.appendingPathComponent("projects", isDirectory: true)
    +				.appendingPathComponent(Post.defaultProject, isDirectory: true)
    +				.appendingPathComponent(id, isDirectory: true)
    +		case let .externalFile(url):
    +			folderURL = url.deletingLastPathComponent()
    +		}
     		let read = Self.readDocument(target)
     		loadFailed = read == nil
     		let body = read ?? ""
    @@ -128,7 +131,9 @@ final class EditorSession {
     			return PostStore.readBody(id: id, home: home)
     		case let .externalFile(url):
     			guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
    -			if text.hasPrefix("\u{FEFF}") { text.removeFirst() }
    +			if text.hasPrefix("\u{FEFF}") {
    +				text.removeFirst()
    +			}
     			return text.replacingOccurrences(of: "\r\n", with: "\n")
     		}
     	}
    diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift
    index 6cd00a9..28ddb07 100644
    --- a/Museion/PostEditorView.swift
    +++ b/Museion/PostEditorView.swift
    @@ -247,8 +247,8 @@ struct PostEditorView: View {
     				// the same muted mono style.
     				return fileURL.lastPathComponent
     			}
    -			if let id = session.postID {
    -				return "posts / \(id) / post.md"
    +			if session.postID != nil {
    +				return "\(session.folderURL.pathComponents.suffix(4).joined(separator: " / "))"
     			}
     		}
     		return "unsaved draft — no folder until first save"
    diff --git a/Museion/PostLibrary.swift b/Museion/PostLibrary.swift
    index 23fcce7..5a9a932 100644
    --- a/Museion/PostLibrary.swift
    +++ b/Museion/PostLibrary.swift
    @@ -3,13 +3,18 @@
     //  Museion
     //
     //  #17 (S1.1): the Posts list mirrors what is on disk under the Museion Home.
    +//  #107 (ADR-0012): pieces live under projects/// and
    +//  archive/// — both roots are scanned.
     //
     
     import Foundation
     
    -/// One Post on disk: `/posts//post.md` (ADR-0004 shape).
    +/// One Post on disk: `/{projects|archive}///post.md`
    +/// (ADR-0012 shape; the folder name under either root is the project).
     nonisolated struct Post: Identifiable, Equatable {
     	/// The post folder's name — the Post's durable identity (CONTEXT.md).
    +	/// Unique across projects AND archive: the slug namespace is global
    +	/// (ADR-0012), so the id alone resolves the folder.
     	let id: String
     	/// The Post's Title: first non-empty line after any frontmatter, heading markers stripped.
     	var title: String
    @@ -17,6 +22,19 @@ nonisolated struct Post: Identifiable, Equatable {
     	var passState: PassState
     	/// Origin from frontmatter; writer when absent. Immutable once set (CONTEXT.md).
     	var origin: Origin
    +	/// Content Type from frontmatter `type` (#107); post when absent.
    +	var type: ContentType
    +	/// The containing folder's name under projects/ or archive/ (#107).
    +	var project: String
    +	/// True when the piece lives under archive/ (#107).
    +	var isArchived: Bool
    +
    +	/// New pieces land here when no project is selected (#107).
    +	static let defaultProject = "posts"
    +
    +	/// The two roots that hold pieces, in resolution order (#107): projects/
    +	/// is searched before archive/.
    +	static let containerRoots = ["projects", "archive"]
     
     	nonisolated enum PassState: String, Equatable, CaseIterable {
     		case firstDraft = "First Draft"
    @@ -31,33 +49,60 @@ nonisolated struct Post: Identifiable, Equatable {
     		case ai
     	}
     
    -	/// Reads every `posts//post.md` into Posts (sorted by title, Finder order).
    -	/// Read-only for #17 — create/rename/delete round-trips are #18. Symlinks and
    -	/// hidden dirs are skipped; folders without `post.md` (lazy) aren't Posts;
    -	/// a malformed folder can't crash the list.
    -	static func scan(home: URL) -> [Post] {
    -		let postsURL = home.appendingPathComponent("posts", isDirectory: true)
    -		guard let entries = try? FileManager.default.contentsOfDirectory(
    -			at: postsURL,
    -			includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
    -		) else { return [] }
    +	nonisolated enum ContentType: String {
    +		case post
    +		case outline
    +	}
     
    +	/// Reads every `///post.md` (roots: projects/, then
    +	/// archive/ — ADR-0012) into Posts (sorted by title, Finder order).
    +	/// Same skip rules at both levels: symlinks, hidden dirs, loose files;
    +	/// folders without `post.md` (lazy) aren't Posts; a malformed folder
    +	/// can't crash the list. Read-only for #17.
    +	static func scan(home: URL) -> [Post] {
     		var posts: [Post] = []
    -		for dir in entries {
    -			let values = try? dir.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
    -			guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
    -			      !dir.lastPathComponent.hasPrefix(".") else { continue }
    -			let fileURL = dir.appendingPathComponent("post.md")
    -			guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { continue }
    -			let frontmatter = frontmatter(of: text)
    -			posts.append(
    -				Post(
    -					id: dir.lastPathComponent,
    -					title: title(of: text),
    -					passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
    -					origin: Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer,
    -				),
    -			)
    +		// #107 audit: duplicate ids can appear on disk (Finder copy across
    +		// projects, partial restore) — first-wins dedupe, in the SAME
    +		// projects-before-archive, name-sorted order folder(of:) resolves
    +		// by, so the row shown is always the piece written. Later twins are
    +		// invisible until renamed in Finder.
    +		var seen: Set = []
    +		for root in containerRoots {
    +			let isArchived = root == "archive"
    +			let rootURL = home.appendingPathComponent(root, isDirectory: true)
    +			guard let projects = try? FileManager.default.contentsOfDirectory(
    +				at: rootURL,
    +				includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
    +			) else { continue }
    +			for projectDir in projects.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
    +				let values = try? projectDir.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
    +				guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
    +				      !projectDir.lastPathComponent.hasPrefix(".") else { continue }
    +				guard let entries = try? FileManager.default.contentsOfDirectory(
    +					at: projectDir,
    +					includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
    +				) else { continue }
    +				for dir in entries.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
    +					let pieceValues = try? dir.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
    +					guard pieceValues?.isDirectory ?? false, !(pieceValues?.isSymbolicLink ?? false),
    +					      !dir.lastPathComponent.hasPrefix(".") else { continue }
    +					let fileURL = dir.appendingPathComponent("post.md")
    +					guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { continue }
    +					guard seen.insert(dir.lastPathComponent).inserted else { continue }
    +					let frontmatter = frontmatter(of: text)
    +					posts.append(
    +						Post(
    +							id: dir.lastPathComponent,
    +							title: title(of: text),
    +							passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
    +							origin: Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer,
    +							type: ContentType(rawValue: frontmatter["type"] ?? "") ?? .post,
    +							project: projectDir.lastPathComponent,
    +							isArchived: isArchived,
    +						),
    +					)
    +				}
    +			}
     		}
     		return posts.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
     	}
    diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift
    index 58ed538..6c0c7bc 100644
    --- a/Museion/PostStore.swift
    +++ b/Museion/PostStore.swift
    @@ -5,6 +5,8 @@
     //  #18 (S1.1): the write side of the Post lifecycle — slug naming, lazy folder
     //  materialization on first write, frontmatter stamping (#59), Explicit Rename
     //  = retitle + move (#60), Trash delete. Pure disk operations, no UI state.
    +//  #107 (ADR-0012): pieces live under projects/// (archive/
    +//  mirrors the shape); the slug namespace is global across both roots.
     //
     
     import Foundation
    @@ -13,6 +15,8 @@ import UniformTypeIdentifiers
     /// Write-side Post lifecycle (#18 map decisions #59/#60). One canonical write
     /// path: every file that leaves here carries the flat frontmatter block the
     /// #17 reader already parses. #22: import copies external markdown in (#94/#95).
    +/// #107: the Piece ID is the durable identity — write paths resolve the folder
    +/// from the id by searching both roots; nothing threads (project, id) around.
     nonisolated enum PostStore {
     	/// #96: .md/.markdown only — every entry point (Open panel, Import panel,
     	/// drag-drop filter) shares this list.
    @@ -28,6 +32,38 @@ nonisolated enum PostStore {
     
     	private static let markdownExtensions = ["md", "markdown"]
     
    +	/// ADR-0012 id→folder resolution: the id is globally unique, so the
    +	/// folder is found by searching the container roots in order (projects/
    +	/// before archive/, project names sorted for determinism). nil when the
    +	/// id lives under neither root.
    +	// ponytail: linear walk of projects/ then archive/ per call — one
    +	// debounced flush = 2–3 walks (overwrite + sidecar). Fine at human
    +	// 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.
    +	static func folder(of id: String, home: URL) -> URL? {
    +		for root in Post.containerRoots {
    +			let rootURL = home.appendingPathComponent(root, isDirectory: true)
    +			guard let projects = try? FileManager.default.contentsOfDirectory(
    +				at: rootURL,
    +				includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
    +			) else { continue }
    +			for project in projects.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
    +				let values = try? project.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
    +				guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
    +				      !project.lastPathComponent.hasPrefix(".") else { continue }
    +				let dir = rootURL.appendingPathComponent(project.lastPathComponent, isDirectory: true)
    +					.appendingPathComponent(id, isDirectory: true)
    +				var isDir: ObjCBool = true
    +				if FileManager.default.fileExists(atPath: dir.path, isDirectory: &isDir), isDir.boolValue {
    +					return dir
    +				}
    +			}
    +		}
    +		return nil
    +	}
    +
     	/// The shared slug function (#60): lowercase, diacritic-fold, strip
     	/// punctuation, whitespace runs → single hyphens, keep CJK, cap 80.
     	/// A slugless title (blank, punctuation-only) is `untitled` (CONTEXT.md).
    @@ -56,14 +92,34 @@ nonisolated enum PostStore {
     	}
     
     	/// First free slug for a title: base slug, then `-2`, `-3`… (#60).
    -	/// Case-insensitive existence check (#60): enumerates `posts/` and
    -	/// compares lowercased — independent of the volume's case sensitivity.
    -	/// `excluding` skips a folder (the renamer's own, still present).
    -	static func availableSlug(for title: String, in postsRoot: URL, excluding ownID: String? = nil) -> String {
    -		let taken = Set(
    -			((try? FileManager.default.contentsOfDirectory(atPath: postsRoot.path)) ?? [])
    -				.map { $0.lowercased() },
    -		)
    +	/// 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
    +	/// collide). Case-insensitive existence check (#60), independent of the
    +	/// volume's case sensitivity. `excluding` skips a folder (the renamer's
    +	/// own, still present).
    +	// ponytail: O(all pieces) per call — enumerates every project's entries
    +	// to build the taken set. Fine at human scale (new-piece / rename only);
    +	// index the namespace if it ever measures hot.
    +	static func availableSlug(for title: String, home: URL, excluding ownID: String? = nil) -> String {
    +		var taken = Set()
    +		for root in Post.containerRoots {
    +			let rootURL = home.appendingPathComponent(root, isDirectory: true)
    +			guard let projects = try? FileManager.default.contentsOfDirectory(atPath: rootURL.path) else { continue }
    +			for project in projects {
    +				let entries = (try? FileManager.default.contentsOfDirectory(
    +					atPath: rootURL.appendingPathComponent(project, isDirectory: true).path,
    +				)) ?? []
    +				for entry in entries {
    +					taken.insert(entry.lowercased())
    +				}
    +			}
    +		}
     		let base = slug(from: title) // slug() is already lowercase
     		if !taken.contains(base) || base == ownID?.lowercased() {
     			return base
    @@ -75,24 +131,27 @@ nonisolated enum PostStore {
     		return "\(base)-\(suffix)"
     	}
     
    -	/// First write (#62): lazily materialize `posts//post.md` with the
    -	/// #59 block stamped. Pass State First Draft, origin writer — the only
    -	/// values #18 writes; the folder appears here, never on New Post.
    -	static func writeNew(body: String, home: URL) throws -> Post {
    +	/// 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
    +	/// here, never on New Post.
    +	static func writeNew(body: String, project: String = Post.defaultProject, home: URL) throws -> Post {
     		try materialize(
     			text: stamped(body: body, passState: .firstDraft, origin: .writer),
     			title: Post.title(of: body),
     			origin: .writer,
    +			project: project,
     			home: home,
     		)
     	}
     
     	/// #22/#94/#95: import one external markdown file as a Post — copy, never
     	/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
    -	/// verbatim with `pass_state: First Draft` and `origin: ` set /
    -	/// overwritten (our two keys win); id = Title slug at import; collisions
    -	/// `-2`/`-3`… (#60 machinery); a fresh copy, no mtime preservation (#96).
    -	static func importFile(at url: URL, origin: Post.Origin, home: URL) throws -> Post {
    +	/// verbatim with `type: post`, `pass_state: First Draft` and
    +	/// `origin: ` set / overwritten (our three keys win); id = Title
    +	/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
    +	/// no mtime preservation (#96).
    +	static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
     		var raw = try String(contentsOf: url, encoding: .utf8)
     		// ponytail: normalize line endings + strip BOM at the import boundary —
     		// in Swift a CRLF pair is ONE grapheme, so every "\n" split in the
    @@ -100,7 +159,9 @@ nonisolated enum PostStore {
     		// title); true CRLF preservation would need grapheme-aware joins
     		// everywhere. Lone-CR (pre-OSX) files still degrade to `untitled` —
     		// ceiling named, add a "\r" pass if one ever shows up.
    -		if raw.hasPrefix("\u{FEFF}") { raw.removeFirst() }
    +		if raw.hasPrefix("\u{FEFF}") {
    +			raw.removeFirst()
    +		}
     		raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
     		let (block, body) = splitFrontmatter(raw)
     		let text = mergedFrontmatter(keeping: block, origin: origin) + body
    @@ -108,60 +169,66 @@ nonisolated enum PostStore {
     			text: text,
     			title: Post.title(of: body),
     			origin: origin,
    +			project: project,
     			home: home,
     		)
     	}
     
    -	/// #95: external frontmatter keys ride along verbatim; `pass_state` and
    -	/// `origin` are set/overwritten in place — our two keys win, everything
    -	/// else untouched. Absent keys are inserted before the closing `---`.
    -	/// Returns the block INCLUDING its trailing newline; "" for a bare file
    -	/// (the caller then writes the #59 stamp shape via a fresh block).
    +	/// #95/#107: external frontmatter keys ride along verbatim; `type`,
    +	/// `pass_state` and `origin` are set/overwritten in place — our three
    +	/// keys win, everything else untouched. Absent keys are inserted before
    +	/// the closing `---` (in that order). Returns the block INCLUDING its
    +	/// trailing newline; "" for a bare file (the caller then writes the #59
    +	/// stamp shape via a fresh block).
     	private static func mergedFrontmatter(keeping block: String, origin: Post.Origin) -> String {
     		guard !block.isEmpty else {
    -			return "---\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
    +			return "---\ntype: post\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
     		}
     		var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
     		// Drop the empty tail the block's final newline produced — re-added below.
     		if let last = lines.last, last.isEmpty {
     			lines.removeLast()
     		}
    -		var ours: Set = []
    +		// #107: three our-keys win — type/pass_state/origin set-overwrite in
    +		// place, absent ones insert before the closing --- in stamp order.
    +		// Ordered pairs (a Dictionary's iteration order is unspecified).
    +		let ours: [(key: String, value: String)] = [
    +			("type", "post"),
    +			("pass_state", Post.PassState.firstDraft.rawValue),
    +			("origin", origin.rawValue),
    +		]
    +		let oursByKey = Dictionary(ours.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
    +		var seen = Set()
     		for (index, line) in lines.enumerated() {
     			// whitespacesAndNewlines: CRLF lines carry a trailing \r.
     			let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
     			guard !trimmed.isEmpty, trimmed != "---" else { continue }
     			let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
    -			if key == "pass_state" {
    -				lines[index] = "pass_state: \(Post.PassState.firstDraft.rawValue)"
    -				ours.insert("pass_state")
    -			} else if key == "origin" {
    -				lines[index] = "origin: \(origin.rawValue)"
    -				ours.insert("origin")
    +			if let value = oursByKey[key] {
    +				lines[index] = "\(key): \(value)"
    +				seen.insert(key)
     			}
     		}
    -		var insertions: [String] = []
    -		if !ours.contains("pass_state") {
    -			insertions.append("pass_state: \(Post.PassState.firstDraft.rawValue)")
    -		}
    -		if !ours.contains("origin") {
    -			insertions.append("origin: \(origin.rawValue)")
    -		}
    +		let insertions = ours.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
     		if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
     			lines.insert(contentsOf: insertions, at: close)
     		}
     		return lines.joined(separator: "\n") + "\n"
     	}
     
    -	/// #62/#95: lazily materialize `posts//post.md` with the given
    -	/// (already stamped/merged) text. Shared by `writeNew` and `importFile` —
    -	/// one lazy-folder path, TOCTOU-guarded, never clobbering.
    +	/// #62/#95: lazily materialize `projects///post.md` with
    +	/// the given (already stamped/merged) text. Shared by `writeNew` and
    +	/// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering.
     	/// Returns the created Post (id, title, First Draft, origin).
    -	private static func materialize(text: String, title: String, origin: Post.Origin, home: URL) throws -> Post {
    -		let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
    -		try FileManager.default.createDirectory(at: postsRoot, withIntermediateDirectories: true)
    -		let id = availableSlug(for: title, in: postsRoot)
    -		let dir = postsRoot.appendingPathComponent(id, isDirectory: true)
    +	private static func materialize(text: String, title: String, origin: Post.Origin, project: String, home: URL) throws -> Post {
    +		let projectsRoot = home.appendingPathComponent("projects", isDirectory: true)
    +		try FileManager.default.createDirectory(
    +			at: projectsRoot.appendingPathComponent(project, isDirectory: true),
    +			withIntermediateDirectories: true,
    +		)
    +		let id = availableSlug(for: title, home: home)
    +		let dir = projectsRoot.appendingPathComponent(project, isDirectory: true)
    +			.appendingPathComponent(id, isDirectory: true)
     		let fileURL = dir.appendingPathComponent("post.md")
     		// TOCTOU guard (audit): a folder appearing between slug pick and write
     		// must fail loudly, never clobber another post's content.
    @@ -179,31 +246,34 @@ nonisolated enum PostStore {
     			}
     			throw error
     		}
    -		return Post(id: id, title: title, passState: .firstDraft, origin: origin)
    +		return Post(id: id, title: title, passState: .firstDraft, origin: origin, type: .post, project: project, isArchived: false)
     	}
     
     	/// Save an existing Post: body-only text in, file normalized out. The
    -	/// file's present `pass_state`/`origin` are preserved (origin immutable,
    -	/// CONTEXT.md; bare corpus posts normalize on save, #59). A vanished
    -	/// post throws — `writeNew` is the only creator; saving must never
    -	/// resurrect a deleted post with reset metadata.
    +	/// file's present `pass_state`/`origin`/`type` are preserved (origin
    +	/// immutable, CONTEXT.md; bare corpus posts normalize on save, #59). A
    +	/// vanished post throws — `writeNew` is the only creator; saving must
    +	/// never resurrect a deleted post with reset metadata.
     	static func overwrite(id: String, body: String, home: URL) throws {
    -		let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
    -		guard let existing = try? String(contentsOf: fileURL, encoding: .utf8) else {
    +		guard let dir = folder(of: id, home: home),
    +		      let existing = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
    +		else {
     			throw CocoaError(.fileReadNoSuchFile)
     		}
     		let matter = Post.frontmatter(of: existing)
     		let passState = Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft
     		let origin = Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer
    -		try stamped(body: body, passState: passState, origin: origin)
    -			.write(to: fileURL, atomically: true, encoding: .utf8)
    +		let type = Post.ContentType(rawValue: matter["type"] ?? "") ?? .post
    +		try stamped(body: body, passState: passState, origin: origin, type: type)
    +			.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
     	}
     
     	/// Body text (frontmatter stripped) for editing; nil when unreadable.
     	/// Bare corpus posts return whole — they normalize on save (#59).
     	static func readBody(id: String, home: URL) -> String? {
    -		let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
    -		guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return nil }
    +		guard let dir = folder(of: id, home: home),
    +		      let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
    +		else { return nil }
     		return splitFrontmatter(text).body
     	}
     
    @@ -218,29 +288,36 @@ nonisolated enum PostStore {
     		var scrollOffset: Double = 0
     	}
     
    -	private static func stateURL(id: String, home: URL) -> URL {
    -		home.appendingPathComponent("posts/\(id)/.museion-state.json")
    +	private static func stateURL(id: String, home: URL) -> URL? {
    +		folder(of: id, home: home)?.appendingPathComponent(".museion-state.json")
     	}
     
     	/// Read the sidecar; nil when absent or corrupt (a fresh cursor is fine).
     	static func readCursor(id: String, home: URL) -> CursorState? {
    -		guard let data = try? Data(contentsOf: stateURL(id: id, home: home)) else { return nil }
    +		guard let url = stateURL(id: id, home: home),
    +		      let data = try? Data(contentsOf: url)
    +		else { return nil }
     		return try? JSONDecoder().decode(CursorState.self, from: data)
     	}
     
     	/// Write the sidecar. Best-effort by design — a failed cursor write must
     	/// never read as a failed content save, so failures are swallowed here.
     	static func writeCursor(_ state: CursorState, id: String, home: URL) {
    -		guard let data = try? JSONEncoder().encode(state) else { return }
    -		try? data.write(to: stateURL(id: id, home: home), options: .atomic)
    +		guard let url = stateURL(id: id, home: home),
    +		      let data = try? JSONEncoder().encode(state)
    +		else { return }
    +		try? data.write(to: url, options: .atomic)
     	}
     
     	/// Explicit Rename (#60): rewrite the `# Title` line as the first
    -	/// non-empty body line, then move the folder to the new slug. The file
    -	/// stays `post.md`; a title that slugs to the current id only retitles.
    +	/// non-empty body line, then move the folder to the new slug — within
    +	/// the SAME parent (ADR-0012: the piece stays in its project, archived
    +	/// stays archived). The file stays `post.md`; a title that slugs to the
    +	/// current id only retitles.
     	static func rename(_ post: Post, to title: String, home: URL) throws -> Post {
    -		let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
    -		let dir = postsRoot.appendingPathComponent(post.id, isDirectory: true)
    +		guard let dir = folder(of: post.id, home: home) else {
    +			throw CocoaError(.fileReadNoSuchFile)
    +		}
     		let fileURL = dir.appendingPathComponent("post.md")
     		let text = try String(contentsOf: fileURL, encoding: .utf8)
     		let (block, body) = splitFrontmatter(text)
    @@ -250,27 +327,30 @@ nonisolated enum PostStore {
     		// availableSlug excludes our own (still-present) folder: a retitle
     		// whose slug matches the current id (any case) keeps the clean name
     		// (no -2 against ourselves); a genuine collision lands on -2 (#60).
    -		let newID = availableSlug(for: title, in: postsRoot, excluding: post.id)
    +		let newID = availableSlug(for: title, home: home, excluding: post.id)
     		guard newID != post.id else {
    -			return Post(id: post.id, title: title, passState: post.passState, origin: post.origin)
    +			return Post(id: post.id, title: title, passState: post.passState, origin: post.origin,
    +			            type: post.type, project: post.project, isArchived: post.isArchived)
     		}
    -		try FileManager.default.moveItem(at: dir, to: postsRoot.appendingPathComponent(newID, isDirectory: true))
    -		return Post(id: newID, title: title, passState: post.passState, origin: post.origin)
    +		try FileManager.default.moveItem(at: dir, to: dir.deletingLastPathComponent().appendingPathComponent(newID, isDirectory: true))
    +		return Post(id: newID, title: title, passState: post.passState, origin: post.origin,
    +		            type: post.type, project: post.project, isArchived: post.isArchived)
     	}
     
     	/// Delete = move the Post folder to the Trash (recoverable in Finder) —
     	/// never permanent removal (#18 AC).
     	static func trash(_ post: Post, home: URL) throws {
    +		guard let dir = folder(of: post.id, home: home) else {
    +			throw CocoaError(.fileReadNoSuchFile)
    +		}
     		var trashed: NSURL?
    -		try FileManager.default.trashItem(
    -			at: home.appendingPathComponent("posts/\(post.id)", isDirectory: true),
    -			resultingItemURL: &trashed,
    -		)
    +		try FileManager.default.trashItem(at: dir, resultingItemURL: &trashed)
     	}
     
    -	/// The #59 v1 block — flat keys, the exact shape the #17 reader parses.
    -	static func stamped(body: String, passState: Post.PassState, origin: Post.Origin) -> String {
    -		"---\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
    +	/// 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 {
    +		"---\ntype: \(type.rawValue)\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
     	}
     
     	/// Splits a file into its verbatim frontmatter block (with both `---`
    diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift
    index 3edcc5e..45a66e5 100644
    --- a/Museion/PostsModel.swift
    +++ b/Museion/PostsModel.swift
    @@ -2,9 +2,10 @@
     //  PostsModel.swift
     //  Museion
     //
    -//  #18 (S1.1): the Posts pane's write side — FSEvents watcher on posts/ with
    -//  a ~0.5 s debounced rescan (#61), selection, and the New Post draft
    -//  lifecycle (#62). Own ops route through the same rescan: one path.
    +//  #18 (S1.1): the Posts pane's write side — FSEvents watcher on the piece
    +//  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.
     //
     
     import CoreServices
    @@ -12,20 +13,23 @@ import Foundation
     import Observation
     
     /// The New Post draft: body text only, no folder until first save (#62).
    +/// #107: remembers the project the piece will land in when first saved.
     struct PostDraft {
     	var text = "# Untitled\n\n"
    +	let project: String
     }
     
    -/// Recursive FSEvents stream on one directory (#61): file-level events, so
    -/// nested `posts//post.md` edits from Finder fire too — a plain dir-FD
    -/// dispatch source only sees direct children and misses them.
    +/// Recursive FSEvents stream on one or more directories (#61): file-level
    +/// events, so nested `projects///post.md` edits from Finder fire
    +/// too — a plain dir-FD dispatch source only sees direct children and misses
    +/// them.
     final nonisolated class PostsWatcher: @unchecked Sendable {
    -	/// Fired on the main actor when anything under the watched path changes.
    +	/// Fired on the main actor when anything under a watched path changes.
     	var onEvent: (@MainActor @Sendable () -> Void)?
     
     	private var stream: FSEventStreamRef?
     
    -	func start(url: URL) {
    +	func start(urls: [URL]) {
     		stop()
     		var context = FSEventStreamContext(
     			version: 0,
    @@ -43,7 +47,7 @@ final nonisolated class PostsWatcher: @unchecked Sendable {
     			kCFAllocatorDefault,
     			callback,
     			&context,
    -			[url.path] as CFArray,
    +			urls.map(\.path) as CFArray,
     			FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
     			0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
     			FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
    @@ -69,7 +73,8 @@ final nonisolated class PostsWatcher: @unchecked Sendable {
     @MainActor
     @Observable
     final class PostsModel {
    -	/// The scanned, title-sorted list — mirrors `posts/` at all times.
    +	/// The scanned, title-sorted list — mirrors `projects/` + `archive/` at
    +	/// all times (#107).
     	private(set) var posts: [Post] = []
     
     	/// The selected Post's id; nil = nothing selected (empty editor).
    @@ -101,9 +106,9 @@ final class PostsModel {
     	/// check reused verbatim for foreign files.
     	private var externalWatcher = PostsWatcher()
     
    -	/// Bind a Home: ensure `posts/` exists (FSEvents on a missing path is
    -	/// unreliable; the AC's lazy rule is about post folders, not this root),
    -	/// initial scan + start (or restart) the watcher. Called from
    +	/// Bind a Home: ensure both container roots exist (FSEvents on a missing
    +	/// path is unreliable; archive/ is a watcher root now, #107), initial
    +	/// scan + start (or restart) the watcher. Called from
     	/// `.task(id: home)` — re-fires on Home repoint.
     	func bind(home: URL) {
     		startWatching(home: home)
    @@ -115,12 +120,12 @@ final class PostsModel {
     	private func startWatching(home: URL) {
     		guard watchedHome != home else { return }
     		watchedHome = home
    -		try? FileManager.default.createDirectory(
    -			at: home.appendingPathComponent("posts", isDirectory: true),
    -			withIntermediateDirectories: true,
    -		)
    +		let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
    +		for root in roots {
    +			try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
    +		}
     		watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
    -		watcher.start(url: home.appendingPathComponent("posts", isDirectory: true))
    +		watcher.start(urls: roots)
     	}
     
     	/// Off-main scan; keeps selection valid across the fresh refresh.
    @@ -158,6 +163,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.
    +	private var targetProject: String {
    +		posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project ?? Post.defaultProject
    +	}
    +
     	/// Tear the watcher down on the main actor (its scheduling thread) —
     	/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
     	/// flushes the open session first (sidecar rides along). #96: quit also
    @@ -170,11 +182,14 @@ final class PostsModel {
     	}
     
     	/// New Post (#62): fresh in-memory draft, no folder, editor takes it.
    +	/// #107: the draft targets the selected post's project (archived posts
    +	/// target the default — new pieces are never born archived).
     	func newPost() {
    +		let target = targetProject
     		dismissExternal() // #92: opening a draft dismisses the guest
     		session?.teardown(flushFirst: true) // #64: selection change flushes
     		session = nil
    -		draft = PostDraft()
    +		draft = PostDraft(project: target)
     		selectedPostID = nil
     	}
     
    @@ -194,7 +209,7 @@ final class PostsModel {
     	func saveDraft(home: URL) {
     		guard let draft else { return }
     		do {
    -			let post = try PostStore.writeNew(body: draft.text, home: home)
    +			let post = try PostStore.writeNew(body: draft.text, project: draft.project, home: home)
     			self.draft = nil
     			selectedPostID = post.id
     			session = EditorSession(postID: post.id, home: home)
    @@ -302,11 +317,11 @@ final class PostsModel {
     	/// main actor already; no re-hop needed.
     	private func startExternalWatch(url: URL) {
     		externalWatcher.onEvent = { [weak self] in
    -			guard let self, let session = self.externalSession else { return }
    +			guard let self, let session = externalSession else { return }
     			guard let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
     			session.diskDidChange(diskText: disk)
     		}
    -		externalWatcher.start(url: url.deletingLastPathComponent())
    +		externalWatcher.start(urls: [url.deletingLastPathComponent()])
     	}
     
     	/// #94: stage a multi-file import — the ONE Origin ask presents; the
    @@ -325,15 +340,17 @@ final class PostsModel {
     	/// a Post; a per-file failure continues the batch into lastError (stated
     	/// default, reversible; never an alert, never an abort). The last
     	/// imported post opens; a failure anywhere keeps its message up even
    -	/// when other files landed.
    +	/// when other files landed. #107: the batch lands in the selected
    +	/// post's project (newPost's target rule).
     	func importFiles(origin: Post.Origin, home: URL) {
     		guard let urls = pendingImportURLs else { return }
     		pendingImportURLs = nil
    +		let project = targetProject
     		var last: Post?
     		var failures = 0
     		for url in urls {
     			do {
    -				last = try PostStore.importFile(at: url, origin: origin, home: home)
    +				last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
     			} catch {
     				failures += 1
     				lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
    diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift
    index e14ef08..1ad1973 100644
    --- a/Museion/PostsPaneView.swift
    +++ b/Museion/PostsPaneView.swift
    @@ -2,8 +2,8 @@
     //  PostsPaneView.swift
     //  Museion
     //
    -//  #17 (S1.1): the Posts pane — library column mirroring the Home's posts/
    -//  on disk. #18: lifecycle — New Post draft, ⌘S first-write/save, rename,
    +//  #17 (S1.1): the Posts pane — library column mirroring the Home's
    +//  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).
     //
    @@ -189,7 +189,7 @@ struct PostsLibraryColumn: View {
     		VStack(spacing: 8) {
     			Text("No posts yet")
     				.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
    -			Text("Posts in this Home's posts/ folder appear here.")
    +			Text("Posts in this Home's projects/ folders appear here.")
     				.font(.callout)
     				.foregroundStyle(DesignTokens.muted)
     				.multilineTextAlignment(.center)
    diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift
    index c5646c3..b0a4cc6 100644
    --- a/Museion/SettingsPaneView.swift
    +++ b/Museion/SettingsPaneView.swift
    @@ -26,7 +26,7 @@ struct SettingsPaneView: View {
     		.background(DesignTokens.background)
     	}
     
    -// MARK: Home (#17)
    +	// MARK: Home (#17)
     
     	private var contentSection: some View {
     		VStack(alignment: .leading, spacing: 12) {
    @@ -42,7 +42,7 @@ struct SettingsPaneView: View {
     				Button("Choose…") { chooseHome() }
     			}
     			Text(
    -				"Repoint-only: Museion never moves content. The Posts list reads this folder's posts/ directory.",
    +				"Repoint-only: Museion never moves content. The Posts list reads this folder's projects/ and archive/ directories.",
     			)
     			.font(.callout)
     			.foregroundStyle(DesignTokens.muted)
    diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md
    index d99574e..ddd1585 100644
    --- a/MuseionTests/AGENTS.md
    +++ b/MuseionTests/AGENTS.md
    @@ -20,13 +20,13 @@ Owned by the root AGENTS.md contract.
     - `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
     - `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) — throwaway Homes via `makeHome`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`), lazy folders / hidden dirs / symlinks / noise not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
    -- `PostStoreTests.swift` (#18) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write + #59 stamp round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes, rename (retitle + move, insert-title path, same-slug retitle-only, collision -2), trash removes from posts/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-posts failure path.
    +- `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.
     - `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. - `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0. -- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our two keys win, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. +- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts//post.md` (#107). ## Verification diff --git a/MuseionTests/EditorSessionTests.swift b/MuseionTests/EditorSessionTests.swift index daae7a4..3221050 100644 --- a/MuseionTests/EditorSessionTests.swift +++ b/MuseionTests/EditorSessionTests.swift @@ -21,7 +21,7 @@ private func makeSessionHome() -> URL { @MainActor private func seedPost(_ home: URL, id: String, body: String) { - let dir = home.appendingPathComponent("posts/\(id)", isDirectory: true) + let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try? PostStore.stamped(body: body, passState: .firstDraft, origin: .writer) .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) @@ -132,7 +132,7 @@ struct EditorSessionTests { // #83: Keep Local with the post vanished mid-alert — the session must // stay dirty (never a lying "Saved"), ⌘S still attempts the write. try? FileManager.default.removeItem( - at: home.appendingPathComponent("posts/eta", isDirectory: true), + at: home.appendingPathComponent("projects/posts/eta", isDirectory: true), ) session.diskDidChange(diskText: "# Eta\n\nExternal 2.") // alert raised; disk now unreadable session.keepLocal() @@ -148,7 +148,7 @@ struct EditorSessionTests { // Vanish the post: overwrite throws (no resurrection), state = failed. try FileManager.default.removeItem( - at: home.appendingPathComponent("posts/delta", isDirectory: true), + at: home.appendingPathComponent("projects/posts/delta", isDirectory: true), ) var reported: String? session.onError = { reported = $0 } @@ -210,4 +210,15 @@ struct EditorSessionTests { #expect(PostStore.readBody(id: "zeta", home: home) == "# Zeta\n\nReworked.") // unwritten #expect(session.saveState != .failed) // no spurious failure fired } + + @Test func `unresolvable id falls back to the default-project path`() { + // #107: folderURL is resolved once at init; a piece that exists + // nowhere still gets a sane path (image resolution, crumbs) — the + // default-project shape, never a crash. + let home = makeSessionHome() + let session = EditorSession(postID: "ghost", home: home) + let expected = home.appendingPathComponent("projects/posts/ghost", isDirectory: true) + #expect(session.folderURL == expected) + #expect(session.loadFailed) // nothing to read there either + } } diff --git a/MuseionTests/ImportExternalTests.swift b/MuseionTests/ImportExternalTests.swift index 22da745..96ae843 100644 --- a/MuseionTests/ImportExternalTests.swift +++ b/MuseionTests/ImportExternalTests.swift @@ -50,7 +50,7 @@ struct ImportExternalTests { #expect(post.id == "my-outside-note") #expect(post.passState == .firstDraft) #expect(post.origin == .ai) - let onDisk = try String(contentsOf: home.appendingPathComponent("posts/my-outside-note/post.md"), encoding: .utf8) + let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/my-outside-note/post.md"), encoding: .utf8) // Our two keys win: #expect(onDisk.contains("pass_state: First Draft")) #expect(onDisk.contains("origin: ai")) @@ -77,7 +77,7 @@ struct ImportExternalTests { let post = try PostStore.importFile(at: ext, origin: .ai, home: home) #expect(post.id == "crlf-note") - let onDisk = try String(contentsOf: home.appendingPathComponent("posts/crlf-note/post.md"), encoding: .utf8) + let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/crlf-note/post.md"), encoding: .utf8) #expect(onDisk.contains("pass_state: First Draft")) #expect(onDisk.contains("origin: ai")) #expect(onDisk.contains("date: 2026-10-11")) @@ -113,8 +113,8 @@ struct ImportExternalTests { #expect(first.id == "same-title") #expect(second.id == "same-title-2") // #60 machinery - let bare = try String(contentsOf: home.appendingPathComponent("posts/same-title/post.md"), encoding: .utf8) - #expect(bare.hasPrefix("---\npass_state: First Draft\norigin: writer\n---\n")) + let bare = try String(contentsOf: home.appendingPathComponent("projects/posts/same-title/post.md"), encoding: .utf8) + #expect(bare.hasPrefix("---\ntype: post\npass_state: First Draft\norigin: writer\n---\n")) } @Test func `import empty file is untitled`() throws { @@ -126,6 +126,31 @@ struct ImportExternalTests { #expect(post.title == "untitled") } + @Test func `import overwrites external type key with post`() throws { + let home = try importHome() + let ext = try writeExternal("outline.md", """ + --- + type: outline + date: 2026-10-12 + --- + + # Outside Outline + + Body. + """) + defer { try? FileManager.default.removeItem(at: ext) } + + let post = try PostStore.importFile(at: ext, origin: .writer, home: home) + + #expect(post.id == "outside-outline") + #expect(post.type == .post) + let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/outside-outline/post.md"), encoding: .utf8) + #expect(onDisk.contains("type: post")) + #expect(!onDisk.contains("type: outline")) + let scanned = try #require(Post.scan(home: home).first) + #expect(scanned.type == .post) + } + @Test func `external session saves in place with no sidecar`() async throws { let home = try importHome() let ext = try writeExternal("journal.md", "# Journal\n\nOne.") diff --git a/MuseionTests/PostLibraryTests.swift b/MuseionTests/PostLibraryTests.swift index 795a3e2..fbe10eb 100644 --- a/MuseionTests/PostLibraryTests.swift +++ b/MuseionTests/PostLibraryTests.swift @@ -2,14 +2,15 @@ // PostLibraryTests.swift // MuseionTests // -// #17: the Posts list mirrors /posts/ on disk. +// #17/#107: the Posts list mirrors /projects/// and +// /archive/// on disk (two-level scan, global slug space). // import Foundation @testable import Museion import Testing -/// Builds throwaway Homes in a temp dir: posts written bare (corpus shape, +/// Builds throwaway Homes in a temp dir: pieces written bare (corpus shape, /// no frontmatter) or with frontmatter; noise entries that must not crash or /// surface as Posts. private func makeHome(_ write: (URL) throws -> Void) throws -> URL { @@ -20,12 +21,17 @@ private func makeHome(_ write: (URL) throws -> Void) throws -> URL { return home } -private func writePost(_ home: URL, _ id: String, _ body: String) throws { - let dir = home.appendingPathComponent("posts/\(id)", isDirectory: true) +/// Seeds ////post.md (root: "projects" or "archive"). +private func writePiece(_ home: URL, _ root: String, _ project: String, _ id: String, _ body: String) throws { + let dir = home.appendingPathComponent("\(root)/\(project)/\(id)", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try body.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } +private func writePost(_ home: URL, _ id: String, _ body: String) throws { + try writePiece(home, "projects", "posts", id, body) +} + @Test func `bare post is first draft writer with heading title`() throws { let home = try makeHome { home in try writePost(home, "the-new-reeder", "## The New Reeder\n\nBody text.") @@ -71,19 +77,62 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws { #expect(Post.scan(home: missing).isEmpty) } +@Test func `scan enumerates two levels across projects and archive`() throws { + let home = try makeHome { home in + try writePiece(home, "projects", "alpha", "one", "## One\n\nBody.") + try writePiece(home, "projects", "beta", "two", "## Two\n\nBody.") + try writePiece(home, "archive", "gamma", "three", "## Three\n\nBody.") + // Noise at the new level: loose file at projects/ root, lazy piece + // folder, hidden project dir. + try "loose".write( + to: home.appendingPathComponent("projects/loose.md"), + atomically: true, + encoding: .utf8, + ) + try FileManager.default.createDirectory( + at: home.appendingPathComponent("projects/alpha/not-yet", isDirectory: true), + withIntermediateDirectories: true, + ) + try writePiece(home, "projects", ".trash", "four", "## Four\n") + } + let posts = Post.scan(home: home) + #expect(posts.count == 3) + let one = try #require(posts.first { $0.id == "one" }) + #expect(one.project == "alpha") + #expect(!one.isArchived) + let two = try #require(posts.first { $0.id == "two" }) + #expect(two.project == "beta") + #expect(!two.isArchived) + let three = try #require(posts.first { $0.id == "three" }) + #expect(three.project == "gamma") + #expect(three.isArchived) +} + +@Test func `type frontmatter is read leniently`() throws { + let home = try makeHome { home in + try writePost(home, "outlined", "---\ntype: outline\n---\n\n## Outlined\n") + try writePost(home, "untyped", "---\npass_state: First Draft\n---\n\n## Plain\n") + try writePost(home, "essay", "---\ntype: essay\n---\n\n## Essay\n") + } + let posts = Post.scan(home: home) + #expect(posts.first { $0.id == "outlined" }?.type == .outline) + #expect(posts.first { $0.id == "untyped" }?.type == .post) // absent key + #expect(posts.first { $0.id == "essay" }?.type == .post) // unknown value +} + @Test func `lazy folders, hidden dirs and noise are not posts`() throws { let home = try makeHome { home in try writePost(home, "one", "One") // Lazy folder: no post.md yet (created lazily on first write, #18). try FileManager.default.createDirectory( - at: home.appendingPathComponent("posts/not-yet", isDirectory: true), + at: home.appendingPathComponent("projects/posts/not-yet", isDirectory: true), withIntermediateDirectories: true, ) // Hidden dir WITH a post.md — must not surface. try writePost(home, ".trash", "---\n---\n## Hidden\n") - // Noise: loose file at posts/ root. + // Noise: loose file at the piece level. try "loose".write( - to: home.appendingPathComponent("posts/loose.md"), + to: home.appendingPathComponent("projects/posts/loose.md"), atomically: true, encoding: .utf8, ) @@ -94,7 +143,7 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws { @Test func `symlinked post dir is not followed`() throws { let home = try makeHome { home in try writePost(home, "one", "One") - // A post.md outside the Home, linked into posts/ by symlink. + // A post.md outside the Home, linked into the project by symlink. let outside = home.deletingLastPathComponent() .appendingPathComponent("postlib-outside-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) @@ -104,7 +153,7 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws { encoding: .utf8, ) try FileManager.default.createSymbolicLink( - at: home.appendingPathComponent("posts/linked", isDirectory: true), + at: home.appendingPathComponent("projects/posts/linked", isDirectory: true), withDestinationURL: outside, ) } @@ -152,3 +201,36 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws { .appendingPathComponent("Documents/Museion", isDirectory: true), ) } + +@Test func `duplicate id on disk dedupes to the folder-of winner`() throws { + // Audit: a Finder copy can duplicate an id across projects (or into + // archive/). scan keeps ONE row — the same projects-before-archive, + // name-sorted winner folder(of:) writes to — so the row shown is + // always the piece written. + let home = try makeHome { home in + try writePiece(home, "projects", "beta", "same-id", "## From Beta\n") + try writePiece(home, "projects", "alpha", "same-id", "## From Alpha\n") + try writePiece(home, "archive", "zeta", "same-id", "## From Archive\n") + } + let posts = Post.scan(home: home) + #expect(posts.count == 1) + #expect(posts.first?.project == "alpha") // alpha < beta; archive never wins + #expect(PostStore.folder(of: "same-id", home: home)? + .lastPathComponent == "same-id") + #expect(PostStore.folder(of: "same-id", home: home)? + .pathComponents.suffix(2).first == "alpha") +} + +@Test func `hidden project folder never shadows a visible piece`() throws { + // Audit: folder(of:) skips dot-projects like scan does — a piece under + // projects/.trash/ must not capture writes meant for the visible twin. + let home = try makeHome { home in + try writePiece(home, "projects", ".trash", "mine", "## Hidden\n") + try writePiece(home, "projects", "posts", "mine", "## Visible\n") + } + let posts = Post.scan(home: home) + #expect(posts.map(\.id) == ["mine"]) + #expect(posts.first?.title == "Visible") + #expect(PostStore.folder(of: "mine", home: home)? + .pathComponents.suffix(2).first == "posts") +} diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index b4bfb62..cb969e3 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -2,9 +2,10 @@ // PostStoreTests.swift // MuseionTests // -// #18: the Post lifecycle write side — slug naming, lazy first write with -// the #59 stamp, rename = retitle + move (#60), Trash delete, save-time -// normalization. +// #18/#107: the Post lifecycle write side — global slug namespace across +// 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. // import Foundation @@ -21,7 +22,7 @@ private func storeHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL { } private func readPost(_ home: URL, _ id: String) throws -> String { - try String(contentsOf: home.appendingPathComponent("posts/\(id)/post.md"), encoding: .utf8) + try String(contentsOf: home.appendingPathComponent("projects/posts/\(id)/post.md"), encoding: .utf8) } @Test func `slug algorithm per #60`() { @@ -45,8 +46,11 @@ private func readPost(_ home: URL, _ id: String) throws -> String { #expect(post.passState == .firstDraft) #expect(post.origin == .writer) #expect(post.title == "My First Post") + #expect(post.project == Post.defaultProject) + #expect(!post.isArchived) + #expect(post.type == .post) let file = try readPost(home, "my-first-post") - #expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# My First Post\n\nBody.") + #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# My First Post\n\nBody.") // The #17 reader round-trips what the write side stamps. let scanned = Post.scan(home: home) @@ -61,28 +65,55 @@ private func readPost(_ home: URL, _ id: String) throws -> String { let post = try PostStore.writeNew(body: "\n\n", home: home) #expect(post.id == "untitled") #expect(post.title == "untitled") - #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/untitled/post.md").path)) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/untitled/post.md").path)) } @Test func `collision appends -2 -3 case-insensitively`() throws { let home = try storeHome { home in try FileManager.default.createDirectory( - at: home.appendingPathComponent("posts/my-post", isDirectory: true), + at: home.appendingPathComponent("projects/posts/my-post", isDirectory: true), withIntermediateDirectories: true, ) + // The taken set spans every project, not just posts/. try FileManager.default.createDirectory( - at: home.appendingPathComponent("posts/My-Post-2", isDirectory: true), + at: home.appendingPathComponent("projects/other/My-Post-2", isDirectory: true), withIntermediateDirectories: true, ) - try "x".write(to: home.appendingPathComponent("posts/my-post/post.md"), atomically: true, encoding: .utf8) + try "x".write(to: home.appendingPathComponent("projects/posts/my-post/post.md"), atomically: true, encoding: .utf8) } - // existing: my-post, My-Post-2 → next free: my-post-3 - #expect(PostStore.availableSlug(for: "My Post", in: home.appendingPathComponent("posts")) == "my-post-3") + // existing: posts/my-post, other/My-Post-2 → next free: my-post-3 + #expect(PostStore.availableSlug(for: "My Post", home: home) == "my-post-3") let post = try PostStore.writeNew(body: "# My Post\n", home: home) #expect(post.id == "my-post-3") } +@Test func `archived slug is never reused`() throws { + let home = try storeHome { home in + try FileManager.default.createDirectory( + at: home.appendingPathComponent("archive/done/my-post", isDirectory: true), + withIntermediateDirectories: true, + ) + try "x".write(to: home.appendingPathComponent("archive/done/my-post/post.md"), atomically: true, encoding: .utf8) + try FileManager.default.createDirectory( + at: home.appendingPathComponent("projects/posts/other-piece", isDirectory: true), + withIntermediateDirectories: true, + ) + } + // Archive counts as taken — restore of the archived piece must not collide. + #expect(PostStore.availableSlug(for: "My Post", home: home) == "my-post-2") +} + +@Test func `writeNew lands in the given project`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Mine\n", project: "essays", home: home) + #expect(post.project == "essays") + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/mine/post.md").path)) + let scanned = Post.scan(home: home) + #expect(scanned.count == 1) + #expect(scanned.first?.project == "essays") +} + @Test func `rename retitles moves folder and keeps frontmatter`() throws { let home = try storeHome() let original = try PostStore.writeNew(body: "# Old Name\n\nBody.", home: home) @@ -90,9 +121,33 @@ private func readPost(_ home: URL, _ id: String) throws -> String { #expect(moved.id == "new-name") #expect(moved.title == "New Name") - #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/old-name").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/old-name").path)) let file = try readPost(home, "new-name") - #expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# New Name\n\nBody.") + #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# New Name\n\nBody.") +} + +@Test func `rename moves within the same project and archive stays archived`() throws { + let home = try storeHome() + // Same project: rename must not bounce the piece to the default project. + let original = try PostStore.writeNew(body: "# Old Essay\n", project: "essays", home: home) + let moved = try PostStore.rename(original, to: "New Essay", home: home) + #expect(moved.project == "essays") + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/new-essay/post.md").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/new-essay").path)) + + // Archived piece: stays under archive//, still flagged archived. + try FileManager.default.createDirectory( + at: home.appendingPathComponent("archive/done/old-thing", isDirectory: true), + withIntermediateDirectories: true, + ) + try "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Old Thing\n" + .write(to: home.appendingPathComponent("archive/done/old-thing/post.md"), atomically: true, encoding: .utf8) + let archived = try #require(Post.scan(home: home).first { $0.id == "old-thing" }) + let renamed = try PostStore.rename(archived, to: "New Thing", home: home) + #expect(renamed.isArchived) + #expect(renamed.project == "done") + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/done/new-thing/post.md").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/done/old-thing").path)) } @Test func `rename inserts title line when body had none`() throws { @@ -102,7 +157,7 @@ private func readPost(_ home: URL, _ id: String) throws -> String { let moved = try PostStore.rename(original, to: "Given Title", home: home) #expect(moved.id == "given-title") let file = try readPost(home, "given-title") - #expect(file.hasPrefix("---\npass_state: First Draft\norigin: writer\n---\n# Given Title")) + #expect(file.hasPrefix("---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Given Title")) } @Test func `rename keeps non-heading first line and inserts title above`() throws { @@ -111,7 +166,7 @@ private func readPost(_ home: URL, _ id: String) throws -> String { let moved = try PostStore.rename(original, to: "Errands", home: home) #expect(moved.id == "errands") let file = try readPost(home, "errands") - #expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# Errands\nCall mom tomorrow\n\nSecond line.") + #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Errands\nCall mom tomorrow\n\nSecond line.") } @Test func `overwrite on vanished post throws instead of resurrecting`() throws { @@ -119,7 +174,7 @@ private func readPost(_ home: URL, _ id: String) throws -> String { #expect(throws: CocoaError(.fileReadNoSuchFile)) { try PostStore.overwrite(id: "ghost", body: "# Ghost\n", home: home) } - #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/ghost").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path)) } @Test func `collision routing consults a fresh listing`() throws { @@ -130,12 +185,12 @@ private func readPost(_ home: URL, _ id: String) throws -> String { // slug pick must see it. (The in-writeNew existence guard covers the // race where the folder appears after the pick; that window isn't // deterministically reachable from a black-box test.) - let racedDir = home.appendingPathComponent("posts/mine-3", isDirectory: true) + let racedDir = home.appendingPathComponent("projects/posts/mine-3", isDirectory: true) try FileManager.default.createDirectory(at: racedDir, withIntermediateDirectories: true) try "external".write(to: racedDir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) - #expect(PostStore.availableSlug(for: "Mine", in: home.appendingPathComponent("posts")) == "mine-4") + #expect(PostStore.availableSlug(for: "Mine", home: home) == "mine-4") _ = try PostStore.writeNew(body: "# Mine\n", home: home) - #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/mine-4/post.md").path)) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/mine-4/post.md").path)) } @Test func `rename to same slug only retitles`() throws { @@ -144,7 +199,7 @@ private func readPost(_ home: URL, _ id: String) throws -> String { // Title slugs to same id → rewrite # line, no move. let moved = try PostStore.rename(original, to: "Same name!", home: home) #expect(moved.id == "same-name") - #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/same-name/post.md").path)) + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/same-name/post.md").path)) } @Test func `rename collision takes -2`() throws { @@ -154,28 +209,46 @@ private func readPost(_ home: URL, _ id: String) throws -> String { let moved = try PostStore.rename(alpha, to: "Beta", home: home) #expect(moved.id == "beta-2") let renamed = try readPost(home, "beta-2") - #expect(renamed.hasPrefix("---\npass_state: First Draft\norigin: writer\n---\n# Beta")) + #expect(renamed.hasPrefix("---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Beta")) } @Test func `trash moves folder out of posts recoverably`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home) try PostStore.trash(post, home: home) - #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("posts/\(post.id)").path)) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path)) + #expect(Post.scan(home: home).isEmpty) +} + +@Test func `trash resolves pieces in the archive`() throws { + let home = try storeHome { home in + try FileManager.default.createDirectory( + at: home.appendingPathComponent("archive/done/doomed", isDirectory: true), + withIntermediateDirectories: true, + ) + try "# Doomed\n".write( + to: home.appendingPathComponent("archive/done/doomed/post.md"), + atomically: true, + encoding: .utf8, + ) + } + let doomed = try #require(Post.scan(home: home).first) + try PostStore.trash(doomed, home: home) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/done/doomed").path)) #expect(Post.scan(home: home).isEmpty) } @Test func `overwrite preserves pass_state and origin normalizing bare posts`() throws { let home = try storeHome() // A bare corpus post on disk (no frontmatter). - let dir = home.appendingPathComponent("posts/bare-one", isDirectory: true) + let dir = home.appendingPathComponent("projects/posts/bare-one", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "# Bare\n\nCorpus body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) try PostStore.overwrite(id: "bare-one", body: "# Bare\n\nEdited body.", home: home) let file = try readPost(home, "bare-one") - #expect(file == "---\npass_state: First Draft\norigin: writer\n---\n# Bare\n\nEdited body.") + #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Bare\n\nEdited body.") let scanned = try #require(Post.scan(home: home).first) #expect(scanned.passState == .firstDraft) #expect(scanned.origin == .writer) @@ -183,7 +256,7 @@ private func readPost(_ home: URL, _ id: String) throws -> String { @Test func `overwrite preserves existing pass_state and origin values`() throws { let home = try storeHome { home in - let dir = home.appendingPathComponent("posts/stamped", isDirectory: true) + let dir = home.appendingPathComponent("projects/posts/stamped", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "---\npass_state: Pass-1 Done\norigin: ai\n---\n# Stamped\n\nBody." .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) @@ -204,9 +277,13 @@ private func readPost(_ home: URL, _ id: String) throws -> String { } @Test func `writeNew failure does not leave a half post`() throws { - // A file where the posts dir should go: writeNew must fail cleanly. + // A file where the default project dir should go: writeNew must fail cleanly. let home = try storeHome() - let postsPath = home.appendingPathComponent("posts").path + try FileManager.default.createDirectory( + at: home.appendingPathComponent("projects", isDirectory: true), + withIntermediateDirectories: true, + ) + let postsPath = home.appendingPathComponent("projects/posts").path try "blocker".write(to: URL(fileURLWithPath: postsPath), atomically: true, encoding: .utf8) #expect(throws: Error.self) { _ = try PostStore.writeNew(body: "# Blocked\n", home: home) diff --git a/docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md b/docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md new file mode 100644 index 0000000..19e3517 --- /dev/null +++ b/docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md @@ -0,0 +1,65 @@ +# Build S1: storage substrate — projects/ + archive/, type frontmatter (#107) + +> **Date:** 2026-10-13 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/107 (map: #97, ADR-0012) + +## Goal + +Re-root the piece storage substrate per #107 / ADR-0012: `posts//` → `projects///` + `archive///` (two-level scan), global slug namespace across both roots, `type: post` frontmatter stamped by New/Import and read leniently, every PostStore write path deriving its folder from the id alone. No UI change beyond what the paths force. + +## What Was Done + +- `PostLibrary.swift` — `Post` gains `type` (`ContentType` post|outline), `project`, `isArchived`; `Post.scan` walks both roots (`projects`, `archive`) with the same skip guards at both levels; `type` read leniently (absent/unknown → post); audit fix: first-wins dedupe by id in the same deterministic order `folder(of:)` resolves (projects-before-archive, name-sorted). +- `PostStore.swift` — new `folder(of:home:)` id→folder resolver (every write path derives its target from the id; nothing threads `(project, id)`); `availableSlug(for:home:)` over the global namespace (all entries under `projects/*/` + `archive/*/`; archived slug never reused); `writeNew(body:project:home:)` + `importFile(at:origin:project:home:)` land under the selected project else default `posts`; `stamped`/`mergedFrontmatter` carry `type: post` as the third our-key (first in the block, order pinned by tests); `overwrite`/`readBody`/cursor sidecar/`rename`/`trash` resolve via `folder(of:)`; audit fix: `folder(of:)` project loop applies scan's skip guards (dot-dirs, symlinks) so a hidden project can't shadow a visible piece; `mergedFrontmatter` key-rewrite folded into one ordered-pairs loop (complexity 11 → lint-clean). +- `PostsModel.swift` — `PostDraft` carries `project`; shared `targetProject` (selected non-archived post's project, else default) feeds `newPost()` + `importFiles`; watcher roots → `projects/` + `archive/` (both created by `bind`); `PostsWatcher.start(urls:)` takes an array. +- `EditorSession.swift` — `folderURL` is a stored property resolved once at init via `PostStore.folder(of:)` (fallback `projects/posts/` for a vanished piece), + test pinning the fallback. +- `PostEditorView.swift` / `PostsPaneView.swift` / `SettingsPaneView.swift` — breadcrumb renders the real ` / / / post.md` path; empty-state + repoint copy updated. +- Tests (4 files) — all fixtures re-rooted to `projects/posts//`; new cases: two-level scan across projects+archive, lenient `type`, archived-slug-never-reused, `writeNew(project:)` routing, rename-within-project + archive-stays-archived, trash-from-archive, external `type: outline` overwritten at import, unresolvable-id fallback, duplicate-id dedupe, hidden-project shadowing. +- Manual step done: the 4 dev posts moved by hand to `~/Documents/Museion/projects/posts//`, old `posts/` root removed (no migration machinery — the app never reads it, #103). +- DOX: Museion/AGENTS.md + MuseionTests/AGENTS.md truth-passed for the new layout. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Write paths resolve folder from id (`folder(of:)`), never thread (project, id) | ADR-0012: Piece ID is the durable identity; keeps sessions/sidecars/callers unchanged | +| Duplicate-id dedupe in `scan`, first-wins in `folder(of:)`'s exact order | Audit (security + general converged): a Finder copy across projects made every id-addressed write land on the sorted-first twin — silent wrong-piece edits/trash. One precedence, shared by row and write target | +| `folder(of:)` skips dot-dirs/symlinks like `scan` | Same audit: `projects/.trash/` sorted before visible projects and captured all writes | +| `type: post` stamped/normalized on save (unknown values → post) | Same our-keys-win rule #59 pinned for pass_state/origin; lenient-read + normalize-on-save | +| Import lands in the selected project (not just New) | Consistency: both are "new piece lands somewhere"; one `targetProject` helper | +| Deferred: per-piece write-refusal on ambiguous ids | Dedupe removes the wrong-write defect for S1; refusal UX belongs to S2's in-app moves slice | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| One `xcodebuild test` run printed `** TEST FAILED **` mid-verification | Every xcresult bundle in the window records 0 failing tests — runner-level flake (two parallel suite runs) | Re-ran; green ×3 since, incl. final full suite | +| `swiftformat .` reformatted spike/, prototypes/, 3 unrelated app files | Ran tree-wide instead of scoped | `git checkout --` the strays; scoped format after (happened twice — child did it too) | +| `folder(of:)` compile error: URL vs String | Converted listing to URL-based but still appended `project` directly | `project.lastPathComponent` | +| Dedupe guard placed before the post.md read | A lazy folder would consume the id before its readable twin | Moved `seen.insert` after the read | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostLibrary.swift` | two-level scan, ContentType/project/isArchived, duplicate-id dedupe | +| `Museion/PostStore.swift` | folder(of:) resolver, global availableSlug, project-aware write paths, type stamping | +| `Museion/PostsModel.swift` | PostDraft.project, targetProject, watcher on both roots | +| `Museion/EditorSession.swift` | stored folderURL resolved at init | +| `Museion/PostEditorView.swift` | real-path breadcrumb | +| `Museion/PostsPaneView.swift` | header + empty-state copy | +| `Museion/SettingsPaneView.swift` | repoint copy | +| `MuseionTests/{PostLibrary,PostStore,EditorSession,ImportExternal}Tests.swift` | re-rooted fixtures + 10 new cases | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX truth-pass + log window | + +## Open Items & Next Steps + +- [ ] S2 of map #97: library UI (variant B project sections, Archive nav-rail) + in-app project commands — the substrate carries `project`/`isArchived` for it +- [ ] Flag on #107 when closing: "selected project" reads as "selected non-archived post, else default" in the implementation +- [ ] Per-piece duplicate-id write-refusal (or in-app resolution UX) if S2's moves make duplicates reachable from the app +- [ ] Ceiling comments name the O(projects) walks (`folder(of:)`, `availableSlug`) — cache only if they ever measure hot + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 362ac0b..ec94eaa 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-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 | | 2026-10-08 | issue | [20261008-issue84-view-menu-doubled_log.md](20261008-issue84-view-menu-doubled_log.md) | #84 single View menu: CommandMenu → CommandGroup(after: .toolbar), menu-count pin test — 105 tests green |