diff --git a/AGENTS.md b/AGENTS.md index 266e2a8..3af2b3d 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** (4188 symbols, 14647 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** (4295 symbols, 15151 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-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) | | 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) | @@ -189,5 +190,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 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) | -| 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 195e66d..acfdc4d 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 +- **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) - **mentor:** Dismiss & decay for Learnings (PRD S4.2, G8) — dismissed patterns fade instead of haunting: a Dismiss button on every visible Learning in the Learnings pane stamps decay state into the Learning's own frontmatter (`dismissed`, `dismiss_count`, `dismissed_at_pass` — every other line preserved verbatim; hand-editable, git-diffable, survives restarts) and hides it from every pass: `query_learnings` serves only visible learnings. Resurfacing is an output clock, not a calendar — a dismissed Learning returns after 10 subsequent completed passes of its content type (a per-type counter under `/learnings/pass-counts.json`, ticked by every completed pass, re-runs included), each re-dismiss doubles the interval (10 → 20 → 40…), and a per-Learning `resurface_after` frontmatter key overrides the base 10. Dismissed rows dim with a "resurfaces in N passes" countdown and no button until they return; hand-edited decay state reads leniently — garbage means visible, absurd numbers clamp, a hand-edit can never crash the pane or the rail (issue #27) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 4d7bd4c..0d163fa 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -21,11 +21,11 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Workspace shell (M1, #17 + #18 / S1.1) - `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette. -- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#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`. 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 (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). - `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). -- `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 line "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); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent). +- `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. +- `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). - `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. @@ -63,17 +63,17 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## museion-tools MCP server (S2.4, #23) -- `MCPServer.swift` — `MCPServer` (nonisolated): the binary's second role. `MuseionLauncher` (`@main`, this file) branches on `--serve-mcp` → `MCPServer.serve()` (headless — never touches AppKit; blocks on stdin lines, exits 0 on EOF) vs `MuseionApp.main()`. NDJSON JSON-RPC 2.0 on stdio (wire facts live-verified against hermes' MCP client): `initialize` → echo the client's `protocolVersion` (client sends `2025-11-25`) + `capabilities {tools}` + serverInfo; `notifications/*` never answered; `tools/list` → the two tools with typed JSON Schemas (the submit schema IS the fix-card schema, ADR-0006 — one schema serves card UI, apply-write, learning promotion; **#25:** the schema descriptions declare the ranked ≤10 contract and the mechanical-fix-as-exact-replacement semantics, and an over-ceiling submit's reply carries `dropped_over_ceiling` — the wire tells the truth about the backstop); `tools/call` results carry `content[{type:"text"}]` + `isError:true` on tool failure; `ping` → `{}`; unknown method `-32601`, unparseable line `-32700` id null; **audit: lines over 1 MB answer `-32600` "Line too long" (frame cap mirroring the ACP reader side; readLine's own buffering is a commented ceiling), and one `jsonString` serializer serves replies and tool payloads**; **fflush after every stdout line** (piped stdout is block-buffered). `run(lines:write:)` is the testable seam behind `serve()`. Registration into the `museion` profile happens at provisioning (see above) — ACP sessions then expose the tools as `mcp_museion_tools_query_learnings` / `mcp_museion_tools_submit_fix_cards`. +- `MCPServer.swift` — `MCPServer` (nonisolated): the binary's second role. `MuseionLauncher` (`@main`, this file) branches on `--serve-mcp` → `MCPServer.serve()` (headless — never touches AppKit; blocks on stdin lines, exits 0 on EOF) vs `MuseionApp.main()`. NDJSON JSON-RPC 2.0 on stdio (wire facts live-verified against hermes' MCP client): `initialize` → echo the client's `protocolVersion` (client sends `2025-11-25`) + `capabilities {tools}` + serverInfo; `notifications/*` never answered; `tools/list` → the three tools with typed JSON Schemas (the submit schema IS the fix-card schema, ADR-0006 — one schema serves card UI, apply-write, learning promotion; **#25:** the schema descriptions declare the ranked ≤10 contract and the mechanical-fix-as-exact-replacement semantics, and an over-ceiling submit's reply carries `dropped_over_ceiling` — the wire tells the truth about the backstop; **#29 (S8.1):** the third tool `submit_research_notes` is the candidates rail — `{piece_path, notes:[{title, url, quote?, note?}]}`, decode-validate ONLY (missing fields fail decode = tool error; empty title/url throw) and reply `{"received": N}`; NOTHING is written — findings are engine-owned session cargo, the only path to disk is the writer's keep); `tools/call` results carry `content[{type:"text"}]` + `isError:true` on tool failure; `ping` → `{}`; unknown method `-32601`, unparseable line `-32700` id null; **audit: lines over 1 MB answer `-32600` "Line too long" (frame cap mirroring the ACP reader side; readLine's own buffering is a commented ceiling), and one `jsonString` serializer serves replies and tool payloads**; **fflush after every stdout line** (piped stdout is block-buffered). `run(lines:write:)` is the testable seam behind `serve()`. Registration into the `museion` profile happens at provisioning (see above) — ACP sessions then expose the tools as `mcp_museion_tools_query_learnings` / `mcp_museion_tools_submit_fix_cards` / `mcp_museion_tools_submit_research_notes`. - `FixCardStore.swift` — `FixCardStore` (nonisolated): the durable card store + tool bodies. `StoredFixCard` (Codable, snake_case, ISO-8601 dates): pattern/problem/diagnosticQuestion/fix, anchor {quote, occurrence (1-based), context?}, lane mechanical|demonstration, emitter lint|engine, provenance {piece, date?, engine?, pass?} (`pass` = the finding pass number — optional, pre-schema cards decode to nil; the palette renders "pass N" in the card meta; #23 follow-up), status "open", anchorStatus valid|stale — the ADR-0006 fields verbatim. `submit(piecePath:cards:)` — piece resolves to post.md (dir or file path; **audit guard: the file form must BE `post.md` under a `projects/`|`archive/` component — any readable file passing as a "piece" made submit a JSON-drop beside it and the anchor check a substring oracle over it; one resolvePostURL guard closed both security MEDIUMs**), raw text loaded once; anchor validation = exact substring, non-overlapping occurrence count vs 1-based occurrence, **stale → the card still lands flagged** (never rejected — the finding survives for the writer; malformed input/vanished piece → thrown error = tool error, the trust boundary); writes `<piece>/cards/<yyyyMMdd-HHmmss>-<PostStore.slug(pattern)>.json` (collision `-2`/`-3`), no dedup (v1 decision — the writer skips repeats). **#25 (S3.2/S3.3):** the pass ceiling (`passCardCeiling` = 10 per submit — the attention-budget backstop; the persona's own cap is the primary filter; the ranked HEAD is kept, tail cards drop before validation) + `rank` stamped 1-based in submit order (optional — pre-#25 cards decode nil); `StoredFixCard.Status` enum (open | applied | skipped | done — CONTEXT.md terminals; foreign status strings fail decode → scan's junk-skip); `appliedText(of:in:)` — the pure mechanical Apply (nth non-overlapping quote occurrence → fix; nil for demonstration lanes or unresolvable anchors — the loud no-match, never a wrong-span patch, ADR-0006; the caller owns the ask + write); `close(pieceURL:id:status:anchorStatus:)` — the in-place status flip in the card's own JSON file, every other field untouched (Skip records nothing); a non-nil `anchorStatus` rides the rewrite (apply's stale path flags the card), nil preserves. `scan(pieceURL:)` sorts submittedAt DESC → rank ASC (nil ranks last — pre-#25 cards) → filename DESC (same-second tiebreak), skips junk. `learnings(piecePath:)` — home/type derivation extracted into private `homeAndType` + public `learningsDir(home:type:)` shared with promote, reads `<home>/learnings/<type>s/` (literal plural, PRD S4.3) returning raw markdown per file — the consult rail (query_learnings serves exactly these files). **#26 (S4.1/S4.3) promote:** `promotedAt: Date?` on StoredFixCard (snake_case `promoted_at`; pre-#26 cards decode nil) — the explicit-confirm stamp; `promote(pieceURL:card:now:)` rejects a symlinked learnings component before any write (security audit: a pre-planted `learnings/posts` link must not become a file-plant primitive), then consults the ON-DISK card as the truth — not-found or already-stamped throws BEFORE anything is written (one confirm = one entry, never a counter; a stale palette copy cannot double-write), resolves home/type from the piece, writes ONE plain markdown Learning `<learningsDir>/<yyyyMMdd>-<PostStore.slug(pattern)>.md` (collision -2/-3 via `uniqueFile(ext:)`), then rewrites the card JSON in place with `promotedAt` (close()'s pattern; learning-first ordering is deliberate — the inverse would lock re-promotion forever); `learningMarkdown` is the pinned file shape — the TEACHING text, never the instance: flat single-line frontmatter (pattern/problem/diagnostic_question?/fix-for-demonstration-lanes-only/lane/emitter/piece?/pass?/engine?/promoted yyyy-MM-dd/from_card uuid; newlines flatten to spaces; the anchor + mechanical replacement stay on the card JSON — a Learning informs, it never gets applied) + readable body (`# pattern`, Problem/Diagnostic lines, `**Example.**` for demonstrations, italic provenance footer omitting missing parts). **#27 (S4.2):** `learnings(piecePath:)` filters DECAYED learnings — the consult rail (query_learnings) serves only visible ones: `LearningDecay.passesHidden(Post.frontmatter(of:), currentPass:) == nil`, the clock from `LearningDecay.passCounts(home:)` under `LearningDecay.passKey(type)`; `formatted(_:_:)` is internal (LearningDecay's dismiss date stamp shares it). - `LearningDecay.swift` — #27 (S4.2; own file — FixCardStore sits at its type-body ceiling): Dismiss & Decay, nonisolated. The pass clock is `<home>/learnings/pass-counts.json` (flat {typeDir: completed-pass count}; keys = the LITERAL plural dir names via `passKey(_:)` — one place so writer and readers can't drift): `passCounts(home:)` reads leniently (missing/corrupt → empty, non-integers dropped; values clamp into [0, 1e9] — a hostile hand-edit can't trap the arithmetic), `recordPass(home:type:)` ticks atomically (.sortedKeys; a symlinked `learnings/` refuses — promote's posture, so the per-pass tick can never write outside the Home's tree). `isClocked(_:)` names the dirs that carry a clock — only the content-type plurals (`recordPass` ticks exactly those); a foreign dir (a hand-made `essays/`) is pane-visible but its clock reads 0 forever, so a dismiss there would hide permanently — the store refuses and the pane offers no button. `passesHidden(_:currentPass:)` is the ONE pure visibility verdict the consult rail, the pane rows, and the dismiss stamp ride: nil = visible, positive = passes until resurface; interval = (`resurface_after` ?? `baseInterval` 10) doubled per re-dismiss (doubling capped at 30 — a hand-edited `dismiss_count` 9999 can't overflow Int), garbage `dismiss_count` defaults 1 when an anchor exists, a missing/garbage anchor means VISIBLE (a malformed dismiss never permanently hides a Learning). `dismiss(home:typeDir:file:)` stamps decay state IN the Learning's own frontmatter — `dismissed` (yyyy-MM-dd), `dismiss_count` (+1, clamped first), `dismissed_at_pass` (the type's current clock) — through `stampingFrontmatter` (mergedFrontmatter's line-walk generalized to ordered pairs, ponytail-marked — extraction would grow PostStore at its ceiling; no block → fresh block prepended; every other line verbatim — leading hand-edit lines above the block included, #27-review-pinned), behind write-path guards (traversal/hidden names refuse; symlinked learnings components OR learning file refuse — a planted file link must not become a copy-into-the-consult-tree primitive; a foreign unclocked type dir refuses; a currently-HIDDEN Learning refuses — re-dismiss means AFTER the resurface, CONTEXT.md, which also makes a double-click's second stamp harmless; promote's posture throughout). -- Tests: `MuseionTests/MCPToolsTests.swift` (anchor matrix incl. occurrence 3-of-2 → stale, empty quote → stale; submit round-trip + snake_case keys; scan ordering + junk skip; learnings per type + missing dir → empty) and `MuseionTests/MCPServerWireTests.swift` (in-process `run(lines:write:)`: initialize echo, silent notifications, both tools listed with required arrays, full submit round-trip through the wire, isError path, -32601/-32700). +- Tests: `MuseionTests/MCPToolsTests.swift` (anchor matrix incl. occurrence 3-of-2 → stale, empty quote → stale; submit round-trip + snake_case keys; scan ordering + junk skip; learnings per type + missing dir → empty) and `MuseionTests/MCPServerWireTests.swift` (in-process `run(lines:write:)`: initialize echo, silent notifications, all three tools listed with required arrays — #29 research schema pins piece_path+notes / title+url — full submit round-trip through the wire, isError path, -32601/-32700; **#29:** a well-formed `submit_research_notes` round-trip replies `{"received": N}` and lands NOTHING on disk, a note missing `title` answers isError). ## ACP bridge (S2.2, #14 map) - `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 → "<name> (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 · \<title\>", 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. -- `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). + **#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 → "<name> (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 · \<title\>", 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. +- `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/<file>` / `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/FixCardStore.swift b/Museion/FixCardStore.swift index 92f1755..2e1232c 100644 --- a/Museion/FixCardStore.swift +++ b/Museion/FixCardStore.swift @@ -292,11 +292,13 @@ nonisolated enum FixCardStore { } /// First free filename for `base`: base, base-2, base-3… (#26: `ext` — - /// cards are .json, Learnings .md.) + /// cards are .json, Learnings and research notes .md.) Internal, not + /// private: PostStore.writeResearchNote reuses it (#29) instead of + /// copying it. // ponytail: exists-then-write race needs two concurrent same-second // same-pattern writers to matter (atomic rename = replace, not // corrupt); O_EXCL retry if a second writer ever appears. - private static func uniqueFile(_ dir: URL, base: String, ext: String = "json") -> String { + static func uniqueFile(_ dir: URL, base: String, ext: String = "json") -> String { var name = "\(base).\(ext)" var suffix = 2 while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name).path) { diff --git a/Museion/MCPServer.swift b/Museion/MCPServer.swift index 0bce476..8f164ac 100644 --- a/Museion/MCPServer.swift +++ b/Museion/MCPServer.swift @@ -96,6 +96,10 @@ nonisolated enum MCPServer { } } + // The dispatcher's body IS the tool catalog — it grows one case per + // tool. ponytail: split per-tool handlers out only when a second + // dimension (not more tools) forces it. + // swiftlint:disable:next function_body_length private static func toolCall(id: Any?, params: [String: Any]) -> String { let name = params["name"] as? String ?? "" let arguments = params["arguments"] as? [String: Any] ?? [:] @@ -147,6 +151,28 @@ nonisolated enum MCPServer { "text": jsonString(payload) ?? "{}", ]] as [[String: Any]], ]) + case "submit_research_notes": + // #29 (S8.1): the candidates rail — DECODE-VALIDATE ONLY. + // Findings are engine-owned cargo in their session; the reply + // is a received count, never storage. The ONLY path to disk is + // the writer's keep (PostStore.writeResearchNote). + let args = try FixCardStore.decoder.decode( + ResearchNotesArgs.self, from: JSONSerialization.data(withJSONObject: arguments), + ) + for note in args.notes { + guard !note.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw FixCardStore.CardError(message: "note title must not be empty") + } + guard !note.url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw FixCardStore.CardError(message: "note url must not be empty") + } + } + return reply(id: id, result: [ + "content": [[ + "type": "text", + "text": jsonString(["received": args.notes.count]) ?? "{}", + ]] as [[String: Any]], + ]) default: return failure(FixCardStore.CardError(message: "Unknown tool: \(name)")) } @@ -164,11 +190,27 @@ nonisolated enum MCPServer { var cards: [FixCardStore.Input] } + /// #29 (S8.1): one candidate source-note — quote/note optional on the + /// wire (they arrive as "" at the keep write when absent). + private struct ResearchNoteArgs: Decodable { + var title: String + var url: String + var quote: String? + var note: String? + } + + /// #29 (S8.1): the research rail's wire shape — ONE shape, no legacy + /// fallback; a missing field fails decode = the trust boundary. + private struct ResearchNotesArgs: Decodable { + var piecePath: String + var notes: [ResearchNoteArgs] + } + // MARK: - Tools - /// The two tools (#23). The submit schema IS the fix-card schema - /// (ADR-0006): it serves the card UI, the apply-write, and learning - /// promotion. + /// The tools (#23 cards + learnings; #29 the research rail). The submit + /// schema IS the fix-card schema (ADR-0006): it serves the card UI, the + /// apply-write, and learning promotion. private static var tools: [[String: Any]] { [ [ @@ -252,6 +294,43 @@ nonisolated enum MCPServer { "required": ["piece_path", "cards"], ] as [String: Any], ], + [ + "name": "submit_research_notes", + "description": "Deliver research findings as candidate source-notes for a piece — " + + "candidates only: the notes arrive in the session, nothing is written to disk. " + + "The writer keeps or rejects each note in Museion; keeping writes the plain " + + "markdown note (with provenance) into the piece's research/ folder.", + "inputSchema": [ + "type": "object", + "properties": [ + "piece_path": [ + "type": "string", + "description": "Path to the piece folder or its post.md.", + ], + "notes": [ + "type": "array", + "description": "Candidate source-notes with provenance.", + "items": [ + "type": "object", + "properties": [ + "title": ["type": "string"], + "url": ["type": "string"], + "quote": [ + "type": "string", + "description": "Verbatim quotation from the source, when there is one.", + ], + "note": [ + "type": "string", + "description": "The finding — why this source matters to the piece.", + ], + ] as [String: Any], + "required": ["title", "url"], + ] as [String: Any], + ] as [String: Any], + ] as [String: Any], + "required": ["piece_path", "notes"], + ] as [String: Any], + ], ] } diff --git a/Museion/MentorPaneView.swift b/Museion/MentorPaneView.swift index 7de72da..77ec7d1 100644 --- a/Museion/MentorPaneView.swift +++ b/Museion/MentorPaneView.swift @@ -73,7 +73,7 @@ struct MentorPaneView: View { } // #28: the transcript rendering is shared — the Sessions pane // reads the same surface in the writing voice. - SessionTranscriptView(model: model, showsDebugRows: debugRows) + SessionTranscriptView(model: model, showsDebugRows: debugRows, home: home) Divider() inputBar case let .crashed(lastPrompt): diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index cdf0302..dc6ed6f 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -23,6 +23,10 @@ struct SessionRow: Identifiable { /// never mixed into the critique text. case thought(String) case fixCard(FixCard) + /// #29 (S8.2): a candidate research note from the session's research + /// tool call — lives in THIS session until the writer keeps or + /// rejects it (engine-owned cargo; replay re-materializes it). + case researchNote(ResearchCandidate) case raw(kind: String, json: String) } @@ -43,6 +47,21 @@ struct FixCard { var status: String } +/// #29 (S8.2) one candidate research note: a source finding the mentor +/// surfaced mid-pass. Candidates wait in their SESSION until kept — nothing +/// auto-saves (CONTEXT.md's Research Note: kept ones land in the piece's +/// research/ via the store rail; rejected ones vanish). Nonisolated: a wire +/// value parsed from rawInput and asserted from tests (SessionEntry rule). +nonisolated struct ResearchCandidate: Equatable { + enum Disposition: Equatable { case pending; case kept(fileName: String); case rejected } + var piecePath: String + var title: String + var url: String + var quote: String + var note: String + var disposition: Disposition = .pending +} + /// How a turn ended — the pass orchestrator's seam (#24): a pass advances /// Pass State only when the engine's turn completed, never on cancel/crash. enum TurnOutcome: Equatable { @@ -726,6 +745,22 @@ extension MentorSessionModel { private func appendToolCall(_ update: [String: JSONValue], to sid: String) { let title = update["title"]?.stringValue ?? "tool call" let rawInput = update["rawInput"] + // #29: the research rail routes on PAYLOAD SHAPE, not the title (a + // tool_call's title is display text, not guaranteed to be the raw + // tool name) and before the fix-card parse — a research payload with + // stray pattern/problem keys must not vanish into a card row. The + // notes-array presence gate keeps fix-card payloads out of the + // research parser; a batch that fails to parse falls through. + var candidates: [ResearchCandidate] = [] + if case .array? = rawInput?.objectValue?["notes"] { + candidates = ResearchCandidate.batch(rawInput) + } + if !candidates.isEmpty { + for candidate in candidates { + appendRow(.researchNote(candidate), to: sid) + } + return + } if let card = FixCard(rawInput: rawInput) { appendRow(.fixCard(card), to: sid) return @@ -767,3 +802,54 @@ private extension FixCard { status = card["status"]?.stringValue ?? "proposed" } } + +/// Flip a research candidate's disposition (#29 S8.3): replaces the +/// row's content in the ACTIVE session's transcript (rows are structs; +/// the store is keyed by wire sessionId). No-op on an unknown row id. +/// File-scope extension — type_body_length posture (PostsModel's guards +/// precedent); the API is unchanged for callers. +extension MentorSessionModel { + func setResearchDisposition(rowID: UUID, _ disposition: ResearchCandidate.Disposition) { + guard let sid = activeEntry?.sessionId, var rows = transcripts[sid]?.rows, + let index = rows.firstIndex(where: { $0.id == rowID }), + case let .researchNote(candidate) = rows[index].content + else { return } + var updated = candidate + updated.disposition = disposition + rows[index].content = .researchNote(updated) + transcripts[sid]?.rows = rows + } +} + +/// 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 +/// any note missing a NON-BLANK title/url yields NO candidates +/// (appendToolCall falls through to the raw row) — the same trim rule the +/// MCP wire enforces, so both boundaries agree (audit: a whitespace title +/// used to render an invisible-titled card and keep as `-untitled.md`). +/// Absent quote/note become "". +nonisolated extension ResearchCandidate { + static func batch(_ rawInput: JSONValue?) -> [ResearchCandidate] { + guard let object = rawInput?.objectValue, + let piecePath = object["piece_path"]?.stringValue, + case let .array(notes)? = object["notes"], + !notes.isEmpty + else { return [] } + var candidates: [ResearchCandidate] = [] + for note in notes { + guard let fields = note.objectValue, + let title = fields["title"]?.stringValue, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + let url = fields["url"]?.stringValue, !url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + else { return [] } + candidates.append(ResearchCandidate( + piecePath: piecePath, + title: title, + url: url, + quote: fields["quote"]?.stringValue ?? "", + note: fields["note"]?.stringValue ?? "", + )) + } + return candidates + } +} diff --git a/Museion/Pass.swift b/Museion/Pass.swift index 27b28c0..c7163a8 100644 --- a/Museion/Pass.swift +++ b/Museion/Pass.swift @@ -50,13 +50,17 @@ nonisolated enum PassContext { /// Pinned shape — keep it a small constant, not a template system. /// Restored contract (#23, museion-tools rail): findings travel as /// fix-card tool calls (submit_fix_cards) — the reply carries the - /// verdict, never the findings. + /// verdict, never the findings. #29: fact-checking research travels + /// as candidate source-note tool calls (submit_research_notes) — + /// engine-owned cargo in the session, never written by the engine. static func stub(kind: PassKind, pieceURL: URL, hasResearch: Bool) -> String { "Pass \(kind.rawValue) — \(kind.level).\nPiece: \(pieceURL.path)\n" + (hasResearch ? "Research notes: \(pieceURL.deletingLastPathComponent().appendingPathComponent("research").path)\n" : "") - + "Critique the piece for this pass. Deliver the verdict in your reply — " + + "Critique the piece for this pass. 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." } diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index 455b598..0c34193 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -622,3 +622,58 @@ nonisolated extension PostStore { return rank(current) >= rank(completed) ? current : completed } } + +// MARK: Research notes (#29) + +/// #29 (S8.2): the keep write — the writer's explicit act. One plain +/// markdown Research Note with provenance per keep, landed in +/// `<piece>/research/`; the candidates themselves wait in their session +/// and are never persisted by the tool rail (CONTEXT.md). Same-file +/// extension like the pass substrate: the enum's private members stay +/// reachable at file scope. +nonisolated extension PostStore { + /// Write ONE kept research note. `piecePath` is the piece folder or its + /// post.md — resolved through the ONE id→folder resolver so the write + /// anchors to THIS Home (a garbage path fails the id lookup honestly). + /// Returns the landed file NAME inside `<piece>/research/`. + /// `quote`/`note` arrive as "" when the candidate carried none; empty + /// sections are omitted. A vanished piece throws (a keep never + /// resurrects, #18's rule). + // swiftlint:disable:next function_parameter_count + static func writeResearchNote( + piecePath: String, title: String, url: String, quote: String, note: String, home: URL, + ) throws -> String { + let given = URL(fileURLWithPath: piecePath) + let pieceDir = given.lastPathComponent == "post.md" ? given.deletingLastPathComponent() : given + guard let dir = folder(of: pieceDir.lastPathComponent, home: home) else { + throw FixCardStore.CardError(message: "piece not found: \(piecePath)") + } + let research = dir.appendingPathComponent("research", isDirectory: true) + // Security (promote's posture): a pre-planted symlinked research/ + // must not turn the keep into a write-outside-Home primitive — + // refuse before any write. + let values = try? research.resourceValues(forKeys: [.isSymbolicLinkKey]) + if values?.isSymbolicLink == true { + throw FixCardStore.CardError(message: "research path is a symlink: \(research.path)") + } + try FileManager.default.createDirectory(at: research, withIntermediateDirectories: true) + let day = FixCardStore.formatted(Date(), "yyyyMMdd") + /// Flat single-line structural fields (Learning-file precedent): a + /// newline in a hostile title/url must not break the heading or the + /// frontmatter shape. Note/quote stay verbatim — they are content. + func flat(_ value: String) -> String { + value.components(separatedBy: .newlines).joined(separator: " ") + } + var body = "# \(flat(title))" + if !note.isEmpty { + body += "\n\n\(note)" + } + if !quote.isEmpty { + body += "\n\n> \(quote)" + } + let markdown = "---\nsource: \(flat(url))\nkept: \(day)\n---\n\n\(body)\n" + let name = FixCardStore.uniqueFile(research, base: "\(day)-\(slug(from: title))", ext: "md") + try markdown.write(to: research.appendingPathComponent(name), atomically: true, encoding: .utf8) + return name + } +} diff --git a/Museion/ResearchKeepSheet.swift b/Museion/ResearchKeepSheet.swift new file mode 100644 index 0000000..64352c7 --- /dev/null +++ b/Museion/ResearchKeepSheet.swift @@ -0,0 +1,71 @@ +// +// ResearchKeepSheet.swift +// Museion +// +// #29 (S8.3): the keep ask — ONE blocking confirm lands ONE plain markdown +// research note in the piece's research/ folder (the store's +// writeResearchNote rail). PromoteAskSheet pattern: own-file ask sheet, +// Cancel writes nothing, a failure shows its reason inline with the +// buttons kept. +// + +import SwiftUI + +struct ResearchKeepSheet: View { + let model: MentorSessionModel + let rowID: UUID + let candidate: ResearchCandidate + let home: URL + @Environment(\.dismiss) private var dismiss + + @State private var refusal: String? + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + Text("Keep this research note?") + .font(.headline) + Text("Plain markdown into the piece's research/ folder — nothing saves until you keep it.") + .font(.callout) + // The note preview: the file the confirm writes. + ResearchNoteContent(candidate: candidate) + .padding(8) + .background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 6)) + if let refusal { + Text(refusal) + .font(.callout) + .foregroundStyle(.orange) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + HStack(spacing: 8) { + Button("Keep") { keep() } + .buttonStyle(.borderedProminent) + Button("Cancel") { dismiss() } + .buttonStyle(.bordered) + } + .frame(maxWidth: .infinity, alignment: .trailing) + } + .padding(16) + .frame(width: 320, alignment: .leading) + } + + private func keep() { + do { + let fileName = try PostStore.writeResearchNote( + piecePath: candidate.piecePath, + title: candidate.title, + url: candidate.url, + quote: candidate.quote, + note: candidate.note, + home: home, + ) + model.setResearchDisposition(rowID: rowID, .kept(fileName: fileName)) + dismiss() + } catch { + refusal = error.localizedDescription + } + } +} diff --git a/Museion/SessionTranscriptView.swift b/Museion/SessionTranscriptView.swift index b4eb12d..8b8f9ef 100644 --- a/Museion/SessionTranscriptView.swift +++ b/Museion/SessionTranscriptView.swift @@ -19,6 +19,21 @@ struct SessionTranscriptView: View { /// Raw session/tool rows, collapsed thinking, and live thinking render /// only when on — the model keeps every row either way. var showsDebugRows = false + /// #29 (S8.3): the Home a kept research note lands in — nil (previews) + /// hides the candidate card's Keep/Reject buttons. + var home: URL? + + /// 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? + + private struct PendingKeep: Identifiable { + let rowID: UUID + let candidate: ResearchCandidate + var id: UUID { + rowID + } + } var body: some View { ScrollView { @@ -46,6 +61,11 @@ 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 writing-session filter: prose + card events stay; raw rows and @@ -53,7 +73,7 @@ struct SessionTranscriptView: View { /// any context. nonisolated static func isWritingRow(_ row: SessionRow) -> Bool { switch row.content { - case .text, .fixCard: true + case .text, .fixCard, .researchNote: true case .thought, .raw: false } } @@ -69,6 +89,13 @@ struct SessionTranscriptView: View { // #23 follow-up: detail lives in the palette window — the // transcript keeps a one-line event, not the card. FixCardEventRow(pattern: card.pattern) + case let .researchNote(candidate): + ResearchNoteRow( + candidate: candidate, + actions: home != nil, + keep: { pendingKeep = PendingKeep(rowID: row.id, candidate: candidate) }, + reject: { model.setResearchDisposition(rowID: row.id, .rejected) }, + ) case let .raw(kind, json): RawUpdateRow(kind: kind, json: json) } @@ -93,6 +120,61 @@ struct SessionTranscriptView: View { } } + /// #29 (S8.3): one candidate research-note card — serif title, mono + /// muted url, selectable note, muted-italic quote. Pending offers Keep + /// (ask-before) + Reject (no confirm — vanishes, nothing recorded); + /// kept/rejected dim 0.45 (closed-card voice) with their meta line. + private struct ResearchNoteRow: View { + let candidate: ResearchCandidate + let actions: Bool + let keep: () -> Void + let reject: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + ResearchNoteContent(candidate: candidate) + dispositionView + } + .frame(maxWidth: .infinity, alignment: .leading) + .opacity(dimmed) + } + + @ViewBuilder + private var dispositionView: some View { + switch candidate.disposition { + case .pending: + if actions { + HStack(spacing: 8) { + Button("Keep", action: keep) + .buttonStyle(.bordered) + .controlSize(.small) + .font(.system(size: 11, design: DesignTokens.mono)) + .help("Land this note in the piece's research/ folder") + Button("Reject", action: reject) + .buttonStyle(.bordered) + .controlSize(.small) + .font(.system(size: 11, design: DesignTokens.mono)) + .help("Vanish the candidate — nothing is recorded") + } + } + case let .kept(fileName): + meta("kept · research/\(fileName)") + case .rejected: + meta("rejected") + } + } + + private var dimmed: Double { + candidate.disposition == .pending ? 1 : 0.45 + } + + private func meta(_ text: String) -> some View { + Text(text) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + } + } + /// #24 fix: the engine's thinking, collapsed — a pass's thought stream /// runs to hundreds of lines and is not the critique. private struct ThoughtRow: View { @@ -132,6 +214,35 @@ struct SessionTranscriptView: View { } } +/// #29 audit: the candidate's content block — title/url/note/quote — shared +/// by the transcript row and the keep sheet's preview, so a restyle edits +/// one place. File scope: ResearchKeepSheet reuses it. +struct ResearchNoteContent: View { + let candidate: ResearchCandidate + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + Text(candidate.title) + .font(.system(size: 13, design: DesignTokens.serif)) + Text(candidate.url) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .lineLimit(1) + .truncationMode(.middle) + if !candidate.note.isEmpty { + Text(candidate.note) + .textSelection(.enabled) + } + if !candidate.quote.isEmpty { + Text("“\(candidate.quote)”") + .italic() + .foregroundStyle(DesignTokens.muted) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} + #Preview { SessionsPaneView(model: MentorSessionModel(), posts: nil, binaryPath: nil) } diff --git a/Museion/SessionsPaneView.swift b/Museion/SessionsPaneView.swift index c67a8d4..716f103 100644 --- a/Museion/SessionsPaneView.swift +++ b/Museion/SessionsPaneView.swift @@ -21,6 +21,8 @@ struct SessionsPaneView: View { /// The gate's winning binary (no re-probe) — this pane can be the first /// to open the engine. var binaryPath: String? + /// #29 (S8.3): the Home a kept research note lands in. + var home: URL? var body: some View { VStack(spacing: 0) { @@ -95,7 +97,7 @@ struct SessionsPaneView: View { livenessRow Divider() } - SessionTranscriptView(model: model, showsDebugRows: false) + SessionTranscriptView(model: model, showsDebugRows: false, home: home) } } } diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index 570a2c0..18a047e 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -202,6 +202,7 @@ struct WorkspaceView: View { model: gate.mentor, posts: gate.posts, binaryPath: gate.gateModel.currentBinaryPath, + home: gate.museionHome, ) case .learnings: // #26: list-only pane over <home>/learnings/ — read side; diff --git a/MuseionTests/ACPClientTests.swift b/MuseionTests/ACPClientTests.swift index 7e080ae..f5aefab 100644 --- a/MuseionTests/ACPClientTests.swift +++ b/MuseionTests/ACPClientTests.swift @@ -34,7 +34,9 @@ import Testing /// chunks); `loadReplay` (#28) adds the lifecycle wire: session/new/load/fork /// all require `mcpServers` (-32602 without, the #44 invariant), session ids /// are minted uniquely (sess-1, sess-2, …), session/load replays -/// user+thought+message chunks for ANY minted sess-* id then answers its id +/// user+thought+message chunks PLUS one submit_research_notes tool call +/// (#29 — candidates re-materialize on resume) for ANY minted sess-* id +/// then answers its id /// (a relaunch default-open resumes the newest rostered entry, #28 review /// fix; any other id answers with NO sessionId = unknown), and session/fork /// of sess-1 returns a fresh F-<n> (any other source id returns ""). load/fork @@ -52,6 +54,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu let path = (dir as NSString).appendingPathComponent(name) let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode") let fixCardB64 = fixCardPayloadB64() + let researchB64 = researchPayloadB64() // ponytail: one echo per wire message — long payloads ride shell vars so // each line stays under the lint cap and inspectable against the schema. let script = """ @@ -59,6 +62,8 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu mode="full" [[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode") card=$(print -- '\(fixCardB64)' | base64 -d) + research=$(print -- '\(researchB64)' | base64 -d) + researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d) framing='{"jsonrpc":"2.0","id":' sessn=0 forkn=0 @@ -99,6 +104,14 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu continue fi echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}' + if [[ "$mode" == "strayResearchOnPrompt" ]]; then + # #29 audit pin: a research payload carrying stray fix-card keys at + # the top level must route by shape (notes array), not vanish into + # a card row. + echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_research_notes","rawInput":'"$researchstray"'}}}' + echo $framing"$rid",'"result":{"stopReason":"end_turn"}}' + continue + fi echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}' if [[ "$mode" == "hangOnPrompt" ]]; then # #124: the cancel-acknowledging hold — the real engine answers its @@ -141,6 +154,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu 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"'"}}' else echo $framing"$rid",'"result":{}}' # unknown session — no sessionId @@ -188,6 +202,25 @@ private func fixCardPayloadB64() -> String { return Data(json.utf8).base64EncodedString() } +/// The research-notes payload for the fake's replayed tool call (#29) — +/// base64 like the fix card so shell quoting can never break the wire JSON. +/// Two notes: one complete, one with quote/note absent (the "" defaults). +private func researchPayloadB64() -> String { + let json = #"{"piece_path":"/tmp/piece","notes":["# + + #"{"title":"Hinge Study","url":"https://example.org/hinge","quote":"We should stop listening.","note":"Counts the pivot tense."},"# + + #"{"title":"Second Source","url":"https://example.org/second"}]}"# + return Data(json.utf8).base64EncodedString() +} + +/// The #29 routing pin's payload: a research batch that ALSO carries stray +/// fix-card keys at the top level (LLM tool calls pick up stray keys). The +/// notes-array shape must win over the pattern/problem match. +private func strayResearchPayloadB64() -> String { + let json = #"{"pattern":"stray","problem":"stray","piece_path":"/tmp/piece","notes":["# + + #"{"title":"Hinge Study","url":"https://example.org/hinge"}]}"# + return Data(json.utf8).base64EncodedString() +} + func acpTempDir(_ label: String) -> String { let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)" try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) @@ -400,6 +433,43 @@ struct ACPClientTests { #expect(refused) } + /// #29 audit pin: a research payload with stray fix-card keys routes by + /// SHAPE (the notes array) — it renders candidates, never a card row. + /// Title-based routing would also work on the fake but titles are + /// display text; the payload is the contract. + @MainActor + @Test func `research payload with stray card keys renders candidates not a card`() async { + let fake = makeFakeACP(at: acpTempDir("stray-research"), mode: "strayResearchOnPrompt") + let model = MentorSessionModel(binaryPath: fake) + defer { model.shutdown() } + await model.openSession() + let outcome = await model.sendPrompt("research this") + guard case .ended = outcome else { + Issue.record("turn did not end: \(outcome)") + return + } + var hasCandidates = false + var hasCard = false + for _ in 0 ..< 250 { + hasCandidates = model.rows.contains { + if case .researchNote = $0.content { + return true + }; return false + } + hasCard = model.rows.contains { + if case .fixCard = $0.content { + return true + }; return false + } + if hasCandidates { + break + } + try? await Task.sleep(nanoseconds: 20_000_000) + } + #expect(hasCandidates, "the stray-key research batch never rendered as candidates") + #expect(!hasCard, "the research payload was swallowed by the fix-card parser") + } + @MainActor @Test func `thought chunks land in a collapsed thought row not the critique`() async { let fake = makeFakeACP(at: acpTempDir("thought-lane")) diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 90a7882..72172e6 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract. - `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — 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-<n>` 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 `<binaryDir>/profiles/<name>` (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/<name>/<id>/` + `archive/<name>/<id>/` (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/<name>/<id>/` + #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/<project>/<id>/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) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). -- `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 `<piece>/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. **#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. +- `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/<name>/<id>/` + #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/<project>/<id>/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. +- `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 `<piece>/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 · <title>" 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 · \<title\>" 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 · \<title\>" 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 ("<name> (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). +- `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 · \<title\>" 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 ("<name> (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). - `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 `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars. - `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit. diff --git a/MuseionTests/EditorSessionTests.swift b/MuseionTests/EditorSessionTests.swift index 9eae22e..bae48a2 100644 --- a/MuseionTests/EditorSessionTests.swift +++ b/MuseionTests/EditorSessionTests.swift @@ -48,12 +48,16 @@ struct EditorSessionTests { #expect(session.saveState == .saved) // Changed → flush → Saved lands here #expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.") - // Sidecar: written on flush, reads back. + // Sidecar: written on flush, reads back. Await the sidecar rather + // than sleeping a fixed window — same starvation rule as above. let cursor = PostStore.CursorState(selectionLocation: 3, selectionLength: 2, scrollOffset: 128) session.cursorUpdate(cursor) session.edit("# Alpha\n\nOne. Two. Three.") - try await Task.sleep(for: .milliseconds(200)) - let restored = PostStore.readCursor(id: "alpha", home: home) + var restored: PostStore.CursorState? + while restored != cursor, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(20)) + restored = PostStore.readCursor(id: "alpha", home: home) + } #expect(restored == cursor) } diff --git a/MuseionTests/MCPServerWireTests.swift b/MuseionTests/MCPServerWireTests.swift index 38d3697..10035f2 100644 --- a/MuseionTests/MCPServerWireTests.swift +++ b/MuseionTests/MCPServerWireTests.swift @@ -9,6 +9,16 @@ // -32601 unknown method, -32700 garbage. Wire facts verified live // against the real hermes MCP client. // +// ## Scenario: candidate rail and the keep write +// From #29 (S8.1/S8.2) +// Given a piece in the library and the mentor researching mid-pass +// When the engine delivers findings as submit_research_notes tool calls +// Then well-formed candidates are accepted with a received count and +// nothing is written anywhere; malformed ones answer a tool error +// And the pass prompt names that rail +// And when the writer keeps one, one plain markdown note with provenance +// lands in the piece's research/ — nothing else auto-saves. +// import Foundation @testable import Museion @@ -70,11 +80,14 @@ struct MCPServerWireTests { #expect(result.isEmpty) } - @Test func `tools list exposes both tools with schemas`() throws { + @Test func `tools list exposes all three tools with schemas`() throws { let replies = try runWire([toolsListLine]) let result = try #require(replies[0]["result"] as? [String: Any]) let tools = try #require(result["tools"] as? [[String: Any]]) - #expect(Set(tools.compactMap { $0["name"] as? String }) == ["query_learnings", "submit_fix_cards"]) + #expect( + Set(tools.compactMap { $0["name"] as? String }) + == ["query_learnings", "submit_fix_cards", "submit_research_notes"], + ) let submit = try #require(tools.first { $0["name"] as? String == "submit_fix_cards" }) let schema = try #require(submit["inputSchema"] as? [String: Any]) @@ -100,6 +113,20 @@ struct MCPServerWireTests { let query = try #require(tools.first { $0["name"] as? String == "query_learnings" }) let querySchema = try #require(query["inputSchema"] as? [String: Any]) #expect(try #require(querySchema["required"] as? [String]) == ["piece_path"]) + + // #29 (S8.1): the research rail requires piece_path + notes, and a + // note item requires title + url. + let research = try #require(tools.first { $0["name"] as? String == "submit_research_notes" }) + let researchSchema = try #require(research["inputSchema"] as? [String: Any]) + let researchRequired = try #require(researchSchema["required"] as? [String]) + #expect(researchRequired.contains("piece_path")) + #expect(researchRequired.contains("notes")) + let researchProps = try #require(researchSchema["properties"] as? [String: Any]) + let notesProp = try #require(researchProps["notes"] as? [String: Any]) + let noteItems = try #require(notesProp["items"] as? [String: Any]) + let noteRequired = try #require(noteItems["required"] as? [String]) + #expect(noteRequired.contains("title")) + #expect(noteRequired.contains("url")) } /// One throwaway wire piece: home + `projects/posts/<name>/post.md` @@ -224,4 +251,69 @@ struct MCPServerWireTests { )) ?? []).filter { $0.hasSuffix(".json") } #expect(onDisk.count == 10) } + + /// #29 (S8.1): one submit_research_notes wire line over the given + /// arguments (JSONSerialization-built — no line_length fights). + private func researchCall(id: Int, arguments: [String: Any]) throws -> String { + let request: [String: Any] = [ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": ["name": "submit_research_notes", "arguments": arguments] as [String: Any], + ] + return try #require(String(data: JSONSerialization.data(withJSONObject: request), encoding: .utf8)) + } + + /// #29 (S8.1): well-formed candidates answer a received count — and + /// create NOTHING on disk (candidates live in their session; keeping + /// is the writer's separate act). + @Test func `research notes reply received and write nothing`() throws { + let (_, piece) = try seedWirePiece("research-piece") + let note = [ + "title": "The Long Now", + "url": "https://example.org/long-now", + "quote": "pace layers", + "note": "Supports the slowness claim.", + ] as [String: Any] + let line = try researchCall(id: 21, arguments: ["piece_path": piece.path, "notes": [note]]) + + let replies = try runWire([initializeLine, initializedLine, line]) + #expect(replies.count == 2) + let result = try #require(replies[1]["result"] as? [String: Any]) + #expect(result["isError"] == nil) + let payload = try #require( + try JSONSerialization.jsonObject(with: Data(toolText(result).utf8)) as? [String: Any], + ) + #expect(payload["received"] as? Int == 1) + #expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("research").path)) + } + + /// #29 (S8.1): malformed candidates answer a tool error — the trust + /// boundary. Missing fields fail decode; a whitespace-only title is + /// refused; none of them writes anything. + @Test func `malformed research notes answer a tool error`() throws { + let (_, piece) = try seedWirePiece("research-error-piece") + let lines = try [ + // notes item missing url → decode fails. + researchCall(id: 31, arguments: ["notes": [["title": "T"]]]), + // notes item missing title → decode fails. + researchCall(id: 32, arguments: ["notes": [["url": "https://example.org"]]]), + // whitespace-only title → CardError. + researchCall(id: 33, arguments: [ + "piece_path": piece.path, + "notes": [["title": " ", "url": "https://example.org"]], + ]), + // piece_path missing → decode fails. + researchCall(id: 34, arguments: [ + "notes": [["title": "T", "url": "https://example.org"]], + ]), + ] + for line in lines { + let replies = try runWire([line]) + let result = try #require(replies[0]["result"] as? [String: Any]) + #expect(result["isError"] as? Bool == true, "expected isError for: \(line)") + #expect(replies[0]["error"] == nil) + #expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("research").path)) + } + } } diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 5d58b07..ad78347 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -8,6 +8,16 @@ // project (#60), Trash delete, save-time normalization. // #108: project moves, archive/restore, project unarchive + creation. // +// ## Scenario: candidate rail and the keep write +// From #29 (S8.1/S8.2) +// Given a piece in the library and the mentor researching mid-pass +// When the engine delivers findings as submit_research_notes tool calls +// Then well-formed candidates are accepted with a received count and +// nothing is written anywhere; malformed ones answer a tool error +// And the pass prompt names that rail +// And when the writer keeps one, one plain markdown note with provenance +// lands in the piece's research/ — nothing else auto-saves. +// import Foundation @testable import Museion @@ -669,15 +679,19 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String) } } -@Test func `stub carries pass name piece path and fix-card reminder`() { +@Test func `stub carries pass name piece path research rail and fix-card reminder`() { let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md") let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false) #expect(stub.contains("Pass 1 — paragraph level and up.")) #expect(stub.contains("Piece: /vault/projects/essays/essay/post.md")) #expect(!stub.contains("Research notes:")) - let closing = "Critique the piece for this pass. Deliver the verdict in your reply — " - + "findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." + // #29: the typed research rail is named in the closing block — the + // engine delivers findings, it never writes candidates itself. + let closing = "Critique the piece for this pass. 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." #expect(stub.contains(closing)) #expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false) .contains("Pass 2 — sentence level and below.")) @@ -703,3 +717,122 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String) } } } + +// MARK: Research notes (#29) + +/// The keep writes "today" — computed at test time like promote's day +/// stamp (a midnight rollover mid-suite is tolerated). +private func researchDay() -> String { + FixCardStore.formatted(Date(), "yyyyMMdd") +} + +@Test func `writeResearchNote lands the pinned markdown shape in research`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Kept\n", home: home) + + let name = try PostStore.writeResearchNote( + piecePath: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true).path, + title: "The Long Now", + url: "https://example.org/long-now", + quote: "pace layers", + note: "Supports the slowness claim.", + home: home, + ) + + let day = researchDay() + #expect(name == "\(day)-the-long-now.md") + let markdown = try String( + contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)"), + encoding: .utf8, + ) + let expected = "---\nsource: https://example.org/long-now\nkept: \(day)\n---\n\n" + + "# The Long Now\n\nSupports the slowness claim.\n\n> pace layers\n" + #expect(markdown == expected) +} + +@Test func `writeResearchNote omits absent note and quote sections`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Bare\n", home: home) + let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true) + + // Both absent: frontmatter + heading, nothing else. + let name = try PostStore.writeResearchNote( + piecePath: pieceDir.path, title: "Only A Link", url: "https://example.org/one", + quote: "", note: "", home: home, + ) + let bare = try String(contentsOf: pieceDir.appendingPathComponent("research/\(name)"), encoding: .utf8) + #expect(bare == "---\nsource: https://example.org/one\nkept: \(researchDay())\n---\n\n# Only A Link\n") + + // Quote without note: the note section goes, the quote stays. + let quoted = try PostStore.writeResearchNote( + piecePath: pieceDir.path, title: "Quoted", url: "https://example.org/two", + quote: "citation needed", note: "", home: home, + ) + let text = try String(contentsOf: pieceDir.appendingPathComponent("research/\(quoted)"), encoding: .utf8) + #expect(text.hasSuffix("\n\n# Quoted\n\n> citation needed\n")) +} + +@Test func `writeResearchNote collision takes -2`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Twice\n", home: home) + let piecePath = home.appendingPathComponent("projects/posts/\(post.id)").path + + let first = try PostStore.writeResearchNote( + piecePath: piecePath, title: "Same Source", url: "https://example.org/same", + quote: "", note: "", home: home, + ) + let second = try PostStore.writeResearchNote( + piecePath: piecePath, title: "Same Source", url: "https://example.org/same", + quote: "", note: "", home: home, + ) + + let day = researchDay() + #expect(first == "\(day)-same-source.md") + #expect(second == "\(day)-same-source-2.md") +} + +@Test func `writeResearchNote accepts the post.md file form`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# File Form\n", home: home) + + let name = try PostStore.writeResearchNote( + piecePath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path, + title: "Via File", url: "https://example.org/file", + quote: "", note: "", home: home, + ) + + #expect(FileManager.default.fileExists( + atPath: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)").path, + )) +} + +@Test func `writeResearchNote on vanished piece throws`() throws { + let home = try storeHome() + #expect(throws: FixCardStore.CardError(message: "piece not found: /nowhere/post.md")) { + try PostStore.writeResearchNote( + piecePath: "/nowhere/post.md", title: "Ghost", url: "https://example.org", + quote: "", note: "", home: home, + ) + } +} + +@Test func `writeResearchNote refuses a symlinked research dir`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Guarded\n", home: home) + let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true) + let target = home.appendingPathComponent("elsewhere", isDirectory: true) + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: pieceDir.appendingPathComponent("research"), + withDestinationURL: target, + ) + + let planted = pieceDir.appendingPathComponent("research").path + #expect(throws: FixCardStore.CardError(message: "research path is a symlink: \(planted)")) { + try PostStore.writeResearchNote( + piecePath: pieceDir.path, title: "Planted", url: "https://example.org", + quote: "", note: "", home: home, + ) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty) +} diff --git a/MuseionTests/ResearchCandidateTests.swift b/MuseionTests/ResearchCandidateTests.swift new file mode 100644 index 0000000..8a252b8 --- /dev/null +++ b/MuseionTests/ResearchCandidateTests.swift @@ -0,0 +1,160 @@ +// +// ResearchCandidateTests.swift +// MuseionTests +// +// #29 (S8.1–S8.3): the research-candidate pins, own file — +// SessionLifecycleTests crossed its type-body ceiling (MCPToolsPromoteTests +// precedent). Reuses the shared fake ACP harness. +// + +import Foundation +@testable import Museion +import Testing + +// #29 suite: candidate parsing, curation, and replay survival. + +struct ResearchCandidateTests { + /// #29 (S8.2): the batch parser — two notes → two candidates with "" + /// defaults; a missing piece_path, an empty/absent notes array, or a + /// note missing title/url yields NO candidates (the raw row owns it). + @Test func `research batch parses notes and refuses garbage`() { + let good: JSONValue = .object([ + "piece_path": .string("/tmp/piece"), + "notes": .array([ + .object(["title": .string("A"), "url": .string("https://a"), "quote": .string("q"), "note": .string("n")]), + .object(["title": .string("B"), "url": .string("https://b")]), + ]), + ]) + let batch = ResearchCandidate.batch(good) + #expect(batch.count == 2) + #expect(batch[0] == ResearchCandidate(piecePath: "/tmp/piece", title: "A", url: "https://a", quote: "q", note: "n")) + #expect(batch[1].quote == "") + #expect(batch[1].note == "") + #expect(batch[1].disposition == .pending) + + // Garbage: no piece_path / empty notes / absent notes / note missing url / not an object. + #expect(ResearchCandidate.batch(.object([ + "notes": .array([.object(["title": .string("A"), "url": .string("https://a")])]), + ])).isEmpty) + #expect(ResearchCandidate.batch(.object(["piece_path": .string("/tmp/piece"), "notes": .array([])])).isEmpty) + #expect(ResearchCandidate.batch(.object(["piece_path": .string("/tmp/piece")])).isEmpty) + #expect(ResearchCandidate.batch(.object([ + "piece_path": .string("/tmp/piece"), + "notes": .array([.object(["title": .string("A")])]), + ])).isEmpty) + // Audit pin: whitespace-only title/url are the wire's refusal too — + // both boundaries must agree (an invisible-titled card used to be + // keepable as `-untitled.md`). + #expect(ResearchCandidate.batch(.object([ + "piece_path": .string("/tmp/piece"), + "notes": .array([.object(["title": .string(" "), "url": .string("https://a")])]), + ])).isEmpty) + #expect(ResearchCandidate.batch(.object([ + "piece_path": .string("/tmp/piece"), + "notes": .array([.object(["title": .string("A"), "url": .string(" ")])]), + ])).isEmpty) + #expect(ResearchCandidate.batch(nil).isEmpty) + } + + /// #29 AC (S8.2): candidates live in their session — resume + /// re-materializes them from the replayed transcript (engine-owned + /// cargo). The planted session's history carries one research tool call + /// with two notes; the default open RESUMES it, so the candidates are + /// there without any extra turn. + @Test @MainActor func `resume re-materializes research candidates from the replay`() async throws { + let rosterDir = acpTempDir("research-roster") + let entry = SessionEntry(sessionId: "sess-1", name: "Research", pieceTitle: nil, createdAt: Date()) + SessionRoster.save([entry], directory: rosterDir) + let fake = makeFakeACP(at: acpTempDir("research"), mode: "loadReplay") + let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir) + defer { mentor.shutdown() } + await mentor.openSession() + + var candidates: [ResearchCandidate] = [] + for _ in 0 ..< 500 { + candidates = mentor.transcriptRows(of: entry).compactMap { + if case let .researchNote(candidate) = $0.content { + candidate + } else { + nil + } + } + if candidates.count == 2 { + break + } + try await Task.sleep(nanoseconds: 20_000_000) + } + // #require (not bare #expect + subscript): a missed settle must fail + // the test, never trap the runner on an out-of-bounds index. + try #require(candidates.count == 2, "expected two candidates from the replay, got \(candidates.count)") + #expect(candidates.allSatisfy { $0.piecePath == "/tmp/piece" }) + #expect(candidates[0].title == "Hinge Study") + #expect(candidates[0].url == "https://example.org/hinge") + #expect(candidates[0].quote == "We should stop listening.") + #expect(candidates[0].note == "Counts the pivot tense.") + // The second note's absent quote/note default to "". + #expect(candidates[1].title == "Second Source") + #expect(candidates[1].quote == "") + #expect(candidates[1].note == "") + #expect(candidates.allSatisfy { $0.disposition == .pending }) + } + + /// #29 (S8.3): the curation mutation — kept/rejected replace the row's + /// content in the ACTIVE session's transcript; an unknown row id no-ops. + @Test @MainActor func `research disposition flips the row and no-ops unknown ids`() async throws { + let rosterDir = acpTempDir("disposition-roster") + let entry = SessionEntry(sessionId: "sess-1", name: "Research", pieceTitle: nil, createdAt: Date()) + SessionRoster.save([entry], directory: rosterDir) + let fake = makeFakeACP(at: acpTempDir("disposition"), mode: "loadReplay") + let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir) + defer { mentor.shutdown() } + await mentor.openSession() + + var rows: [SessionRow] = [] + for _ in 0 ..< 500 { + rows = mentor.transcriptRows(of: entry).filter { + if case .researchNote = $0.content { + return true + } + return false + } + if rows.count == 2 { + break + } + try await Task.sleep(nanoseconds: 20_000_000) + } + try #require(rows.count == 2, "expected two candidate rows, got \(rows.count)") + + mentor.setResearchDisposition(rowID: rows[0].id, .kept(fileName: "20261022-hinge-study.md")) + mentor.setResearchDisposition(rowID: rows[1].id, .rejected) + mentor.setResearchDisposition(rowID: UUID(), .rejected) // unknown id — no-op + + let after = mentor.transcriptRows(of: entry) + #expect(after.contains { row in + if case let .researchNote(candidate) = row.content { + return candidate.disposition == .kept(fileName: "20261022-hinge-study.md") + } + return false + }) + #expect(after.contains { row in + if case let .researchNote(candidate) = row.content { + return candidate.disposition == .rejected + } + return false + }) + // Exactly two research rows still — the unknown id added nothing. + #expect(after.filter { + if case .researchNote = $0.content { + return true + } + return false + }.count == 2) + } + + /// #29 (S8.3): the writing filter keeps candidate cards visible. + @Test func `writing filter keeps research candidate rows`() { + #expect(SessionTranscriptView.isWritingRow(SessionRow(content: .researchNote(ResearchCandidate( + piecePath: "/tmp/piece", title: "A", url: "https://a", quote: "", note: "", + ))))) + } +} diff --git a/MuseionTests/SessionLifecycleTests.swift b/MuseionTests/SessionLifecycleTests.swift index 6fb436e..ba3331a 100644 --- a/MuseionTests/SessionLifecycleTests.swift +++ b/MuseionTests/SessionLifecycleTests.swift @@ -380,7 +380,7 @@ struct SessionLifecycleTests { defer { mentor.shutdown() } await mentor.openSession() _ = await mentor.sendPrompt("hello") // a turn lands in the active session - #expect(!mentor.transcriptRows(of: try #require(mentor.activeEntry)).isEmpty) + #expect(try !mentor.transcriptRows(of: #require(mentor.activeEntry)).isEmpty) if let pid = mentor.childProcessIdentifier { kill(pid, SIGKILL) // crash the child @@ -398,7 +398,7 @@ struct SessionLifecycleTests { await mentor.restart() // The post-restart transcript is the ENGINE's replay — the replay // marker proves the words came from the engine, not the local copy. - let rows = mentor.transcriptRows(of: try #require(mentor.activeEntry)) + let rows = try mentor.transcriptRows(of: #require(mentor.activeEntry)) #expect(rows.contains { row in if case let .text(text) = row.content { return text.contains("earlier ask") diff --git a/docs/devlog/20261022-issue29-research-library-light_log.md b/docs/devlog/20261022-issue29-research-library-light_log.md new file mode 100644 index 0000000..9bb9e85 --- /dev/null +++ b/docs/devlog/20261022-issue29-research-library-light_log.md @@ -0,0 +1,71 @@ +# #29 M5: Research & library-light (S8) + +> **Date:** 2026-10-22 +> **Type:** issue +> **Reference:** [#29 M5: Research & library-light (S8)](https://git.babylondreams.de/AlexKucera/museion/issues/29) (PRD S8.1–S8.3, G9 trust defaults) + +## Goal + +The mentor researches mid-pass and its findings arrive as candidate source-notes with provenance inside their Session. The writer curates: Keep writes plain markdown into the Post's `research/`; Reject vanishes; nothing auto-saves. Candidates survive session resume (engine-owned cargo, ADR-0007); kept notes feed later passes as context. Both blockers (#24, #28) were closed before work started. + +## What Was Done + +Two parallel subagent slices implemented the feature (both interrupted by infra timeouts near the end; finished in-session), then a three-reviewer finish-audit (ponytail / security / general) drove a second fix batch. + +- **The candidates rail** (`Museion/MCPServer.swift`) — third museion-tools tool `submit_research_notes`, shape `{piece_path, notes:[{title, url, quote?, note?}]}`. Decode-validate ONLY; replies `{"received": N}`; writes nothing (S8.2 nothing-auto-saves — the tool is not a storage rail). Schema declares the candidates-only semantics. +- **The pass prompt names the rail** (`Museion/Pass.swift`) — the pinned stub gains one clause: fact-check where needed, findings travel as `submit_research_notes` candidate tool calls, never written by the engine. +- **The keep write** (`Museion/PostStore.swift`) — `writeResearchNote(piecePath:title:url:quote:note:home:)`: resolves the piece through the ONE `folder(of:)` id lookup (folder or post.md path form), refuses a symlinked `research/` (promote's posture), lands `<yyyyMMdd>-<slug(title)>.md` via FixCardStore's now-internal `uniqueFile`, flat single-line frontmatter (`source`/`kept`; title/url newline-flattened), empty note/quote sections omitted, atomic. Returns the landed file name. +- **Session cargo** (`Museion/MentorSessionModel.swift`) — `ResearchCandidate` (piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote`. `appendToolCall` routes on PAYLOAD SHAPE (top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key. `ResearchCandidate.batch` parses one candidate per note, all-or-nothing per batch (garbage → raw row), whitespace-only title/url refused (the wire's trim rule mirrored). `setResearchDisposition` flips the ACTIVE session's row (file-scope extension, type-body posture). Resume re-materializes candidates for free: replays re-run `appendToolCall`. +- **The curation surface** (`Museion/SessionTranscriptView.swift`, new `Museion/ResearchKeepSheet.swift`, `Museion/MentorPaneView.swift`, `Museion/SessionsPaneView.swift`, `Museion/WorkspaceView.swift`) — candidates render as full cards in the shared transcript (no palette — a handful curates in place): serif title, mono muted url, selectable note, italic quote; pending offers Keep + Reject (hidden when `home` is nil — previews); kept/rejected dim 0.45 with meta `kept · research/<file>` / `rejected`. Keep = ask-before (G9): `ResearchKeepSheet` (PromoteAskSheet posture — inline orange refusal, buttons kept) → ONE confirm → `writeResearchNote`. Reject = no confirm (Dismiss-button voice). Sheet state lives in SessionTranscriptView (`pendingKeep`, `.sheet(item:)` — never inside a lazy row); `home` threads from both panes. +- **Finish-audit fixes** — whitespace title/url parity between wire and parser (converged finding); shape-based routing so a research payload with stray `pattern`/`problem` keys can't vanish into a card row (converged); `ResearchNoteContent` extracted (row + sheet share one render); war-story trimmed from MuseionTests/AGENTS.md. Rejected: parser merge (strict wire vs lenient transcript are deliberate different postures), batch cap (the raw-row fallback retains identical bytes — the unbounded transcript IS the adjudicated engine-owned-cargo ceiling). Deferred: piece-level symlink guard in `folder(of:)` (same ceiling as promote; fixes both when it lifts). +- **Tests** — new `MuseionTests/ResearchCandidateTests.swift` (own file; SessionLifecycleTests crossed its type-body ceiling, MCPToolsPromoteTests precedent): batch matrix (incl. whitespace audit pin), resume re-materialization AC pin (end-to-end over the real client + fake), disposition flip/no-op, writing-filter pin. `MuseionTests/ACPClientTests.swift`: the fake's `loadReplay` mode streams a research tool_call (resume pin) and a `strayResearchOnPrompt` mode carries a stray-keys payload (routing pin). `MCPServerWireTests`: three tools listed, received-count reply, nothing-on-disk pin, malformed → isError. `PostStoreTests`: markdown shape, section omission, collision `-2`, post.md path form, vanished piece, symlinked `research/` refusal. Stub-shape pin updated for the research clause. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Candidates travel as a typed tool call that writes NOTHING | ADR-0006 posture (never prose to parse) + S8.2: the session is the holding area; the only path to disk is the writer's Keep. The tool's reply is a received count, not storage. | +| Resume survival comes free from replay | Transcripts are engine-owned (ADR-0007); the candidates ARE transcript rows, so `session/load` re-materializes them with no app-side persistence. Dispositions reset honestly — they were never persisted. | +| Keep = blocking ask sheet; Reject = no confirm | G9 classifies keep-note as ask-before (PromoteAskSheet/ApplyAskSheet house posture); rejection is low-stakes and self-healing (Dismiss-button voice). | +| Route tool calls by payload shape, not title | A tool_call's `title` is display text, not guaranteed to be the raw tool name; the `notes` array is the deterministic discriminator, and routing research first keeps stray-key payloads from vanishing into a card row. | +| Full cards in the transcript instead of a Fix-Cards-style palette | Fix cards accumulate dozens and need a work surface; research candidates are a handful mid-pass — curating in place is the smaller UI. | +| `writeResearchNote` anchors via `folder(of:)` id lookup, not path-shape validation | The one-resolver rule beats re-implementing `resolvePostURL`'s shape check; a garbage path fails the id lookup honestly and the write can only land inside this Home. | +| Two parsers stay separate (audit rejection) | The MCP decode is strict (a tool error teaches the engine the shape); the transcript parse is deliberately lenient (falls to the raw row, payload stays visible). Merging needs a mode flag that costs more than the duplication; both shapes are test-pinned. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Both resume pins timed out (10 s polls, 0 candidates); the subagent chased "parallel load" | The fake ACP's research echo line missed the `"rawInput"` key's closing quote — `"rawInput':"$research"` emitted invalid JSON, which the client silently dropped (deterministic, load-independent) | Fixed the quoting to the fix-card line's exact pattern; lesson pinned in the test file's fake comments | +| Grep-filtered xcodebuild output lost the verdict line while xcresult showed `372 failed: 1` | Background runs pipe through `grep | tail`, and concurrent xcodebuild invocations (an orphaned foreground rerun) wrote interleaved result bundles | `xcrun xcresulttool get test-results summary --path <bundle>` is the authoritative gate — count failures from the bundle, not the pipe | +| Full suite failed 1–3 tests per run; the persistent one was `debounce flushes after idle and stamps the sidecar` | The rig's FIRST flush already polled, but its sidecar half slept a fixed 200 ms — under full-suite parallel load (48 more tests from #29) the main actor starved the second debounce past any constant | Converted the sidecar wait to the same poll loop (poll `readCursor` == cursor within the existing deadline — the sidecar lands on flush, so the pin still proves the flush wrote it); full suite went green (373 tests, 0 failures). Remaining single-run rotates in PassRun rigs pass isolated — follow-up issue candidate | +| Audit additions pushed `SessionLifecycleTests` and `MentorSessionModel` over their SwiftLint type-body ceilings | The #29 pins (~120 lines) and routing changes landed in already-large bodies | Own-file `ResearchCandidateTests.swift` (MCPToolsPromoteTests precedent) + `setResearchDisposition` moved to a file-scope extension (PostsModel guards precedent) | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/MCPServer.swift` | Third tool `submit_research_notes` — validate-only rail, `{"received": N}` reply | +| `Museion/Pass.swift` | Stub gains the research-rail clause | +| `Museion/PostStore.swift` | `writeResearchNote` — the keep write into `<piece>/research/` | +| `Museion/FixCardStore.swift` | `uniqueFile` widened internal for reuse | +| `Museion/MentorSessionModel.swift` | `ResearchCandidate` + shape-based routing in `appendToolCall` + `setResearchDisposition` (file-scope extension) | +| `Museion/SessionTranscriptView.swift` | `home` param, candidate cards, Keep/Reject, shared `ResearchNoteContent`, keep sheet state | +| `Museion/ResearchKeepSheet.swift` | NEW — the ask-before keep confirm | +| `Museion/MentorPaneView.swift` / `SessionsPaneView.swift` / `WorkspaceView.swift` | `home` threading to the transcript | +| `MuseionTests/ACPClientTests.swift` | Fake: research replay payload + `strayResearchOnPrompt` mode; routing pin test | +| `MuseionTests/ResearchCandidateTests.swift` | NEW — the four research-candidate pins | +| `MuseionTests/MCPServerWireTests.swift` / `PostStoreTests.swift` | Wire pins (received/nothing-written/malformed) + store pins (shape/collision/forms/symlink) | +| `MuseionTests/SessionLifecycleTests.swift` | Rebalanced below its type-body ceiling (pins moved out) | +| `AGENTS.md` / `Museion/AGENTS.md` / `MuseionTests/AGENTS.md` | DOX pass: the research rail, keep write, candidates, curation surface, test pins | + +## Open Items & Next Steps + +- [ ] Engine-side research initiative (when to research, how to use the tool) is the museion-profile/skills lane (#56–#58); the stub now tells passes the rail exists +- [ ] Full-suite parallel-load flakes in PassRun/EditorSession rigs (2–3 rotating settle-window failures per run; all pass isolated) — follow-up issue candidate +- [ ] Piece-level symlink guard in `PostStore.folder(of:)` if the single-user ceiling ever lifts (fixes promote + research keep together) +- [ ] Kept candidate re-keep after resume creates a `-2` duplicate — accepted (engine-owned cargo); revisit only if it bites + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index e3b1b43..d892898 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 <!-- write-log: full-index --> | Date | Type | File | Summary | |------|------|------|---------| +| 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 | | 2026-10-21 | issue | [20261021-issue26-promote-consult-learnings_log.md](20261021-issue26-promote-consult-learnings_log.md) | #26 promote/consult Learnings: teaching-shape files, on-disk-truth promote, symlink guard, Learnings pane — 329 tests green |