diff --git a/AGENTS.md b/AGENTS.md
index 3af2b3d..6f0323d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -132,7 +132,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** (4295 symbols, 15151 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
+This project is indexed by GitNexus as **museion** (4323 symbols, 15235 relationships, 300 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).
@@ -180,6 +180,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| Date | Log |
|------|-----|
+| 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) |
| 2026-10-22 | [20261022-issue29-research-library-light_log.md](docs/devlog/20261022-issue29-research-library-light_log.md) |
| 2026-10-22 | [20261022-issue28-session-lifecycle-ui_log.md](docs/devlog/20261022-issue28-session-lifecycle-ui_log.md) |
| 2026-10-21 | [20261021-issue27-dismiss-decay-learnings_log.md](docs/devlog/20261021-issue27-dismiss-decay-learnings_log.md) |
@@ -189,5 +190,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-20 | [20261020-issue24-pass-guard-matrix_log.md](docs/devlog/20261020-issue24-pass-guard-matrix_log.md) |
| 2026-10-20 | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](docs/devlog/20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) |
| 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) |
-| 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index acfdc4d..44f5d84 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
+- **sessions:** New Post from Session & drill offers (PRD S2.7/S2.8) — a freeform Session births a Post: "New Post" in the Sessions pane opens an ask-before sheet prefilled with the session's last mentor reply (editable, G9), and ONE confirm materializes the piece under `projects/posts/` stamped `origin: ai` — immutable frontmatter, never stats-eligible — and opens it in Posts; a failed write keeps the sheet up with the reason inline and the draft intact. "New Brainstorm" is a session started with an opener prompt (session flavor, no new machinery). The freeform composer (input + liveness + Stop) moved into the shared `SessionTranscriptView`, so both session surfaces are conversations; session-born pieces and the resume rail are pinned (issue #30). Resume now speaks the REAL adapter wire: 0.21.5 answers `session/load` with `_meta.hermes.sessionProvenance.acpSessionId` and no top-level `sessionId` — resume accepts both shapes (live-probed; every prior real-engine resume misread as "unknown") (issue #30)
+
- **mentor:** Research & library-light (PRD S8, G9) — the mentor researches mid-pass and its findings arrive as candidate source-notes with provenance inside their Session: a third museion-tools tool `submit_research_notes` is the typed rail (decode-validate only, replies `{"received": N}`, writes NOTHING — the session is the holding area), candidates ride the transcript as full cards parsed by payload shape (the `notes` array routes before the fix-card parse; titles are display text), and resume re-materializes them for free from the engine's replay (engine-owned cargo, ADR-0007 — dispositions reset honestly). The writer curates in place: Keep opens the ask-before sheet and ONE confirm lands one plain markdown note with provenance (`source`/`kept` frontmatter) into the piece's `research/` — anchored through the one `folder(of:)` id lookup, a symlinked `research/` refuses, collision -2; Reject vanishes, recording nothing. The pass prompt names the rail and forbids the engine writing candidates itself; kept notes flip `hasResearch`, so every later pass consults the library (issue #29)
- **sessions:** Session lifecycle UI (PRD S2.3, ADR-0007) — the mentor bridge hosts multiple engine-owned sessions on one child: per-session transcripts keyed by wire sessionId behind the same-named proxies (every existing caller compiles unchanged), a names-only roster at `~/Library/Application Support/Museion/sessions.json` (0600; id/name/pieceTitle/date — the words stay engine-owned), and the standard affordances over the wire: `session/new`, `session/load` (the engine replays the full history before responding — user turns included), `session/fork`, compact as the `/compress` slash prompt, `session/cancel` as the Stop rail. The Sessions pane replaces its placeholder: roster list (piece-associated by name when Posts has an open piece), row-click resume, Fork · Compact, live streaming with Stop; every pass auto-creates its rostered session ("Pass N · \
") and streams into it; the transcript renderer is shared with the mentor pane. Resume refusals are honest and entry-attributed (an engine-unknown session never fabricates history), concurrent replays refuse instead of interleaving, restart replays from the engine, and the notification hops ride the main queue so the adapter's replay-before-response contract is guaranteed. Finish-audit (three reviewers) surfaced the concurrent-resume race, the dead restart branch, the runPass guard window, the 15 s session/load default, and the missing createSession backstop — all fixed and pinned (issue #28)
diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md
index 0d163fa..4db3b4c 100644
--- a/Museion/AGENTS.md
+++ b/Museion/AGENTS.md
@@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Workspace shell (M1, #17 + #18 / S1.1)
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
-- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (plain + button; becomes a Menu — "New Session" / "New Session on \" — when Posts has an open piece; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, Fork · Compact bordered mono-11, both disabled on `!canStartSession`) + the liveness row (ProgressView + Stop → `stopStreaming` — cancel works from the pane) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer lives in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates. **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).
+- `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). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
-- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws). **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name.
+- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `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). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws). **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name.
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
-- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#28: `mentor.beginPassSession(kind:pieceTitle:)` — every pass auto-creates its Session (wire session/new, rostered "Pass N · \", activated; the `runningPass` flag goes live only AFTER these awaits — setting it earlier left a window where the #124 Cancel pin could observe the flag with `isStreaming` still false and the cancel refused, the turn hung)** → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · ")` (the label renders, the wire stub never lands; the prompt lands in the pass's OWN session) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit).
+- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#28: `mentor.beginPassSession(kind:pieceTitle:)` — every pass auto-creates its Session (wire session/new, rostered "Pass N · \", activated; the `runningPass` flag goes live only AFTER these awaits — setting it earlier left a window where the #124 Cancel pin could observe the flag with `isStreaming` still false and the cancel refused, the turn hung)** → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · ")` (the label renders, the wire stub never lands; the prompt lands in the pass's OWN session) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit).
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
@@ -72,7 +72,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): engine state machine (idle/starting/ready/crashed; `isStreaming` Bool; **#28: `.ready` carries NO sessionId — session ids live in the roster**). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`; **#28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)**), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks). **#28: the handshake is initialize ONLY — sessions are created separately (`newSession`/`beginPassSession`/`ensureDefaultSession`), the bridge is session-agnostic.** `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
- **#28 (S2.3) session lifecycle:** the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId; `rows`/`streamingText`/`streamingThought` are same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged). `SessionEntry` (nonisolated, Codable: `sessionId`/`name`/`pieceTitle`/`createdAt`) + `SessionRoster` (nonisolated; JSON array at `~/Library/Application Support/Museion/sessions.json`, `rosterDirectory` injectable — `init(binaryPath:rosterDirectory:)`; an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). **The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand.** API: `newSession(name:pieceTitle:)` (wire session/new, rostered newest-first, activated), `resumeSession(_)` (wire session/load — the adapter replays full history as `session/update` BEFORE responding; user turns arrive as `user_message_chunk` and RENDER on replay, live-turn echoes stay ignored; a result without sessionId = the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session), `forkActiveSession()` (wire session/fork → " (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginPassSession(kind:pieceTitle:)` ("Pass N · \", rostered + activated — the pass auto-create rail), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. **#29 (S8.1–S8.3) research candidates:** `ResearchCandidate` (nonisolated: piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote` — `appendToolCall` routes on PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses via `ResearchCandidate.batch` (one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted). `setResearchDisposition(rowID:_:)` flips the ACTIVE session's row in place (unknown id = no-op). `isWritingRow` keeps `.researchNote` visible in the writing voice.
+ **#28 (S2.3) session lifecycle:** the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId; `rows`/`streamingText`/`streamingThought` are same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged). `SessionEntry` (nonisolated, Codable: `sessionId`/`name`/`pieceTitle`/`createdAt`) + `SessionRoster` (nonisolated; JSON array at `~/Library/Application Support/Museion/sessions.json`, `rosterDirectory` injectable — `init(binaryPath:rosterDirectory:)`; an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). **The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand.** API: `newSession(name:pieceTitle:)` (wire session/new, rostered newest-first, activated), `resumeSession(_)` (wire session/load — the adapter replays full history as `session/update` BEFORE responding; user turns arrive as `user_message_chunk` and RENDER on replay, live-turn echoes stay ignored; **#30 dogfood: the REAL 0.21.5 load response carries NO top-level `sessionId` — the id rides `_meta.hermes.sessionProvenance.acpSessionId`, so extraction accepts both shapes and empty-everywhere alone means the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session; the top-level-only read made every real-engine resume fail as "unknown"**), `forkActiveSession()` (wire session/fork → " (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginPassSession(kind:pieceTitle:)` ("Pass N · \", rostered + activated — the pass auto-create rail), `beginBrainstormSession(pieceTitle:)` (#30: the brainstorm flavor — a "Brainstorm" rostered session whose first turn is `brainstormPrompt`, the normal prompt rail, no new machinery; pinned: roster head + labeled opener + raw prompt absent + reply streams into ITS transcript), `draftCandidateText()` / `draftCandidateText(in:)` (#30: the New-Post-from-Session candidate — the LAST "Mentor: " text row, prefix stripped; user/thought/card/research/raw rows never prefill, blank bodies skipped, and the refusal/connection-shaped rows sharing the display prefix are excluded — ponytail-marked until SessionRow carries speaker identity), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. **#29 (S8.1–S8.3) research candidates:** `ResearchCandidate` (nonisolated: piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote` — `appendToolCall` routes on PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses via `ResearchCandidate.batch` (one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted). `setResearchDisposition(rowID:_:)` flips the ACTIVE session's row in place (unknown id = no-op). `isWritingRow` keeps `.researchNote` visible in the writing voice.
- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (running version + orange drift note — **#28: the version shows `activeEntry`'s id alongside, `.ready` no longer carries it**; trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `title(of:)`), Cancel/Promote; ONE confirm → `promoteCard`, refusal inline orange with buttons kept (ApplyAskSheet posture). **#29 (S8.3):** the transcript renders `.researchNote` as full candidate cards (NOT one-line events — a handful of notes curates in place, no palette): serif-13 title, mono-11 muted url, selectable note, muted-italic quote; pending offers Keep + Reject (mono-11 bordered; hidden when the pane's `home` is nil — previews), kept/rejected dim 0.45 (closed-card voice) with meta `kept · research/` / `rejected`; the Mentor pane passes its `home`, the Sessions pane gains `home: URL?` (WorkspaceView hands `gate.museionHome`). Keep = ask-before (G9): `ResearchKeepSheet` (own file, PromoteAskSheet posture — "Keep this research note?", the nothing-saves-until-you-keep line, note preview, Cancel/Keep; ONE confirm → `PostStore.writeResearchNote` → disposition flips, refusal inline orange with buttons kept). Reject = no confirm (Dismiss-button voice — vanishes, nothing recorded). The sheet state lives in SessionTranscriptView (`pendingKeep`, `.sheet(item:)` over the transcript — never inside a lazy row).
- Wiring: `AppGateState.mentor` is the app-scoped model ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss).
- Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
diff --git a/Museion/MentorPaneView.swift b/Museion/MentorPaneView.swift
index 77ec7d1..8ca7a75 100644
--- a/Museion/MentorPaneView.swift
+++ b/Museion/MentorPaneView.swift
@@ -11,7 +11,6 @@ import SwiftUI
/// The mentor debug pane: transcript, freeform input, Stop while streaming,
/// restart prompt on crash. Post-gate main surface (map decision).
struct MentorPaneView: View {
- @State private var draft = ""
@State private var model: MentorSessionModel
/// #23 follow-up: opens the Fix Cards palette window (scene "fix-cards").
@Environment(\.openWindow) private var openWindow
@@ -72,10 +71,9 @@ struct MentorPaneView: View {
Divider()
}
// #28: the transcript rendering is shared — the Sessions pane
- // reads the same surface in the writing voice.
+ // reads the same surface in the writing voice. #30: the
+ // freeform input + liveness ride the shared surface too.
SessionTranscriptView(model: model, showsDebugRows: debugRows, home: home)
- Divider()
- inputBar
case let .crashed(lastPrompt):
crashCard(lastPrompt: lastPrompt)
}
@@ -157,61 +155,14 @@ struct MentorPaneView: View {
}
}
-// MARK: Input + crash card (file-scope extension — type_body_length posture)
+// MARK: Crash card (file-scope extension — type_body_length posture; the
+
+// freeform composer moved to the shared SessionTranscriptView in #30)
private extension MentorPaneView {
- // MARK: Input
-
- private var inputBar: some View {
- VStack(alignment: .leading, spacing: 8) {
- // Liveness: a pass legitimately runs minutes of silent tool work
- // (skill loads, learnings) — without this the pane reads as dead
- // (dogfood #23: "hard to tell if it is still thinking").
- if model.isStreaming {
- HStack(spacing: 8) {
- ProgressView()
- .controlSize(.small)
- Text("Mentor is working — Stop to interrupt.")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- }
- HStack(spacing: 8) {
- TextField("Ask the mentor…", text: $draft, axis: .vertical)
- .textFieldStyle(.plain)
- .lineLimit(1 ... 4)
- .onSubmit { send() }
- Button {
- send()
- } label: {
- Image(systemName: "arrow.up.circle.fill")
- .font(.title2)
- }
- .buttonStyle(.plain)
- .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
- if model.isStreaming {
- Button {
- model.stopStreaming()
- } label: {
- Text("Stop")
- }
- .controlSize(.regular)
- }
- }
- }
- .padding(12)
- .disabled(model.phase.isReady == false)
- }
-
- private func send() {
- let text = draft
- draft = ""
- Task { await model.sendPrompt(text) }
- }
-
// MARK: Crash → restart prompt (map decision: EOF/crash surfaces an
- // in-pane Restart prompt; the transcript replays from the engine (ADR-0007)
+ // in-pane Restart prompt; the transcript replays from the engine, ADR-0007)
private func crashCard(lastPrompt: String?) -> some View {
VStack(spacing: 14) {
diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift
index dc6ed6f..499271e 100644
--- a/Museion/MentorSessionModel.swift
+++ b/Museion/MentorSessionModel.swift
@@ -407,6 +407,23 @@ final class MentorSessionModel {
return await createSession(name: "\(kind.rawValue) · \(pieceTitle)", pieceTitle: pieceTitle)
}
+ /// #30 (S2.7): the brainstorm flavor — a plain freeform session whose
+ /// first turn is the brainstorm prompt (PRD S2.8: no new machinery).
+ /// Nil when the session couldn't be created; the opener rides the
+ /// normal prompt rail and streams like any turn.
+ @discardableResult
+ func beginBrainstormSession(pieceTitle: String?) async -> SessionEntry? {
+ guard let entry = await newSession(name: "Brainstorm", pieceTitle: pieceTitle) else { return nil }
+ _ = await sendPrompt(Self.brainstormPrompt, label: "Brainstorm")
+ return entry
+ }
+
+ /// #30 (S2.7): the brainstorm opener — questions over prose.
+ nonisolated static let brainstormPrompt =
+ "Let's brainstorm together. Ask me one question at a time to draw out ideas "
+ + "and angles for what I want to write — keep replies short and generative, "
+ + "and don't draft prose unless I ask."
+
/// The shared creation rail behind newSession/beginPassSession.
private func createSession(name: String, pieceTitle: String?) async -> SessionEntry? {
// Finish-audit backstop: fork guards !isStreaming; the views disable
@@ -491,8 +508,20 @@ final class MentorSessionModel {
timeout: Self.promptTimeout,
)
replayingSessionId = nil
- // null/absent (or empty) sessionId in the result = the engine does not know it.
- guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
+ // The real adapter (0.21.5, live-verified #30 dogfood) answers
+ // session/load WITHOUT a top-level sessionId — the id rides
+ // `_meta.hermes.sessionProvenance.acpSessionId`. The fake's
+ // top-level shape stays accepted (the older contract).
+ let resultObject = result?.objectValue
+ let provenance = resultObject?["_meta"]?
+ .objectValue?["hermes"]?
+ .objectValue?["sessionProvenance"]?
+ .objectValue
+ let sid = resultObject?["sessionId"]?.stringValue
+ ?? provenance?["acpSessionId"]?.stringValue
+ ?? ""
+ // null/absent everywhere = the engine does not know it.
+ guard !sid.isEmpty else {
// The refusal belongs to the ENTRY — attributed, and visible
// on its next row click (the store is kept, not discarded).
appendRow(
@@ -821,6 +850,38 @@ extension MentorSessionModel {
}
}
+// MARK: New Post from Session (#30, S2.7)
+
+extension MentorSessionModel {
+ /// The draft candidate for New Post from Session: the ACTIVE session's
+ /// last mentor text row, "Mentor: " prefix stripped. Feeds the ask
+ /// sheet's prefill.
+ func draftCandidateText() -> String? {
+ Self.draftCandidateText(in: rows)
+ }
+
+ /// The pure extraction (test seam): scan backwards — the LAST mentor
+ /// text row wins; user rows and thought/card/research/raw rows never
+ /// prefill. Blank bodies are skipped so a whitespace leftover can't
+ /// blank the prefill while an earlier real reply still exists.
+ static func draftCandidateText(in rows: [SessionRow]) -> String? {
+ for row in rows.reversed() {
+ guard case let .text(text) = row.content, text.hasPrefix("Mentor: ") else { continue }
+ // ponytail: refusal/connection rows share the display prefix —
+ // excluded by their known shapes until SessionRow carries speaker
+ // identity (an enum reshape is its own ticket).
+ if text.hasPrefix("Mentor: (refused") || text.hasPrefix("Mentor: connection lost") {
+ continue
+ }
+ let body = text.dropFirst("Mentor: ".count).trimmingCharacters(in: .whitespacesAndNewlines)
+ if !body.isEmpty {
+ return String(body)
+ }
+ }
+ return nil
+ }
+}
+
/// Research-candidate batch parsing (#29): the submit_research_notes wire
/// shape {piece_path, notes: [{title, url, quote?, note?}]} — one candidate
/// PER note. Lenient: a missing piece_path, an empty/absent notes array, or
diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift
index 0c34193..c2f7d83 100644
--- a/Museion/PostStore.swift
+++ b/Museion/PostStore.swift
@@ -146,12 +146,17 @@ nonisolated enum PostStore {
/// with the #59 block stamped (plus `type`, #107). Pass State First
/// Draft, origin writer — the only values #18 writes; the folder appears
/// here, never on New Post. #109: `type` lets the outliner birth outline
- /// pieces; prose pieces keep the default.
- static func writeNew(body: String, project: String = Post.defaultProject, type: Post.ContentType = .post, home: URL) throws -> Post {
+ /// pieces; prose pieces keep the default. #30 (S2.7): `origin` lets a
+ /// session-born Post stamp `origin: ai` (never stats-eligible); the
+ /// default stays `.writer`, so every existing caller compiles unchanged.
+ static func writeNew(
+ body: String, project: String = Post.defaultProject, type: Post.ContentType = .post,
+ origin: Post.Origin = .writer, home: URL,
+ ) throws -> Post {
try materialize(
- text: stamped(body: body, passState: .firstDraft, origin: .writer, type: type),
+ text: stamped(body: body, passState: .firstDraft, origin: origin, type: type),
title: Post.title(of: body),
- origin: .writer,
+ origin: origin,
project: project,
type: type,
home: home,
diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift
index f091982..22b4d17 100644
--- a/Museion/PostsModel.swift
+++ b/Museion/PostsModel.swift
@@ -299,6 +299,24 @@ final class PostsModel {
}
}
+ /// #30 (S2.7): New Post from Session — materialize the session-born
+ /// draft stamped `origin: ai` (never stats-eligible) and open it in
+ /// Posts (select's open path; the WorkspaceView selection onChange
+ /// hops the pane). Nil + lastError on failure; Cancel never gets here.
+ @discardableResult
+ func newPostFromSession(body: String, home: URL) -> Post? {
+ do {
+ let post = try PostStore.writeNew(body: body, origin: .ai, home: home)
+ select(post.id, home: home)
+ lastError = nil
+ Task { await rescan() }
+ return post
+ } catch {
+ lastError = error.localizedDescription
+ return nil
+ }
+ }
+
/// Select a Post; selecting anything abandons an unsaved draft (the
/// draft otherwise hijacks the editor — its only exits are save or
/// selecting away). #19: opening a post ends the previous session
diff --git a/Museion/SessionTranscriptView.swift b/Museion/SessionTranscriptView.swift
index 8b8f9ef..21737e0 100644
--- a/Museion/SessionTranscriptView.swift
+++ b/Museion/SessionTranscriptView.swift
@@ -10,10 +10,12 @@
import SwiftUI
-/// The shared session transcript — the ACTIVE session's rows + streaming
-/// buffers, extracted from MentorPaneView in #28 so the Sessions pane reads
-/// the same surface. Writing voice: pass `showsDebugRows: false` (the debug
-/// toggle stays the Mentor pane's).
+/// The shared session surface — the ACTIVE session's rows + streaming
+/// buffers + the freeform input rail (#28, extracted from MentorPaneView so
+/// the Sessions pane reads the same surface; **#30: the composer moved here
+/// too — a session is a conversation, and every session surface offers
+/// one**). Writing voice: pass `showsDebugRows: false` (the debug toggle
+/// stays the Mentor pane's).
struct SessionTranscriptView: View {
let model: MentorSessionModel
/// Raw session/tool rows, collapsed thinking, and live thinking render
@@ -26,6 +28,8 @@ struct SessionTranscriptView: View {
/// The ask-before keep (#29 G9): ONE blocking confirm per candidate,
/// presented over the transcript — never inside a lazy row.
@State private var pendingKeep: PendingKeep?
+ /// The freeform draft (#30: shared input rail).
+ @State private var draft = ""
private struct PendingKeep: Identifiable {
let rowID: UUID
@@ -36,6 +40,19 @@ struct SessionTranscriptView: View {
}
var body: some View {
+ VStack(spacing: 0) {
+ transcript
+ Divider()
+ inputBar
+ }
+ .sheet(item: $pendingKeep) { pending in
+ if let home {
+ ResearchKeepSheet(model: model, rowID: pending.rowID, candidate: pending.candidate, home: home)
+ }
+ }
+ }
+
+ private var transcript: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
ForEach(model.rows.filter { showsDebugRows || Self.isWritingRow($0) }) { row in
@@ -61,11 +78,55 @@ struct SessionTranscriptView: View {
// #24 fix: programmatic scrollTo raced the growing lazy rows and
// mislanded at the TOP; the native bottom anchor needs no scroll code.
.defaultScrollAnchor(.bottom)
- .sheet(item: $pendingKeep) { pending in
- if let home {
- ResearchKeepSheet(model: model, rowID: pending.rowID, candidate: pending.candidate, home: home)
+ }
+
+ /// The freeform composer + liveness — the Mentor pane's #23 rail,
+ /// shared with the Sessions pane (#30).
+ private var inputBar: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ // Liveness: a pass legitimately runs minutes of silent tool work
+ // (skill loads, learnings) — without this the pane reads as dead
+ // (dogfood #23: "hard to tell if it is still thinking").
+ if model.isStreaming {
+ HStack(spacing: 8) {
+ ProgressView()
+ .controlSize(.small)
+ Text("Mentor is working — Stop to interrupt.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ HStack(spacing: 8) {
+ TextField("Ask the mentor…", text: $draft, axis: .vertical)
+ .textFieldStyle(.plain)
+ .lineLimit(1 ... 4)
+ .onSubmit { send() }
+ Button {
+ send()
+ } label: {
+ Image(systemName: "arrow.up.circle.fill")
+ .font(.title2)
+ }
+ .buttonStyle(.plain)
+ .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
+ if model.isStreaming {
+ Button {
+ model.stopStreaming()
+ } label: {
+ Text("Stop")
+ }
+ .controlSize(.regular)
+ }
}
}
+ .padding(12)
+ .disabled(model.phase.isReady == false)
+ }
+
+ private func send() {
+ let text = draft
+ draft = ""
+ Task { await model.sendPrompt(text) }
}
/// The writing-session filter: prose + card events stay; raw rows and
diff --git a/Museion/SessionsPaneView.swift b/Museion/SessionsPaneView.swift
index 716f103..4c258da 100644
--- a/Museion/SessionsPaneView.swift
+++ b/Museion/SessionsPaneView.swift
@@ -23,6 +23,10 @@ struct SessionsPaneView: View {
var binaryPath: String?
/// #29 (S8.3): the Home a kept research note lands in.
var home: URL?
+ /// #30 (S2.7): the staged New Post from Session ask — the editable
+ /// draft candidate; nil = no sheet. The sheet is pane-local: this pane
+ /// holds posts + home, so no WorkspaceView staging is needed.
+ @State private var sessionDraft: String?
var body: some View {
VStack(spacing: 0) {
@@ -42,6 +46,24 @@ struct SessionsPaneView: View {
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
+ // #30 (S2.7): the ask prefills the candidate; dismissal is the
+ // cancel (nothing materializes).
+ .sheet(isPresented: Binding(
+ get: { sessionDraft != nil },
+ set: {
+ if !$0 {
+ sessionDraft = nil
+ }
+ },
+ )) {
+ NewPostFromSessionSheet(
+ draft: Binding(
+ get: { sessionDraft ?? "" },
+ set: { sessionDraft = $0 },
+ ),
+ create: { newPostFromSession() },
+ )
+ }
// Same lazy lifecycle as MentorPaneView: idempotent open — whichever
// surface the writer reaches first spawns the engine.
.task {
@@ -93,10 +115,8 @@ struct SessionsPaneView: View {
VStack(spacing: 0) {
actionsRow
Divider()
- if model.isStreaming {
- livenessRow
- Divider()
- }
+ // #30: transcript + freeform input + liveness ride the shared
+ // surface (the composer lives in SessionTranscriptView).
SessionTranscriptView(model: model, showsDebugRows: false, home: home)
}
}
@@ -118,6 +138,18 @@ struct SessionsPaneView: View {
.help(model.versionNote ?? version)
}
Spacer()
+ // #30 (S2.7): the draft candidate prefills the ask sheet (empty
+ // transcript → empty prefill — the sheet still works). Reads
+ // in-memory transcript rows — engine-free, never gated on
+ // canStartSession (a crashed engine must not strand the draft).
+ Button("New Post") {
+ sessionDraft = model.draftCandidateText() ?? ""
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .font(.system(size: 11, design: DesignTokens.mono))
+ .help("Start a Post from this session's draft candidate")
+ .accessibilityLabel("New Post from Session")
Button("Fork") {
Task { _ = await model.forkActiveSession() }
}
@@ -141,28 +173,6 @@ struct SessionsPaneView: View {
.padding(.vertical, 8)
}
- /// Liveness (the Mentor pane's #23 posture, no input bar here): silent
- /// tool work must not read as dead, Stop is the pane's Cancel affordance.
- private var livenessRow: some View {
- HStack(spacing: 8) {
- ProgressView()
- .controlSize(.small)
- Text("Mentor is working — Stop to interrupt.")
- .font(.caption)
- .foregroundStyle(.secondary)
- .lineLimit(1)
- Spacer()
- Button("Stop") {
- model.stopStreaming()
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
- .accessibilityLabel("Stop the mentor")
- }
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
- }
-
/// No second restart flow — the Mentor pane owns Restart (map decision).
private var crashedNote: some View {
VStack(spacing: 8) {
@@ -181,39 +191,48 @@ struct SessionsPaneView: View {
// MARK: New Session control
- @ViewBuilder
+ /// #30 (S2.7): one Menu in both states — New Brainstorm joined the
+ /// roster of actions, so the plain-button branch (single action) is
+ /// gone. Brainstorm rides the same piece association when Posts has
+ /// an open piece.
private var newSessionControl: some View {
- if let piece = Self.openPiece(in: posts) {
- Menu {
- Button("New Session") { createSession(associatedWith: nil) }
+ let piece = Self.openPiece(in: posts)
+ return Menu {
+ Button("New Session") { createSession(associatedWith: nil) }
+ if let piece {
Button("New Session on \(piece.title)") { createSession(associatedWith: piece.title) }
- } label: {
- Image(systemName: "plus")
}
- .menuStyle(.button)
- .buttonStyle(.plain)
- .foregroundStyle(DesignTokens.muted)
- .disabled(!model.canStartSession)
- .help("New Session")
- .accessibilityLabel("New Session")
- } else {
- Button {
- createSession(associatedWith: nil)
- } label: {
- Image(systemName: "plus")
+ Button("New Brainstorm") {
+ Task { _ = await model.beginBrainstormSession(pieceTitle: piece?.title) }
}
- .buttonStyle(.plain)
- .foregroundStyle(DesignTokens.muted)
- .disabled(!model.canStartSession)
- .help("New Session")
- .accessibilityLabel("New Session")
+ } label: {
+ Image(systemName: "plus")
}
+ .menuStyle(.button)
+ .buttonStyle(.plain)
+ .foregroundStyle(DesignTokens.muted)
+ .disabled(!model.canStartSession)
+ .help("New Session")
+ .accessibilityLabel("New Session")
}
private func createSession(associatedWith title: String?) {
Task { _ = await model.newSession(name: "New Session", pieceTitle: title) }
}
+ /// #30 (S2.7): the ask's confirm — materialize + open in Posts. Returns
+ /// the failure reason for the sheet's inline refusal (nil = written +
+ /// opened); a failed write keeps the sheet up with the draft intact
+ /// (ApplyAskSheet posture — the edited draft is never destroyed).
+ private func newPostFromSession() -> String? {
+ guard let posts, let home else { return "No library to write into." }
+ if posts.newPostFromSession(body: sessionDraft ?? "", home: home) == nil {
+ return posts.lastError ?? "The piece couldn't be written."
+ }
+ sessionDraft = nil
+ return nil
+ }
+
/// The open piece in Posts — the association target for the New Session
/// choice (nil = free-floating only). Static + posts-coupled: test-pinned.
static func openPiece(in posts: PostsModel?) -> Post? {
@@ -296,3 +315,60 @@ private struct SessionEntryRow: View {
return parts.joined(separator: " · ")
}
}
+
+/// #30 (S2.7): the New Post from Session ask — the draft candidate
+/// (the session's last mentor reply) prefills and stays editable.
+/// Confirm materializes the piece stamped `origin: ai` — never
+/// stats-eligible — and opens it in Posts; Cancel writes nothing.
+/// The error line is SHEET-LOCAL state: it dies with the presentation,
+/// so a re-opened ask never shows a stale refusal.
+private struct NewPostFromSessionSheet: View {
+ @Binding var draft: String
+ /// The confirm's failure reason — a failed write keeps the sheet up,
+ /// draft intact; dismissal itself is the cancel.
+ @State private var createError: String?
+ let create: () -> String?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("New Post from Session")
+ .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
+ Text(
+ "The draft starts from the session's last mentor reply. It lands in your library stamped origin: ai — never counted as your writing.",
+ )
+ .font(.callout)
+ .foregroundStyle(DesignTokens.muted)
+ TextEditor(text: $draft)
+ .font(.system(size: 13, design: DesignTokens.serif))
+ .frame(width: 380, height: 160)
+ .overlay(
+ RoundedRectangle(cornerRadius: DesignTokens.radius)
+ .strokeBorder(DesignTokens.border),
+ )
+ if let createError {
+ Text(createError)
+ .font(.system(size: 11, design: DesignTokens.mono))
+ .foregroundStyle(.orange)
+ }
+ HStack {
+ Spacer()
+ // Dismissal itself is the cancel (binding set(false) →
+ // sessionDraft = nil) — Esc and ⌘. land here too.
+ Button("Cancel", role: .cancel) {}
+ .keyboardShortcut(.cancelAction)
+ Button("Create Post", action: confirm)
+ .keyboardShortcut(.defaultAction)
+ .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ }
+ .padding(20)
+ .frame(width: 420)
+ }
+
+ /// No dismiss() here — success closes the sheet via the pane's
+ /// `sessionDraft = nil` (the binding); failure keeps it up with the
+ /// inline reason and the edited draft intact.
+ private func confirm() {
+ createError = create()
+ }
+}
diff --git a/MuseionTests/ACPClientTests.swift b/MuseionTests/ACPClientTests.swift
index f5aefab..b1d4941 100644
--- a/MuseionTests/ACPClientTests.swift
+++ b/MuseionTests/ACPClientTests.swift
@@ -150,12 +150,22 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
rnot='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$lsid"'","update":'
if [[ "$lsid" == sess-* ]]; then
# Full history replay, wire order, BEFORE the load response — the
- # real adapter's contract (#28).
+ # real adapter's contract (#28). The load RESPONSE carries NO
+ # top-level sessionId (0.21.5 live-verified, #30 dogfood): the id
+ # rides _meta.hermes.sessionProvenance.acpSessionId — resuming a
+ # minted id must ACCEPT this shape; an empty result stays the
+ # unknown-refusal.
echo $rnot'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"earlier ask"}}}}'
echo $rnot'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"old thinking"}}}}'
echo $rnot'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier verdict"}}}}'
echo $rnot'{"sessionUpdate":"tool_call","toolCallId":"tc2","title":"submit_research_notes","rawInput":'"$research"'}}}'
- echo $framing"$rid",'"result":{"sessionId":"'"$lsid"'"}}'
+ if [[ "$mode" == "loadReplayLegacy" ]]; then
+ # #30 audit knob: the OLDER contract - top-level sessionId, no
+ # provenance. resumeSession must accept BOTH shapes.
+ echo $framing"$rid\",'\"result\":{\"sessionId\":\"'"$lsid"'\"}}'
+ continue
+ fi
+ echo $framing"$rid\",'\"result\":{\"modes\":[],\"_meta\":{\"hermes\":{\"sessionProvenance\":{\"acpSessionId\":\"'\"$lsid\"'\"}}}}}'
else
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
fi
diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md
index 72172e6..5f86b9f 100644
--- a/MuseionTests/AGENTS.md
+++ b/MuseionTests/AGENTS.md
@@ -18,15 +18,15 @@ Owned by the root AGENTS.md contract.
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- `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` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). 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. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; an unknown id answers WITHOUT a sessionId), `session/fork` → fresh `F-` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
+- `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` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). 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. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `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. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects///` + `archive///` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
-- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects///` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects///post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted.
+- `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, writeNew outline stamping (#109: `type: outline` first line, `projects///post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted.
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · " renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#28:** one roster pin — a completed pass grows the roster with "Pass 1 · \" active (the auto-created session).
-- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass auto-creates its session (rostered "Pass 1 · \" newest-first, active, pass streams into ITS transcript), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork (" (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key).
+- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass auto-creates its session (rostered "Pass 1 · \" newest-first, active, pass streams into ITS transcript), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork (" (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key).
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native ``, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift
index ad78347..3f2b172 100644
--- a/MuseionTests/PostStoreTests.swift
+++ b/MuseionTests/PostStoreTests.swift
@@ -150,6 +150,49 @@ private func readPost(_ home: URL, _ id: String) throws -> String {
#expect(try readPost(home, post.id).hasPrefix("---\ntype: post\n"))
}
+// Scenario: New Post from Session — from #30 (S2.7). Given a freeform
+// session whose transcript holds mentor text, when the writer picks
+// "New Post from Session" and confirms the ask sheet, then a piece folder
+// materializes under projects/posts/ with the draft body and origin: ai
+// stamped, and Museion opens the piece in Posts.
+@Test func `writeNew origin ai stamps the session-born piece and scans back`() throws {
+ let home = try storeHome()
+ let post = try PostStore.writeNew(
+ body: "# From the Session\n\nMentor text becomes the draft.",
+ origin: .ai,
+ home: home,
+ )
+
+ #expect(post.origin == .ai)
+ #expect(post.id == "from-the-session")
+ #expect(post.project == Post.defaultProject) // default posts/ landing
+ #expect(post.passState == .firstDraft)
+ #expect(try readPost(home, post.id)
+ == "---\ntype: post\npass_state: First Draft\norigin: ai\n---\n# From the Session\n\nMentor text becomes the draft.")
+
+ // The #17 reader reads it back as an ai piece.
+ let scanned = try #require(Post.scan(home: home).first)
+ #expect(scanned.origin == .ai)
+}
+
+@Test func `writeNew default origin stays writer for existing callers`() throws {
+ let home = try storeHome()
+ // #30: the additive parameter — saveDraft's call shape is unchanged.
+ let post = try PostStore.writeNew(body: "# Plain\n", home: home)
+ #expect(post.origin == .writer)
+ #expect(try readPost(home, post.id).contains("origin: writer"))
+}
+
+@Test func `a session-born ai piece keeps origin ai through overwrite`() throws {
+ // #30: immutability is the AC — the save path preserves the ai stamp.
+ let home = try storeHome()
+ let post = try PostStore.writeNew(body: "# From the Session\n\nv1", origin: .ai, home: home)
+ try PostStore.overwrite(id: post.id, body: "# From the Session\n\nedited v2", home: home)
+ let scanned = try #require(Post.scan(home: home).first)
+ #expect(scanned.origin == .ai)
+ #expect(try readPost(home, post.id).contains("origin: ai\n"))
+}
+
@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)
diff --git a/MuseionTests/SessionLifecycleTests.swift b/MuseionTests/SessionLifecycleTests.swift
index ba3331a..c452a92 100644
--- a/MuseionTests/SessionLifecycleTests.swift
+++ b/MuseionTests/SessionLifecycleTests.swift
@@ -217,6 +217,55 @@ struct SessionLifecycleTests {
_ = await chat.value
}
+ // Scenario: Brainstorm session — from #30 (S2.7). Given a ready engine,
+ // when the writer picks "New Brainstorm", then a rostered "Brainstorm"
+ // session activates and the mentor receives the opener — a session
+ // started with a prompt, no new machinery.
+ @Test @MainActor func `brainstorm opens a rostered session with the labeled opener`() async throws {
+ let (model, home, mentor) = try makePassRig()
+ defer { mentor.shutdown() }
+ await mentor.openSession()
+ _ = model
+ _ = home
+
+ let entry = try #require(await mentor.beginBrainstormSession(pieceTitle: "Draft Piece"))
+
+ // Rostered newest-first, named "Brainstorm", piece-associated, active.
+ #expect(mentor.roster.first?.name == "Brainstorm")
+ #expect(entry.pieceTitle == "Draft Piece")
+ #expect(mentor.activeEntry?.id == entry.id)
+ // The opener rides the labeled rail — the raw prompt never renders.
+ #expect(texts(in: mentor.transcriptRows(of: entry)).contains("Brainstorm"))
+ #expect(!texts(in: mentor.transcriptRows(of: entry)).contains { $0.contains("Let's brainstorm together") })
+ // The mentor's reply streams into the NEW session's transcript.
+ var streamed = false
+ for _ in 0 ..< 250 {
+ streamed = texts(in: mentor.transcriptRows(of: entry)).contains { $0.contains("Hello mentor.") }
+ if streamed {
+ break
+ }
+ try await Task.sleep(nanoseconds: 20_000_000)
+ }
+ #expect(streamed)
+ }
+
+ /// #30 audit pin: the real 0.21.5 wire answers load with the provenance
+ /// shape (pinned by every other resume test via the fake's default);
+ /// the OLDER top-level-sessionId contract stays accepted — the knob
+ /// flips the fake to that shape and the resume must still succeed.
+ @Test @MainActor func `resume accepts the legacy top-level sessionId shape`() async throws {
+ let (model, home, mentor) = try makePassRig(mode: "loadReplayLegacy")
+ defer { mentor.shutdown() }
+ await mentor.openSession()
+ _ = model
+ _ = home
+
+ let entry = try #require(await mentor.newSession(name: "Legacy", pieceTitle: nil))
+ let resumed = await mentor.resumeSession(entry)
+ #expect(resumed)
+ #expect(mentor.activeEntry?.id == entry.id)
+ }
+
/// #28 AC4 (ownership) + review fix (the default open RESUMES): a new
/// model over the same roster directory restores every entry — the
/// roster FILE carries no transcript payload (pinned against the raw
@@ -406,6 +455,51 @@ struct SessionLifecycleTests {
return false
})
}
+
+ // Scenario: draft candidate — from #30 (S2.7). Given a session
+ // transcript, when the sheet prefills, then the last mentor text row is
+ // the draft candidate; thought/card/research/raw rows never prefill.
+ @Test @MainActor func `draft candidate is the last mentor text row`() {
+ let rows: [SessionRow] = [
+ SessionRow(content: .text("You: help me draft this")),
+ SessionRow(content: .thought("thinking hard about angles")),
+ SessionRow(content: .text("Mentor: first reply")),
+ SessionRow(content: .researchNote(ResearchCandidate(
+ piecePath: "/tmp/piece", title: "T", url: "https://x", quote: "", note: "",
+ ))),
+ SessionRow(content: .fixCard(FixCard(
+ pattern: "p", problem: "pr", diagnosticQuestion: "d", fix: "f",
+ anchor: "a", provenance: "engine", status: "open",
+ ))),
+ SessionRow(content: .raw(kind: "tool call", json: "{}")),
+ SessionRow(content: .text("Mentor: second and latest reply")),
+ ]
+ #expect(MentorSessionModel.draftCandidateText(in: rows) == "second and latest reply")
+ }
+
+ @Test @MainActor func `no mentor text yields no draft candidate`() {
+ // Empty transcript, user-only, and non-text lanes never prefill.
+ #expect(MentorSessionModel.draftCandidateText(in: []) == nil)
+ #expect(MentorSessionModel.draftCandidateText(in: [
+ SessionRow(content: .text("You: hello")),
+ SessionRow(content: .thought("hm")),
+ ]) == nil)
+ // A trailing blank mentor row doesn't blank the prefill — the
+ // earlier real reply is still the candidate.
+ #expect(MentorSessionModel.draftCandidateText(in: [
+ SessionRow(content: .text("Mentor: the real reply")),
+ SessionRow(content: .text("Mentor: ")),
+ ]) == "the real reply")
+ // Refusal/connection rows share the display prefix — an error is
+ // not the draft; an earlier reply still wins, error-only yields nil.
+ #expect(MentorSessionModel.draftCandidateText(in: [
+ SessionRow(content: .text("Mentor: the real reply")),
+ SessionRow(content: .text("Mentor: connection lost — broken pipe")),
+ ]) == "the real reply")
+ #expect(MentorSessionModel.draftCandidateText(in: [
+ SessionRow(content: .text("Mentor: (refused the prompt)")),
+ ]) == nil)
+ }
}
@MainActor
diff --git a/docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md b/docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md
new file mode 100644
index 0000000..43f8e4e
--- /dev/null
+++ b/docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md
@@ -0,0 +1,67 @@
+# Sessions: New Post from Session & drill offers (S2.7–S2.8)
+
+> **Date:** 2026-10-22
+> **Type:** issue
+> **Reference:** [Gitea #30](https://git.babylondreams.de/AlexKucera/museion/issues/30) (PRD S2.7, S2.8; blocked-by #24/#28 both closed)
+
+## Goal
+
+A freeform Session can birth a Post (New Post from Session: piece folder, draft, immutable `origin: ai` — never stats-eligible); drill offers ride the pass finding's motivation moment as pure session flavor; brainstorming is a session started with a brainstorm prompt.
+
+## What Was Done
+
+- `PostStore.writeNew` gains `origin: Post.Origin = .writer` (additive default — every existing caller compiles); the session-born path passes `.ai` via `PostsModel.newPostFromSession` (write + select + rescan).
+- `MentorSessionModel.beginBrainstormSession(pieceTitle:)` — a "Brainstorm" rostered session whose first turn is `brainstormPrompt` over the normal prompt rail; the Sessions pane's New Session control became one Menu ("New Session" / "New Session on \" / "New Brainstorm").
+- `NewPostFromSessionSheet` (pane-local, PromoteAskSheet posture): editable draft candidate prefilled by `MentorSessionModel.draftCandidateText` (the last "Mentor: " text row, prefix stripped; refusal/connection-shaped rows excluded — ponytail-marked until SessionRow carries speaker identity). Sheet-local error state via `create: () -> String?` — a failed write keeps the sheet up with the edited draft intact.
+- The shared `SessionTranscriptView` now carries the freeform composer + liveness + Stop (moved out of MentorPaneView's private extension) — one conversation surface, two panes; MentorPaneView keeps crash card + debug toggle.
+- Sessions actions row: **New Post · Fork · Compact** — Fork/Compact gated on `canStartSession`, New Post never engine-gated (it reads in-memory transcript rows).
+- **Resume wire fix (#30 dogfood):** the real adapter 0.21.5 answers `session/load` with NO top-level `sessionId` — the id rides `_meta.hermes.sessionProvenance.acpSessionId`. `resumeSession` accepts both shapes; empty-everywhere alone is the unknown-refusal. Live-probed against the real engine binary (create → kill -9 → fresh engine → load) before fixing; the fake ACP server now answers load in the real shape (+ a `loadReplayLegacy` knob pinning the older contract's acceptance).
+- Pass persona v1.4: "One drill may ride the strongest finding" — the trigger for the seeded micro-drill doctrine (the offer itself is engine-side by design: session flavor, no machinery beyond S2.3).
+- Finish-audit (three reviewers, parallel): the triple-converged `confirm()` dismissal bug (failed write destroyed the edited draft), stale-error-on-reopen, zero brainstorm pins, untested legacy resume branch — all fixed with pins.
+
+## Decisions & Rationale
+
+| Decision | Rationale |
+|----------|-----------|
+| Draft = last mentor text row, edited in an ask-before sheet before anything writes | G9 ask-before; the writer curates — no auto-extraction of "the draft" from a transcript that mixes verdicts, drills, and debriefs |
+| Draft candidate extraction string-matches "Mentor: " with a ponytail ceiling | Speaker identity in `SessionRow` is an enum reshape with renderer/replay blast radius — its own ticket; one guarded extraction point covers the class |
+| New Post lands in default project `posts`, title = first body line | Sessions pane has no selected-project context; house slug/title conventions cover the rest |
+| Drill wiring = one persona section, zero app code | PRD S2.8: "session flavor, no machinery beyond S2.3" — the seeded micro-drill skill owns the doctrine (motivation moment, ≤2 min, single shelf, the vanish) |
+| Composer lives in `SessionTranscriptView` | The Sessions pane shipped #28 as a read-only transcript; a brainstorm that asks questions with no way to answer is a dead end — one composer, two panes, duplicate deleted |
+| Resume reads both load-response shapes | Live-probed: the real wire carries the id in provenance only; the fake's top-level shape stays accepted as the older contract — each branch has its own pin |
+| Brainstorm opener outcome discarded (`_ = await sendPrompt`) | Exact `compactActiveSession` posture — failures surface as transcript rows |
+
+## Gotchas & Fixes
+
+| Problem | Root Cause | Fix |
+|---------|------------|-----|
+| "Unable to switch sessions" + "The engine does not know 'Brainstorm'" | #28's resume read only the top-level `sessionId` the real adapter never sends — every real-engine resume misread as engine-unknown | Provenance fallback in `resumeSession`; fake corrected to the real shape so the whole resume suite guards the live wire |
+| Two consecutive single-test failures in full-suite runs (`cancelling a held pass`, `runPass snapshots`) | Real-Process fake-ACP tests are load-sensitive; concurrent builds/analyzes stressed them | Verified each passes in isolation; the definitive full-suite run was made on an idle machine |
+| First `confirm()` fix incomplete — the sheet still dismissed on failure | The pane kept the draft but the sheet's unconditional `dismiss()` niled it via the binding | Triple-converged audit finding: `dismiss()` deleted; sheet-local error state; flip-cycle verified on the resume pins |
+
+## Files Changed
+
+| File | Change Summary |
+|------|---------------|
+| `Museion/PostStore.swift` | `writeNew` origin param (additive, default `.writer`) |
+| `Museion/PostsModel.swift` | `newPostFromSession(body:home:)` — write `origin: ai` + select + rescan |
+| `Museion/MentorSessionModel.swift` | `beginBrainstormSession`, `brainstormPrompt`, `draftCandidateText`, resume provenance fallback |
+| `Museion/SessionTranscriptView.swift` | Shared composer + liveness + Stop (moved from MentorPaneView) |
+| `Museion/SessionsPaneView.swift` | New Post action + ask sheet, unified New Session menu, engine-free New Post gate |
+| `Museion/MentorPaneView.swift` | Duplicate composer deleted; crash card kept |
+| `MuseionTests/ACPClientTests.swift` | Fake load answers the real provenance shape; `loadReplayLegacy` knob |
+| `MuseionTests/PostStoreTests.swift` | ai-stamp pin, additive-default pin, ai-immutability-through-overwrite pin |
+| `MuseionTests/SessionLifecycleTests.swift` | Draft-candidate pins, brainstorm pin, legacy-resume pin |
+| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX passes (root = analyze stats churn) |
+| `ref/writing skills/pass-persona/SKILL.md` | v1.4 drill-trigger section |
+
+## Open Items & Next Steps
+
+- [ ] SessionRow speaker identity (enum reshape) — retires the draftCandidateText string-shape ceiling
+- [ ] `lastError` double-routing vs the createProject precedent — lands with the speaker-identity pass
+- [ ] Stats capture (S5.1, M4) keys on `origin: writer` — the ai stamp is the exclusion marker, machinery not yet built
+- [ ] Drill offers need a real-engine pass to observe end-to-end (the persona trigger + seeded doctrine are engine-side)
+
+---
+
+*Log written by write-log skill*
diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md
index d892898..248a2bc 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-22 | issue | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | #30 lands: session-born Posts stamp origin: ai, brainstorm flavor, shared composer, and the real-engine resume wire fix. |
| 2026-10-22 | issue | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) | #29 research rail: submit_research_notes candidates in-session, ask-before keep into research/, resume replay pin, audit fixes — targeted suites green |
| 2026-10-22 | issue | [20261022-issue28-session-lifecycle-ui_log.md](20261022-issue28-session-lifecycle-ui_log.md) | #28 Session lifecycle: multi-session model + names-only roster, pane, pass auto-create, finish-audit with 7 fixes — 359 tests green |
| 2026-10-21 | issue | [20261021-issue27-dismiss-decay-learnings_log.md](20261021-issue27-dismiss-decay-learnings_log.md) | #27 dismiss & decay Learnings: per-type pass clock, frontmatter decay state, consult filtering, two review waves with 5 fixes |
diff --git a/ref/writing skills/pass-persona/SKILL.md b/ref/writing skills/pass-persona/SKILL.md
index 3ae32da..f227b22 100644
--- a/ref/writing skills/pass-persona/SKILL.md
+++ b/ref/writing skills/pass-persona/SKILL.md
@@ -5,7 +5,7 @@ license: GNU GPLv3
metadata:
author: Alexander Kucera
email: a.kucera@babylondreams.de
- version: "1.3"
+ version: "1.4"
---
# Pass Persona
@@ -41,6 +41,10 @@ Critique calibrates against the writer's best published prose: a small sample th
The Chief works before the Knife: verdict on structure, argument, and flow before any line edit. What is this Piece, does it hold, what moves where—settle that, then put every word on trial. The order is serif's two-pass rule; the manner here is how it sounds.
+## One drill may ride the strongest finding
+
+After a finding lands—while its pattern is still on the writer's screen—you may offer one micro-drill per Pass: the finding with the most pull, that one shelf only. The micro-drill doctrine governs the offer, the run, and the vanish. Skip the drill when the moment has passed.
+
## Fix Cards leave as one ranked submit
The verdict lands in prose; the findings leave as Fix Cards. One ranked `submit_fix_cards` call as the pass closes—findings ride the typed rail (ADR-0006), never prose to parse. Calling the tool mid-pass stays possible when a finding would otherwise be lost; the doctrine is one submit at the end. Every card carries `provenance.pass`—the number of the pass that found it.