feat(mentor): research & library-light (S8) (#29)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
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 (ADR-0006
posture): decode-validate only, reply {"received": N}, write NOTHING
— the session is the holding area, and keeping is the writer's act.
Candidates ride the transcript as first-class rows (researchNote):
parsed from the tool call's rawInput by payload shape — the notes
array routes before the fix-card parse, titles are display text —
one row per note, all-or-nothing per batch, the wire's whitespace
rule mirrored so both boundaries agree. Resume re-materializes them
for free: replays re-run the same parse; dispositions reset honestly
(they were never persisted — engine-owned cargo, ADR-0007).
The writer curates in place (full cards in the shared transcript, no
palette — a handful curates where it lands): Keep opens the
ask-before sheet (G9; PromoteAskSheet posture — inline refusal,
buttons kept) and ONE confirm lands one plain markdown note with
provenance into the piece's research/ via writeResearchNote — the
one folder(of:) id lookup anchors it inside this Home, a symlinked
research/ refuses, collision -2; Reject vanishes, recording nothing.
The pass stub names the rail and forbids the engine writing
candidates itself; kept notes flip hasResearch, so every later pass
sees the research/ path (S8.3 at v1 depth).
Finish-audit (three reviewers) drove the whitespace-parity and
shape-routing fixes, the ResearchNoteContent dedup, and a poll-loop
fix for the debounce rig's sidecar half that the larger suite's load
had pushed past its fixed sleep — full suite green (373 tests).
Closes #29
This commit is contained in:
1 parent
9895614b7e
commit
b02d36bb5d
22 files changed
+977
-33
No files matched your search
+7
-7
@@ -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 \<title\>" — 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 `<home>/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 `<project>` + 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` (`outlineGLine truncated
|
||||
- `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 \<title\>" — 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 `<home>/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 `<project>` + 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 pLine truncated
|
||||
- `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/<name>/<id>/post.md` AND `archive/<name>/<id>/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/<project>/` — 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>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — 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/<name>/`), 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 `<piece>/passes/pass-<n>.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 resurfacLine truncated
|
||||
- `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/<project>/` — 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>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — 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/<name>/`), 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 `<piece>/passes/pass-<n>.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 resurfacLine truncated
|
||||
- `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 sessionLine truncated
|
||||
- `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 `titlLine truncated
|
||||
**#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 `titlLine truncated
|
||||
- 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.
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+82
-3
@@ -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],
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -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."
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user