feat(sessions): session lifecycle UI (S2.3) (#28)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Each Session is a conversation Museion UIs, never owns. The mentor bridge hosts multiple engine-owned sessions: per-session transcripts keyed by wire sessionId behind same-named proxies (every existing caller compiles unchanged), a names-only roster at Application Support/sessions.json (0600; id/name/pieceTitle/date — the words stay engine-owned per ADR-0007), and the standard affordances over the wire: session/new, session/load, session/fork, compact as the /compress slash prompt, session/cancel as the Stop rail. The Sessions pane replaces its placeholder: roster list (piece- associated by name when Posts has an open piece), row-click resume with the engine's full-history replay (user turns included), Fork · Compact, live streaming with Stop; every pass auto-creates its rostered session and streams into it; the transcript renderer is shared with the mentor pane. Notification hops ride the main queue (FIFO with the continuation resume) so the adapter's replay-before- response contract is guaranteed, not probabilistic. Resume refusals are honest and entry-attributed (an engine-unknown session never fabricates history); concurrent replays refuse instead of interleaving; restart replays from the engine rather than trusting a diverging local copy. Finish-audit (three reviewers) surfaced the concurrent-resume race, the dead restart branch, the runPass guard window, the 15 s session/load default, and the missing createSession backstop — all fixed and pinned (12 lifecycle pins; 359 tests green). Closes #28
This commit is contained in:
1 parent
78c8844184
commit
9895614b7e
15 files changed
+1523
-245
No files matched your search
@@ -132,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **museion** (4079 symbols, 13825 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **museion** (4188 symbols, 14647 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
|
||||
@@ -180,6 +180,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-22 | [20261022-issue28-session-lifecycle-ui_log.md](docs/devlog/20261022-issue28-session-lifecycle-ui_log.md) |
|
||||
| 2026-10-21 | [20261021-issue27-dismiss-decay-learnings_log.md](docs/devlog/20261021-issue27-dismiss-decay-learnings_log.md) |
|
||||
| 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) |
|
||||
| 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) |
|
||||
@@ -189,4 +190,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
| 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) |
|
||||
| 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) |
|
||||
| 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) |
|
||||
| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) |<!-- write-log: window-end -->
|
||||
<!-- write-log: window-end -->
|
||||
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **sessions:** Session lifecycle UI (PRD S2.3, ADR-0007) — the mentor bridge hosts multiple engine-owned sessions on one child: per-session transcripts keyed by wire sessionId behind the same-named proxies (every existing caller compiles unchanged), a names-only roster at `~/Library/Application Support/Museion/sessions.json` (0600; id/name/pieceTitle/date — the words stay engine-owned), and the standard affordances over the wire: `session/new`, `session/load` (the engine replays the full history before responding — user turns included), `session/fork`, compact as the `/compress` slash prompt, `session/cancel` as the Stop rail. The Sessions pane replaces its placeholder: roster list (piece-associated by name when Posts has an open piece), row-click resume, Fork · Compact, live streaming with Stop; every pass auto-creates its rostered session ("Pass N · \<title\>") and streams into it; the transcript renderer is shared with the mentor pane. Resume refusals are honest and entry-attributed (an engine-unknown session never fabricates history), concurrent replays refuse instead of interleaving, restart replays from the engine, and the notification hops ride the main queue so the adapter's replay-before-response contract is guaranteed. Finish-audit (three reviewers) surfaced the concurrent-resume race, the dead restart branch, the runPass guard window, the 15 s session/load default, and the missing createSession backstop — all fixed and pinned (issue #28)
|
||||
|
||||
- **mentor:** Dismiss & decay for Learnings (PRD S4.2, G8) — dismissed patterns fade instead of haunting: a Dismiss button on every visible Learning in the Learnings pane stamps decay state into the Learning's own frontmatter (`dismissed`, `dismiss_count`, `dismissed_at_pass` — every other line preserved verbatim; hand-editable, git-diffable, survives restarts) and hides it from every pass: `query_learnings` serves only visible learnings. Resurfacing is an output clock, not a calendar — a dismissed Learning returns after 10 subsequent completed passes of its content type (a per-type counter under `<home>/learnings/pass-counts.json`, ticked by every completed pass, re-runs included), each re-dismiss doubles the interval (10 → 20 → 40…), and a per-Learning `resurface_after` frontmatter key overrides the base 10. Dismissed rows dim with a "resurfaces in N passes" countdown and no button until they return; hand-edited decay state reads leniently — garbage means visible, absurd numbers clamp, a hand-edit can never crash the pane or the rail (issue #27)
|
||||
|
||||
- **mentor:** Promote & consult Learnings (PRD S4.1/S4.3/S4.4, ADR-0005) — only the writer's explicit confirmation promotes a Fix Card into a Learning: one confirm = one entry, never a repetition counter (the store refuses a second promote of a stamped card). The promote ask on every card row (open or closed — the Learning outlives the card) matches the design contract's dialog (pattern/problem/provenance preview, Cancel/Promote); confirming writes ONE plain markdown file `<home>/learnings/<type>s/YYYYMMDD-<pattern-slug>.md` carrying the card's teaching fields — pattern, problem, diagnostic question, the demonstration example (demonstration lanes only) — plus promotion provenance (flat frontmatter + readable body, `from_card` traceability, collision -2; the instance-bound anchor and mechanical replacement stay on the card — the Learning teaches the symptom/fix, never re-quotes the originating text) and stamps the card `promoted_at` (pre-#26 cards decode nil); every pass consults exactly these files through `query_learnings`, so recurring weaknesses surface as fix cards; the Learnings pane replaces its placeholder — list-only, grouped by content type, newest first, lenient to hand-edits; learnings are hand-editable, git-diffable, per-writer portable files in the Home (dismiss/decay landed in #27) (issue #26)
|
||||
|
||||
+6
-5
@@ -14,19 +14,19 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
|
||||
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
|
||||
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's `state.json` (see below).
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exceptions (both app metadata, never content): the engine gate's `state.json` and the session roster's `sessions.json` (#28 — names/ids only; transcripts stay engine-owned per ADR-0007).
|
||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
|
||||
- App icon: `Assets.xcassets/AppIcon.appiconset` — single-size 1024×1024 PNG (`Museion-Logo_1024.png`); Xcode derives all sizes. The built icns tops out at 256 px entries — that matches Apple's own apps on this macOS; larger sizes come from the catalog.
|
||||
|
||||
## Workspace shell (M1, #17 + #18 / S1.1)
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions stays an honest placeholder until #28; **#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` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (plain + button; becomes a Menu — "New Session" / "New Session on \<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
|
||||
- `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).
|
||||
- `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
|
||||
- `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.
|
||||
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||
@@ -71,8 +71,9 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
## 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): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), 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) → `session/new` cwd `~` + `mcpServers: []`. `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.
|
||||
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note, 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 (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `title(of:)`), Cancel/Promote; ONE confirm → `promoteCard`, refusal inline orange with buttons kept (ApplyAskSheet posture).
|
||||
- `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
|
||||
- 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.
|
||||
|
||||
|
||||
@@ -71,7 +71,9 @@ struct MentorPaneView: View {
|
||||
.padding(.vertical, 6)
|
||||
Divider()
|
||||
}
|
||||
transcript
|
||||
// #28: the transcript rendering is shared — the Sessions pane
|
||||
// reads the same surface in the writing voice.
|
||||
SessionTranscriptView(model: model, showsDebugRows: debugRows)
|
||||
Divider()
|
||||
inputBar
|
||||
case let .crashed(lastPrompt):
|
||||
@@ -81,7 +83,10 @@ struct MentorPaneView: View {
|
||||
// #17: the pane lives in the workspace's fixed 356pt mentor column —
|
||||
// no root min frame (it was the full-window M0 surface).
|
||||
.task {
|
||||
model.binaryPath = binaryPath ?? model.binaryPath
|
||||
// #28 review: an honest if-let — the ?? self-assignment was a no-op.
|
||||
if let binaryPath {
|
||||
model.binaryPath = binaryPath
|
||||
}
|
||||
// Hosted unit tests run this app as their runner — never spawn a
|
||||
// real engine child there (it outlives the test session and kills
|
||||
// the runner).
|
||||
@@ -90,16 +95,6 @@ struct MentorPaneView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The writing-session transcript: prose (verdicts, labels, notes) and
|
||||
/// card events stay; raw session/tool rows and collapsed thinking are
|
||||
/// debug-only. Static — pure, testable.
|
||||
static func isWritingRow(_ row: SessionRow) -> Bool {
|
||||
switch row.content {
|
||||
case .text, .fixCard: true
|
||||
case .thought, .raw: false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Header
|
||||
|
||||
private var header: some View {
|
||||
@@ -120,7 +115,7 @@ struct MentorPaneView: View {
|
||||
.help(note)
|
||||
}
|
||||
Spacer()
|
||||
if case let .ready(sessionId) = model.phase {
|
||||
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId {
|
||||
Text("session \(sessionId.prefix(8))")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
@@ -160,112 +155,6 @@ struct MentorPaneView: View {
|
||||
.padding(.top, 10)
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
|
||||
// MARK: Transcript
|
||||
|
||||
private var transcript: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 10) {
|
||||
ForEach(model.rows.filter { debugRows || Self.isWritingRow($0) }) { row in
|
||||
rowView(row)
|
||||
}
|
||||
if debugRows, !model.streamingThought.isEmpty {
|
||||
// Live thinking: quiet, capped — it's transient (the full
|
||||
// text lands in a collapsed row when the turn ends).
|
||||
Text(model.streamingThought)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(3)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
if !model.streamingText.isEmpty {
|
||||
textRow("Mentor: \(model.streamingText)")
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
// #24 fix: programmatic scrollTo raced the growing lazy rows and
|
||||
// mislanded at the TOP; the native bottom anchor needs no scroll code.
|
||||
.defaultScrollAnchor(.bottom)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func rowView(_ row: SessionRow) -> some View {
|
||||
switch row.content {
|
||||
case let .text(text):
|
||||
textRow(text)
|
||||
case let .thought(text):
|
||||
ThoughtRow(text: text)
|
||||
case let .fixCard(card):
|
||||
// #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 .raw(kind, json):
|
||||
RawUpdateRow(kind: kind, json: json)
|
||||
}
|
||||
}
|
||||
|
||||
private func textRow(_ text: String) -> some View {
|
||||
Text(text)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
// MARK: Rows
|
||||
|
||||
/// The tool-call EVENT, not the card: the pattern title alone. The
|
||||
/// card's full statement lives in the Fix Cards palette window.
|
||||
private struct FixCardEventRow: View {
|
||||
let pattern: String
|
||||
|
||||
var body: some View {
|
||||
Label(pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
/// #24 fix: the engine's thinking, collapsed — a pass's thought stream runs
|
||||
/// to hundreds of lines and is not the critique (only `agent_message_chunk`
|
||||
/// is). Same shape as RawUpdateRow: quiet mono, expandable, never in the way.
|
||||
private struct ThoughtRow: View {
|
||||
let text: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(text)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text("thinking")
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RawUpdateRow: View {
|
||||
let kind: String
|
||||
let json: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(json)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text(kind)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Input + crash card (file-scope extension — type_body_length posture)
|
||||
@@ -322,7 +211,7 @@ private extension MentorPaneView {
|
||||
|
||||
// MARK: Crash → restart prompt (map decision: EOF/crash surfaces an
|
||||
|
||||
// in-pane Restart prompt, never data loss)
|
||||
// in-pane Restart prompt; the transcript replays from the engine (ADR-0007)
|
||||
|
||||
private func crashCard(lastPrompt: String?) -> some View {
|
||||
VStack(spacing: 14) {
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
// Museion
|
||||
//
|
||||
// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle,
|
||||
// one session, prompt streaming, fix-card render, crash → restart prompt.
|
||||
// prompt streaming, fix-card render, crash → restart prompt.
|
||||
// #28 (S2.3): multi-session — a persisted roster of engine-owned sessions
|
||||
// (session/new, session/load, session/fork, /compress on the wire), one
|
||||
// transcript per session, and the same-named ACTIVE surface (rows, buffers,
|
||||
// sendPrompt, stop) so the pane and every existing test read unchanged.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@@ -50,16 +54,66 @@ enum TurnOutcome: Equatable {
|
||||
case failed
|
||||
}
|
||||
|
||||
/// One rostered mentor session (#28, S2.3). Piece association is by
|
||||
/// convention — the entry's `pieceTitle` field only, no filesystem linkage.
|
||||
/// History is engine-owned; only these four fields persist.
|
||||
nonisolated struct SessionEntry: Identifiable, Equatable, Codable {
|
||||
let sessionId: String
|
||||
let name: String
|
||||
var pieceTitle: String?
|
||||
let createdAt: Date
|
||||
|
||||
var id: String {
|
||||
sessionId
|
||||
}
|
||||
}
|
||||
|
||||
/// The persisted roster (#28) — a JSON array of entries at a
|
||||
/// caller-injectable directory, default `~/Library/Application
|
||||
/// Support/Museion/sessions.json`. EngineGate's state.json posture: wholesale
|
||||
/// replace, atomic, a write failure must never crash the app.
|
||||
nonisolated enum SessionRoster {
|
||||
static func load(directory: String? = nil) -> [SessionEntry] {
|
||||
guard let data = try? Data(contentsOf: rosterURL(directory)) else { return [] }
|
||||
return (try? JSONDecoder().decode([SessionEntry].self, from: data)) ?? []
|
||||
}
|
||||
|
||||
static func save(_ entries: [SessionEntry], directory: String? = nil) {
|
||||
let dir = directory ?? defaultDirectory
|
||||
do {
|
||||
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(entries).write(
|
||||
to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"),
|
||||
options: .atomic,
|
||||
)
|
||||
// Finish-audit: names+ids only, but piece titles are the writer's
|
||||
// business — the default umask would hand them to every local user.
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path)
|
||||
} catch {
|
||||
// ponytail: the roster is a convenience index; a write failure must not crash the gate.
|
||||
}
|
||||
}
|
||||
|
||||
private static var defaultDirectory: String {
|
||||
("~/Library/Application Support/Museion" as NSString).expandingTildeInPath
|
||||
}
|
||||
|
||||
private static func rosterURL(_ directory: String?) -> URL {
|
||||
URL(fileURLWithPath: directory ?? defaultDirectory).appendingPathComponent("sessions.json")
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the
|
||||
/// pane opens its first session and stays alive for the app's life (map
|
||||
/// decision: child lifecycle).
|
||||
/// decision: child lifecycle). The engine bridge is session-agnostic —
|
||||
/// session ids live in the roster (#28), the phase only says the engine is up.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class MentorSessionModel {
|
||||
enum Phase: Equatable {
|
||||
case idle
|
||||
case starting
|
||||
case ready(sessionId: String)
|
||||
case ready
|
||||
case crashed(lastPrompt: String?)
|
||||
|
||||
var isReady: Bool {
|
||||
@@ -70,16 +124,49 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session transcript state (#28) — the model used to hold ONE
|
||||
/// session's rows and streaming buffers; now keyed by sessionId. The
|
||||
/// active session's entries surface through the same-named proxies below.
|
||||
private struct SessionTranscript {
|
||||
var rows: [SessionRow] = []
|
||||
var streamingText = ""
|
||||
var streamingThought = ""
|
||||
}
|
||||
|
||||
private(set) var phase: Phase = .idle
|
||||
/// True while a turn streams — the Stop button's target.
|
||||
/// True while a turn streams — the Stop button's target. One engine
|
||||
/// child, so at most one turn streams at a time across all sessions.
|
||||
private(set) var isStreaming = false
|
||||
private(set) var rows: [SessionRow] = []
|
||||
/// Streaming buffer for the in-flight agent message; flushed to a row on completion.
|
||||
private(set) var streamingText = ""
|
||||
/// The roster, newest-first (#28). Persisted via SessionRoster.
|
||||
private(set) var roster: [SessionEntry] = []
|
||||
/// The session the pane reads and new prompts target (#28).
|
||||
private(set) var activeEntry: SessionEntry?
|
||||
|
||||
/// The ACTIVE session's transcript — the same-named pane surface over
|
||||
/// the per-session store (#28). MentorPaneView and every existing test
|
||||
/// keep reading these untouched.
|
||||
var rows: [SessionRow] {
|
||||
activeTranscript?.rows ?? []
|
||||
}
|
||||
|
||||
/// Streaming buffer for the in-flight agent message of the ACTIVE
|
||||
/// session; flushed to a row on completion.
|
||||
var streamingText: String {
|
||||
activeTranscript?.streamingText ?? ""
|
||||
}
|
||||
|
||||
/// #24 fix: streaming buffer for the engine's THINKING — kept out of the
|
||||
/// critique stream. A pass runs to hundreds of thought lines; conflating
|
||||
/// them with `agent_message_chunk` made the transcript one giant blob.
|
||||
private(set) var streamingThought = ""
|
||||
var streamingThought: String {
|
||||
activeTranscript?.streamingThought ?? ""
|
||||
}
|
||||
|
||||
/// A new session may start: engine up, no turn in flight (#28).
|
||||
var canStartSession: Bool {
|
||||
phase.isReady && !isStreaming
|
||||
}
|
||||
|
||||
/// Advisory engine-version verdict (map decision: advisory, never blocks).
|
||||
private(set) var versionNote: String?
|
||||
/// The running engine's version, from the initialize handshake (always visible).
|
||||
@@ -87,8 +174,16 @@ final class MentorSessionModel {
|
||||
/// Last stderr lines from the engine — the restart prompt's technical details.
|
||||
private(set) var stderrTail: [String] = []
|
||||
|
||||
private var transcripts: [String: SessionTranscript] = [:]
|
||||
/// While a session/load is in flight, its replayed updates render as rows
|
||||
/// instead of feeding the streaming buffers (#28).
|
||||
private var replayingSessionId: String?
|
||||
/// The resolved roster directory (nil = SessionRoster's default). Under
|
||||
/// hosted tests a unique temp dir keeps suites off the real roster
|
||||
/// (ponytail: redirect here instead of making every rig inject a directory).
|
||||
private let rosterDirectory: String?
|
||||
|
||||
private var client: ACPEngineClient?
|
||||
private var sessionId: String?
|
||||
private var lastPrompt: String?
|
||||
|
||||
/// The gate's winning binary path (no re-probe — map decision). Set by the
|
||||
@@ -100,8 +195,20 @@ final class MentorSessionModel {
|
||||
/// The gate's recorded engine version (state.json) — injectable for tests.
|
||||
var recordedVersionProvider: () -> String? = { EngineProbe.readStateRecord()?.engineVersion }
|
||||
|
||||
init(binaryPath: String? = nil) {
|
||||
init(binaryPath: String? = nil, rosterDirectory: String? = nil) {
|
||||
self.binaryPath = binaryPath
|
||||
if let rosterDirectory {
|
||||
self.rosterDirectory = rosterDirectory
|
||||
} else if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
|
||||
self.rosterDirectory = NSTemporaryDirectory() + "museion-roster-\(UUID().uuidString)"
|
||||
} else {
|
||||
self.rosterDirectory = nil
|
||||
}
|
||||
roster = SessionRoster.load(directory: self.rosterDirectory)
|
||||
}
|
||||
|
||||
private var activeTranscript: SessionTranscript? {
|
||||
activeEntry.flatMap { transcripts[$0.sessionId] }
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -109,6 +216,12 @@ final class MentorSessionModel {
|
||||
shutdownClientDirectly()
|
||||
}
|
||||
|
||||
/// The engine child's pid — internal observation surface for the
|
||||
/// finish-audit restart pin (kills the child to drive a real crash).
|
||||
var childProcessIdentifier: pid_t? {
|
||||
client?.childProcessIdentifier
|
||||
}
|
||||
|
||||
/// App-quit teardown (#14): close the engine child cleanly. Idempotent.
|
||||
func shutdown() {
|
||||
shutdownClientDirectly()
|
||||
@@ -128,25 +241,34 @@ final class MentorSessionModel {
|
||||
/// wherever `client` is assigned.
|
||||
private nonisolated(unsafe) var clientRef: ACPEngineClient?
|
||||
|
||||
/// Lazy spawn on first session open. Idempotent per lifecycle.
|
||||
/// Lazy spawn on first session open. Idempotent per lifecycle. Ensures
|
||||
/// ONE session exists: the default freeform 'Mentor' session on first
|
||||
/// open, otherwise the newest rostered entry activated with a FRESH
|
||||
/// transcript — history is engine-owned and comes back on resume (#28).
|
||||
func openSession() async {
|
||||
guard phase == .idle else { return }
|
||||
phase = .starting
|
||||
await startEngine()
|
||||
guard case .starting = phase else { return } // startEngine crashed instead
|
||||
await ensureDefaultSession()
|
||||
}
|
||||
|
||||
/// Restart after a crash — keeps the transcript (never data loss) and
|
||||
/// Restart after a crash — re-spawns the engine and REPLAYS every
|
||||
/// transcript from it (ADR-0007: the engine owns the words), and
|
||||
/// remembers the last prompt so the writer can resend it.
|
||||
func restart() async {
|
||||
guard case .crashed = phase else { return }
|
||||
client?.close()
|
||||
client = nil
|
||||
clientRef = nil
|
||||
sessionId = nil
|
||||
streamingText = ""
|
||||
streamingThought = ""
|
||||
for sid in transcripts.keys {
|
||||
transcripts[sid]?.streamingText = ""
|
||||
transcripts[sid]?.streamingThought = ""
|
||||
}
|
||||
phase = .starting
|
||||
await startEngine()
|
||||
guard case .starting = phase else { return }
|
||||
await ensureDefaultSession()
|
||||
}
|
||||
|
||||
private func startEngine() async {
|
||||
@@ -158,19 +280,24 @@ final class MentorSessionModel {
|
||||
let client = ACPEngineClient(binaryPath: binaryPath)
|
||||
self.client = client
|
||||
clientRef = client
|
||||
// All three hops ride DispatchQueue.main.async, NOT Task { @MainActor }:
|
||||
// a Task must first win cooperative-pool time, which hundreds of
|
||||
// parallel jobs can starve for seconds (#28 test finding); the main
|
||||
// queue is FIFO with the continuation resume, so wire order — replay
|
||||
// updates before the load response — is guaranteed, not probable.
|
||||
client.onCrash = { [weak self] in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleCrash()
|
||||
}
|
||||
}
|
||||
client.onStderrLine = { [weak self] line in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.appendStderr(line)
|
||||
}
|
||||
}
|
||||
do {
|
||||
try client.start { [weak self] method, params in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleNotification(method: method, params: params)
|
||||
}
|
||||
}
|
||||
@@ -188,7 +315,8 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// initialize + session/new (map decisions: advisory version verify; cwd ~).
|
||||
/// initialize (map decisions: advisory version verify). Sessions are
|
||||
/// created separately (#28) — the bridge is session-agnostic.
|
||||
private func handshake(_ client: ACPEngineClient) async throws {
|
||||
let params: JSONValue = .object([
|
||||
"protocolVersion": .number(1),
|
||||
@@ -218,35 +346,233 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
versionNote = note
|
||||
|
||||
// New session — cwd ~ (map decision). Adapter ≥0.21.5 requires mcpServers
|
||||
// (ACP SDK NewSessionRequest); Museion ships none, so the honest empty list.
|
||||
let newResult = try await client.request(
|
||||
"session/new",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
|
||||
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
|
||||
}
|
||||
sessionId = sid
|
||||
phase = .ready(sessionId: sid)
|
||||
}
|
||||
|
||||
/// Send a prompt and stream the reply. Appends the user row first — a
|
||||
/// non-nil `label` renders verbatim INSTEAD of the raw prompt (pass prompts
|
||||
/// are long wire stubs that must not land in the transcript); the
|
||||
/// stop_reason response ends the turn (refusal maps to a plain note —
|
||||
/// wire-verified edge semantics). Returns how the turn ended (#24 seam):
|
||||
/// a pass advances only on a completed turn, never on cancel/crash.
|
||||
/// session/prompt's response arrives only when the TURN ends — a pass
|
||||
/// legitimately runs minutes of tool work between prompt and stop reason.
|
||||
/// The client's 15 s request default would abandon the wait mid-stream
|
||||
/// (observed live, #23 dogfood: "connection lost" while the engine kept
|
||||
/// working, Stop vanished with isStreaming). Long-but-finite so a truly
|
||||
/// stuck engine still surfaces; Stop is the live-turn exit.
|
||||
/// After an engine start: exactly one active session (#28). The newest
|
||||
/// rostered entry activates and RESUMES — session/load replays its
|
||||
/// history (user turns included), so prompt/fork/compact never run
|
||||
/// against unloaded state; a first open creates the default freeform
|
||||
/// 'Mentor' session.
|
||||
private func ensureDefaultSession() async {
|
||||
if let newest = roster.first {
|
||||
activate(newest)
|
||||
// The resume REPLAYS, unconditionally (finish-audit): the deleted
|
||||
// rows.isEmpty skip was dead — activate() resets the store one
|
||||
// line above it — and restart()'s kept rows are intentionally
|
||||
// replaced by the engine's replay (ADR-0007: the engine owns the
|
||||
// words; a diverging local copy would lie). An engine-unknown id
|
||||
// lands the honest refusal row; the entry stays rostered.
|
||||
_ = await resumeSession(newest)
|
||||
return
|
||||
}
|
||||
if await createSession(name: "Mentor", pieceTitle: nil) == nil {
|
||||
phase = .crashed(lastPrompt: nil)
|
||||
stderrTail = ["no session — the engine refused session/new"]
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh freeform session (#28): wire session/new, roster it
|
||||
/// newest-first, activate. Nil when the engine isn't ready or refuses.
|
||||
@discardableResult
|
||||
func newSession(name: String, pieceTitle: String?) async -> SessionEntry? {
|
||||
guard phase.isReady, client != nil else { return nil }
|
||||
return await createSession(name: name, pieceTitle: pieceTitle)
|
||||
}
|
||||
|
||||
/// The pass's own session (#28): wire session/new + roster
|
||||
/// 'Pass N · <title>' + activate, so the pass prompt streams into ITS
|
||||
/// transcript. Nil when the engine isn't ready or refuses.
|
||||
@discardableResult
|
||||
func beginPassSession(kind: PassKind, pieceTitle: String) async -> SessionEntry? {
|
||||
guard phase.isReady, client != nil else { return nil }
|
||||
return await createSession(name: "\(kind.rawValue) · \(pieceTitle)", pieceTitle: pieceTitle)
|
||||
}
|
||||
|
||||
/// The shared creation rail behind newSession/beginPassSession.
|
||||
private func createSession(name: String, pieceTitle: String?) async -> SessionEntry? {
|
||||
// Finish-audit backstop: fork guards !isStreaming; the views disable
|
||||
// these controls mid-turn. A programmatic caller must not switch the
|
||||
// active session out from under a live turn — Stop would then cancel
|
||||
// the wrong session.
|
||||
guard !isStreaming else {
|
||||
appendRow(.text("Session refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
guard let client else { return nil }
|
||||
do {
|
||||
// Adapter ≥0.21.5 requires mcpServers on every session/new (#44
|
||||
// invariant); Museion ships none, so the honest empty list.
|
||||
let result = try await client.request(
|
||||
"session/new",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
// #28 review fix: a refused session speaks like its siblings —
|
||||
// resume/fork append honest rows; New Session must never be a
|
||||
// silent nil. (Nothing active yet → the row drops; the crash
|
||||
// posture owns that path in ensureDefaultSession.)
|
||||
appendRow(.text("Session refused — the engine returned no id."), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date())
|
||||
roster.insert(entry, at: 0)
|
||||
transcripts[sid] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
saveRoster()
|
||||
return entry
|
||||
} catch {
|
||||
appendRow(.text("Session refused — \(error.localizedDescription)"), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume a rostered session (#28): session/load, the engine replays its
|
||||
/// history into the transcript (user turns included), Museion owns none
|
||||
/// of it. A session the engine does NOT know returns false honestly —
|
||||
/// the entry stays and an explanatory row lands; never a fabricated
|
||||
/// empty session.
|
||||
func resumeSession(_ entry: SessionEntry) async -> Bool {
|
||||
guard phase.isReady, let client else { return false }
|
||||
guard !isStreaming else {
|
||||
// "Not now" refusals target the ACTIVE session — they are about
|
||||
// the writer's action right now, not the entry's state.
|
||||
appendRow(.text("Resume refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
|
||||
return false
|
||||
}
|
||||
guard replayingSessionId == nil else {
|
||||
// Finish-audit (converged, 3 reviewers): one replay slot — a
|
||||
// second session/load in flight would divert the first's replayed
|
||||
// chunks into live streaming buffers. Refuse; the winner's
|
||||
// completion frees the slot and the next click just works.
|
||||
appendRow(.text("Resume refused — another session is loading."), to: activeEntry?.sessionId)
|
||||
return false
|
||||
}
|
||||
do {
|
||||
// Replay fills this fresh store; a failed resume leaves nothing fabricated.
|
||||
transcripts[entry.sessionId] = SessionTranscript()
|
||||
replayingSessionId = entry.sessionId
|
||||
// Replay ordering: the adapter writes the history notifications
|
||||
// BEFORE the load response, and the MainActor Task pipeline
|
||||
// preserves that order — same reliance as live streaming.
|
||||
let result = try await client.request(
|
||||
"session/load",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"sessionId": .string(entry.sessionId),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
// Finish-audit: the adapter replays the FULL history before
|
||||
// responding — #23's exact shape (response arrives when the
|
||||
// work ends). The client's 15 s default would abort a long
|
||||
// session's resume mid-replay.
|
||||
timeout: Self.promptTimeout,
|
||||
)
|
||||
replayingSessionId = nil
|
||||
// null/absent (or empty) sessionId in the result = the engine does not know it.
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
// The refusal belongs to the ENTRY — attributed, and visible
|
||||
// on its next row click (the store is kept, not discarded).
|
||||
appendRow(
|
||||
.text("The engine does not know “\(entry.name)” — its history is no longer on the engine."),
|
||||
to: entry.sessionId,
|
||||
)
|
||||
return false
|
||||
}
|
||||
// Activate WITHOUT resetting the transcript — activate() is for
|
||||
// fresh-transcript activations; the replay already filled this one.
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
return true
|
||||
} catch {
|
||||
replayingSessionId = nil
|
||||
// Partial replay rows (if any) + the failure row stay in the
|
||||
// ENTRY's store — attributed, visible on its next row click.
|
||||
appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Fork the active session (#28): the engine copies its history to a NEW
|
||||
/// sessionId (session/fork); Museion rosters '<name> (fork)' with the
|
||||
/// same pieceTitle and activates it with a FRESH transcript — the
|
||||
/// original entry and transcript stay untouched. An empty-string
|
||||
/// sessionId from the wire is a refusal (honest row, nil return).
|
||||
@discardableResult
|
||||
func forkActiveSession() async -> SessionEntry? {
|
||||
guard phase.isReady, let client, let source = activeEntry, !isStreaming else { return nil }
|
||||
do {
|
||||
let result = try await client.request(
|
||||
"session/fork",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"sessionId": .string(source.sessionId),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
appendRow(.text("Fork refused — the engine returned no new session."), to: source.sessionId)
|
||||
return nil
|
||||
}
|
||||
let entry = SessionEntry(
|
||||
sessionId: sid,
|
||||
name: "\(source.name) (fork)",
|
||||
pieceTitle: source.pieceTitle,
|
||||
createdAt: Date(),
|
||||
)
|
||||
roster.insert(entry, at: 0)
|
||||
transcripts[sid] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
saveRoster()
|
||||
return entry
|
||||
} catch {
|
||||
appendRow(.text("Fork failed — \(error.localizedDescription)"), to: source.sessionId)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Compact the active idle session (#28): the engine's /compress dispatch
|
||||
/// rides the existing prompt rail; the label keeps the raw slash command
|
||||
/// out of the transcript and the summary streams back as ordinary chunks.
|
||||
/// Refused while a turn streams (idle-only engine-side, too).
|
||||
func compactActiveSession() async {
|
||||
guard canStartSession, activeEntry != nil else { return }
|
||||
_ = await sendPrompt("/compress", label: "Compact…")
|
||||
}
|
||||
|
||||
/// Read-only transcript of ANY rostered session (#28) — the Sessions pane
|
||||
/// and tests read without activating.
|
||||
func transcriptRows(of entry: SessionEntry) -> [SessionRow] {
|
||||
transcripts[entry.sessionId]?.rows ?? []
|
||||
}
|
||||
|
||||
private func activate(_ entry: SessionEntry) {
|
||||
transcripts[entry.sessionId] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
}
|
||||
|
||||
private func saveRoster() {
|
||||
SessionRoster.save(roster, directory: rosterDirectory)
|
||||
}
|
||||
|
||||
/// Send a prompt and stream the reply into the ACTIVE session's
|
||||
/// transcript. Appends the user row first — a non-nil `label` renders
|
||||
/// verbatim INSTEAD of the raw prompt (pass prompts are long wire stubs
|
||||
/// that must not land in the transcript); the stop_reason response ends
|
||||
/// the turn (refusal maps to a plain note — wire-verified edge
|
||||
/// semantics). Returns how the turn ended (#24 seam): a pass advances
|
||||
/// only on a completed turn, never on cancel/crash. session/prompt's
|
||||
/// response arrives only when the TURN ends — a pass legitimately runs
|
||||
/// minutes of tool work between prompt and stop reason. The client's
|
||||
/// 15 s request default would abandon the wait mid-stream (observed
|
||||
/// live, #23 dogfood: "connection lost" while the engine kept working,
|
||||
/// Stop vanished with isStreaming). Long-but-finite so a truly stuck
|
||||
/// engine still surfaces; Stop is the live-turn exit.
|
||||
nonisolated static let promptTimeout: TimeInterval = 1800
|
||||
|
||||
@discardableResult
|
||||
@@ -255,20 +581,22 @@ final class MentorSessionModel {
|
||||
// Guard refusal: the turn never ran — .failed is the closest of the
|
||||
// three buckets (the seam has no "never started" case; callers that
|
||||
// check phase before prompting never land here).
|
||||
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return .failed }
|
||||
guard !prompt.isEmpty, phase.isReady, !isStreaming, let sid = activeEntry?.sessionId else {
|
||||
return .failed
|
||||
}
|
||||
lastPrompt = prompt
|
||||
rows.append(SessionRow(content: .text(label ?? "You: \(prompt)")))
|
||||
appendRow(.text(label ?? "You: \(prompt)"), to: sid)
|
||||
isStreaming = true
|
||||
defer {
|
||||
// Flush the thinking first (it preceded the message), collapsed.
|
||||
if !streamingThought.isEmpty {
|
||||
rows.append(SessionRow(content: .thought(streamingThought)))
|
||||
streamingThought = ""
|
||||
if let pending = transcripts[sid], !pending.streamingThought.isEmpty {
|
||||
appendRow(.thought(pending.streamingThought), to: sid)
|
||||
transcripts[sid]?.streamingThought = ""
|
||||
}
|
||||
// Flush any streamed-but-unfinished agent text into a row.
|
||||
if !streamingText.isEmpty {
|
||||
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
|
||||
streamingText = ""
|
||||
if let pending = transcripts[sid], !pending.streamingText.isEmpty {
|
||||
appendRow(.text("Mentor: \(pending.streamingText)"), to: sid)
|
||||
transcripts[sid]?.streamingText = ""
|
||||
}
|
||||
isStreaming = false
|
||||
}
|
||||
@@ -290,7 +618,7 @@ final class MentorSessionModel {
|
||||
// must not advance on a maybe (review: empty-stopReason bug).
|
||||
guard !stopReason.isEmpty else { return .failed }
|
||||
if stopReason == "refusal" {
|
||||
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
|
||||
appendRow(.text("Mentor: (refused the prompt)"), to: sid)
|
||||
}
|
||||
if stopReason == "cancelled" {
|
||||
return .cancelled
|
||||
@@ -302,7 +630,7 @@ final class MentorSessionModel {
|
||||
if case .crashed = phase {
|
||||
// Crash card already owns the failure surface.
|
||||
} else {
|
||||
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
|
||||
appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: sid)
|
||||
}
|
||||
return .failed
|
||||
}
|
||||
@@ -312,10 +640,22 @@ final class MentorSessionModel {
|
||||
/// session/cancel, a notification — no response expected). The engine
|
||||
/// ends the turn (PromptResponse) as its acknowledgement.
|
||||
func stopStreaming() {
|
||||
guard isStreaming, let sid = sessionId else { return }
|
||||
guard isStreaming, let sid = activeEntry?.sessionId else { return }
|
||||
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
|
||||
}
|
||||
|
||||
/// Base version of a version string — the part before `+` build metadata
|
||||
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
|
||||
nonisolated static func baseVersion(of version: String) -> String {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Crash, stderr, and notification decoding (same-file extension —
|
||||
|
||||
// the class body keeps lifecycle + turn operations)
|
||||
|
||||
extension MentorSessionModel {
|
||||
private func handleCrash() {
|
||||
guard case .ready = phase else {
|
||||
// A crash during startup also lands in the restart prompt.
|
||||
@@ -334,53 +674,70 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Base version of a version string — the part before `+` build metadata
|
||||
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
|
||||
nonisolated static func baseVersion(of version: String) -> String {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
|
||||
// MARK: - Notification decoding
|
||||
|
||||
/// Route by the session id FROM THE PARAMS (#28) — a replay for a
|
||||
/// background session lands in ITS transcript, never the active one's.
|
||||
private func handleNotification(method: String, params: JSONValue?) {
|
||||
guard method == "session/update",
|
||||
let params,
|
||||
let sessionId = params.objectValue?["sessionId"]?.stringValue,
|
||||
sessionId == self.sessionId else { return }
|
||||
let sid = params.objectValue?["sessionId"]?.stringValue,
|
||||
transcripts[sid] != nil else { return }
|
||||
guard let update = params.objectValue?["update"]?.objectValue else { return }
|
||||
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
|
||||
let replaying = sid == replayingSessionId
|
||||
switch kind {
|
||||
case "agent_message_chunk":
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
streamingText += text
|
||||
if replaying {
|
||||
// ponytail: one row per replayed chunk — a chunked engine message
|
||||
// renders as several rows; wire order stays faithful. Coalesce
|
||||
// only if a real adapter chunks replayed turns.
|
||||
appendRow(.text("Mentor: \(text)"), to: sid)
|
||||
} else {
|
||||
transcripts[sid]?.streamingText += text
|
||||
}
|
||||
case "agent_thought_chunk":
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
streamingThought += text
|
||||
if replaying {
|
||||
appendRow(.thought(text), to: sid)
|
||||
} else {
|
||||
transcripts[sid]?.streamingThought += text
|
||||
}
|
||||
case "user_message_chunk":
|
||||
// The engine echoes the user message; we already rendered it.
|
||||
break
|
||||
// Live: the engine echoes the user message; the label row already
|
||||
// rendered. During replay there IS no rendered row — the engine
|
||||
// owns the turn, so it renders (#28: user turns included).
|
||||
if replaying {
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
appendRow(.text("You: \(text)"), to: sid)
|
||||
}
|
||||
case "tool_call":
|
||||
appendToolCall(update)
|
||||
appendToolCall(update, to: sid)
|
||||
default:
|
||||
// Every other update type: collapsible raw-JSON row (map decision).
|
||||
let object = params.objectValue?.mapValues { $0.any } ?? [:]
|
||||
let json = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data()
|
||||
rows.append(SessionRow(content: .raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? "")))
|
||||
appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool-call decoding — the fix-card rail (ADR-0006): a tool call whose
|
||||
/// `rawInput` decodes to fix-card fields renders as a card; any other tool
|
||||
/// call renders as a raw row.
|
||||
private func appendToolCall(_ update: [String: JSONValue]) {
|
||||
private func appendToolCall(_ update: [String: JSONValue], to sid: String) {
|
||||
let title = update["title"]?.stringValue ?? "tool call"
|
||||
let rawInput = update["rawInput"]
|
||||
if let card = FixCard(rawInput: rawInput) {
|
||||
rows.append(SessionRow(content: .fixCard(card)))
|
||||
appendRow(.fixCard(card), to: sid)
|
||||
return
|
||||
}
|
||||
let json = (try? JSONSerialization.data(withJSONObject: rawInput?.any ?? [:], options: [.sortedKeys])) ?? Data()
|
||||
rows.append(SessionRow(content: .raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? "")))
|
||||
appendRow(.raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
|
||||
}
|
||||
|
||||
/// Append one row to a session's transcript; nil targets the ACTIVE one.
|
||||
private func appendRow(_ content: SessionRow.Content, to sid: String?) {
|
||||
guard let sid else { return }
|
||||
transcripts[sid, default: SessionTranscript()].rows.append(SessionRow(content: content))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -821,6 +821,29 @@ extension PostsModel {
|
||||
lastError = error.localizedDescription
|
||||
return
|
||||
}
|
||||
// #28 (S2.3): every pass auto-creates its own session — rostered
|
||||
// 'Pass N · <title>' and activated, so the pass streams into ITS
|
||||
// transcript. The existing ready-guard above stays the refusal pin.
|
||||
let passSession = await mentor.beginPassSession(kind: kind, pieceTitle: title(of: id))
|
||||
guard passSession != nil else {
|
||||
lastError = "The mentor engine refused a session for the pass."
|
||||
return
|
||||
}
|
||||
// Finish-audit: the beginPassSession await above is these guards'
|
||||
// first suspension — a second Run Pass landing inside it re-passed
|
||||
// every guard (both flags still unset) and minted a second pass
|
||||
// session. Re-check ownership here, before the flag goes live; the
|
||||
// sub-ms window where BOTH awaits are still in flight self-contains
|
||||
// via sendPrompt's isStreaming refusal (one orphan roster entry,
|
||||
// never a double stream — ponytail ceiling).
|
||||
guard runningPass == nil else {
|
||||
lastError = "A pass is already running."
|
||||
return
|
||||
}
|
||||
// runningPass goes live only AFTER the session awaits are done: from
|
||||
// here to sendPrompt's isStreaming there is no suspension, so anything
|
||||
// observing runningPass (the pass bar, the #124 Cancel pin) can rely
|
||||
// on Stop being able to cancel the live turn.
|
||||
runningPass = kind
|
||||
defer { runningPass = nil }
|
||||
let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//
|
||||
// SessionTranscriptView.swift
|
||||
// Museion
|
||||
//
|
||||
// #28 (S2.3): the shared session transcript, extracted from MentorPaneView —
|
||||
// one renderer for the ACTIVE session's rows + streaming buffers. The
|
||||
// Mentor pane passes its debug toggle; the Sessions pane reads the writing
|
||||
// voice.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// The shared session transcript — the ACTIVE session's rows + streaming
|
||||
/// buffers, extracted from MentorPaneView in #28 so the Sessions pane reads
|
||||
/// the same surface. Writing voice: pass `showsDebugRows: false` (the debug
|
||||
/// toggle stays the Mentor pane's).
|
||||
struct SessionTranscriptView: View {
|
||||
let model: MentorSessionModel
|
||||
/// Raw session/tool rows, collapsed thinking, and live thinking render
|
||||
/// only when on — the model keeps every row either way.
|
||||
var showsDebugRows = false
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 10) {
|
||||
ForEach(model.rows.filter { showsDebugRows || Self.isWritingRow($0) }) { row in
|
||||
rowView(row)
|
||||
}
|
||||
if showsDebugRows, !model.streamingThought.isEmpty {
|
||||
// Live thinking: quiet, capped — it's transient (the full
|
||||
// text lands in a collapsed row when the turn ends).
|
||||
Text(model.streamingThought)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(3)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
if !model.streamingText.isEmpty {
|
||||
textRow("Mentor: \(model.streamingText)")
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
// #24 fix: programmatic scrollTo raced the growing lazy rows and
|
||||
// mislanded at the TOP; the native bottom anchor needs no scroll code.
|
||||
.defaultScrollAnchor(.bottom)
|
||||
}
|
||||
|
||||
/// The writing-session filter: prose + card events stay; raw rows and
|
||||
/// thinking are debug-only. Static, nonisolated — pure, testable from
|
||||
/// any context.
|
||||
nonisolated static func isWritingRow(_ row: SessionRow) -> Bool {
|
||||
switch row.content {
|
||||
case .text, .fixCard: true
|
||||
case .thought, .raw: false
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func rowView(_ row: SessionRow) -> some View {
|
||||
switch row.content {
|
||||
case let .text(text):
|
||||
textRow(text)
|
||||
case let .thought(text):
|
||||
ThoughtRow(text: text)
|
||||
case let .fixCard(card):
|
||||
// #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 .raw(kind, json):
|
||||
RawUpdateRow(kind: kind, json: json)
|
||||
}
|
||||
}
|
||||
|
||||
private func textRow(_ text: String) -> some View {
|
||||
Text(text)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
/// The tool-call EVENT, not the card: the pattern title alone. The
|
||||
/// card's full statement lives in the Fix Cards palette window.
|
||||
private struct FixCardEventRow: View {
|
||||
let pattern: String
|
||||
|
||||
var body: some View {
|
||||
Label(pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
/// #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 {
|
||||
let text: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(text)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text("thinking")
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RawUpdateRow: View {
|
||||
let kind: String
|
||||
let json: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(json)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text(kind)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
SessionsPaneView(model: MentorSessionModel(), posts: nil, binaryPath: nil)
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
//
|
||||
// SessionsPaneView.swift
|
||||
// Museion
|
||||
//
|
||||
// #28 (S2.3): the Sessions pane — the roster (newest-first) + the active
|
||||
// session's transcript, with New/Resume/Fork/Compact/Cancel over
|
||||
// MentorSessionModel. Also hosts the shared session transcript extracted
|
||||
// from MentorPaneView (one renderer, two panes; writing voice here, debug
|
||||
// toggle there).
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// The Sessions rail destination: two-column body like Posts — roster list
|
||||
/// (library width) + transcript. Selecting a row resumes that session; the
|
||||
/// engine owns the words, so a fresh activation replays its history.
|
||||
struct SessionsPaneView: View {
|
||||
var model: MentorSessionModel
|
||||
/// The open piece is the New Session control's association target.
|
||||
var posts: PostsModel?
|
||||
/// The gate's winning binary (no re-probe) — this pane can be the first
|
||||
/// to open the engine.
|
||||
var binaryPath: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
PaneHeader(title: "Sessions") {
|
||||
newSessionControl
|
||||
}
|
||||
if model.roster.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
HStack(spacing: 0) {
|
||||
rosterList
|
||||
.frame(width: DesignTokens.libraryWidth)
|
||||
paneBorder
|
||||
sessionDetail
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(DesignTokens.background)
|
||||
// Same lazy lifecycle as MentorPaneView: idempotent open — whichever
|
||||
// surface the writer reaches first spawns the engine.
|
||||
.task {
|
||||
if let binaryPath {
|
||||
model.binaryPath = binaryPath
|
||||
}
|
||||
// Hosted unit tests run this app as their runner — never spawn a
|
||||
// real engine child there.
|
||||
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
|
||||
await model.openSession()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Roster list
|
||||
|
||||
private var rosterList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
ForEach(model.roster) { entry in
|
||||
SessionEntryRow(entry: entry, selected: entry.id == model.activeEntry?.id) {
|
||||
// Resume = activate: the engine replays the history
|
||||
// into the fresh transcript; unknown sessions land
|
||||
// the model's honest refusal row and stay rostered.
|
||||
Task { await model.resumeSession(entry) }
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
}
|
||||
|
||||
private var paneBorder: some View {
|
||||
Rectangle()
|
||||
.fill(DesignTokens.border)
|
||||
.frame(width: 1)
|
||||
}
|
||||
|
||||
// MARK: Detail column
|
||||
|
||||
@ViewBuilder
|
||||
private var sessionDetail: some View {
|
||||
switch model.phase {
|
||||
case .idle, .starting:
|
||||
ProgressView("Starting the mentor engine…")
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
case .crashed:
|
||||
crashedNote
|
||||
case .ready:
|
||||
VStack(spacing: 0) {
|
||||
actionsRow
|
||||
Divider()
|
||||
if model.isStreaming {
|
||||
livenessRow
|
||||
Divider()
|
||||
}
|
||||
SessionTranscriptView(model: model, showsDebugRows: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The active session's name + engine version, Fork/Compact beside them
|
||||
/// — disabled while a turn streams (canStartSession).
|
||||
private var actionsRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(model.activeEntry?.name ?? "—")
|
||||
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
if let version = model.engineVersion {
|
||||
Text(version)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(1)
|
||||
.help(model.versionNote ?? version)
|
||||
}
|
||||
Spacer()
|
||||
Button("Fork") {
|
||||
Task { _ = await model.forkActiveSession() }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.disabled(!model.canStartSession)
|
||||
.help("Copy this session's history into a new one")
|
||||
.accessibilityLabel("Fork session")
|
||||
Button("Compact") {
|
||||
Task { await model.compactActiveSession() }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.disabled(!model.canStartSession)
|
||||
.help("Compress the session's history")
|
||||
.accessibilityLabel("Compact session")
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
/// Liveness (the Mentor pane's #23 posture, no input bar here): silent
|
||||
/// tool work must not read as dead, Stop is the pane's Cancel affordance.
|
||||
private var livenessRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
Text("Mentor is working — Stop to interrupt.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
Spacer()
|
||||
Button("Stop") {
|
||||
model.stopStreaming()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.accessibilityLabel("Stop the mentor")
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
/// No second restart flow — the Mentor pane owns Restart (map decision).
|
||||
private var crashedNote: some View {
|
||||
VStack(spacing: 8) {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.font(.system(size: 30))
|
||||
.foregroundStyle(.orange)
|
||||
Text("The mentor engine stopped")
|
||||
.font(.title3)
|
||||
Text("Restart it in the Mentor pane — nothing is lost.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
// MARK: New Session control
|
||||
|
||||
@ViewBuilder
|
||||
private var newSessionControl: some View {
|
||||
if let piece = Self.openPiece(in: posts) {
|
||||
Menu {
|
||||
Button("New Session") { createSession(associatedWith: nil) }
|
||||
Button("New Session on \(piece.title)") { createSession(associatedWith: piece.title) }
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.menuStyle(.button)
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.disabled(!model.canStartSession)
|
||||
.help("New Session")
|
||||
.accessibilityLabel("New Session")
|
||||
} else {
|
||||
Button {
|
||||
createSession(associatedWith: nil)
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.disabled(!model.canStartSession)
|
||||
.help("New Session")
|
||||
.accessibilityLabel("New Session")
|
||||
}
|
||||
}
|
||||
|
||||
private func createSession(associatedWith title: String?) {
|
||||
Task { _ = await model.newSession(name: "New Session", pieceTitle: title) }
|
||||
}
|
||||
|
||||
/// The open piece in Posts — the association target for the New Session
|
||||
/// choice (nil = free-floating only). Static + posts-coupled: test-pinned.
|
||||
static func openPiece(in posts: PostsModel?) -> Post? {
|
||||
guard let posts, let id = posts.session?.postID else { return nil }
|
||||
return posts.posts.first(where: { $0.id == id })
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
VStack(spacing: 8) {
|
||||
Text("No sessions yet.")
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("Sessions arrive when a pass runs — or create one with New Session.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding(38)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
/// One roster row: the library's post-row language — always-2px leading
|
||||
/// strip (accent when selected, no layout shift), surface card + border on
|
||||
/// selection, serif name over mono-11 meta (piece · created).
|
||||
private struct SessionEntryRow: View {
|
||||
let entry: SessionEntry
|
||||
let selected: Bool
|
||||
let select: () -> Void
|
||||
@State private var hover = false
|
||||
|
||||
var body: some View {
|
||||
// Same shape as LibraryPostRow: leading corners square (the 2px
|
||||
// strip), trailing rounded 8 — only the strip's COLOR changes.
|
||||
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
|
||||
return Button(action: select) {
|
||||
HStack(spacing: 0) {
|
||||
Rectangle()
|
||||
.fill(selected ? DesignTokens.accent : .clear)
|
||||
.frame(width: 2)
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text(entry.name)
|
||||
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(metaLine)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.padding(10)
|
||||
}
|
||||
.clipShape(shape)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.foreground)
|
||||
.background {
|
||||
if selected || hover {
|
||||
shape
|
||||
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
|
||||
.overlay(
|
||||
shape.strokeBorder(selected ? DesignTokens.border : .clear),
|
||||
)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.onHover { hover = $0 }
|
||||
.help(entry.name)
|
||||
.accessibilityLabel("\(entry.name), \(entry.pieceTitle ?? "free-floating session")")
|
||||
}
|
||||
|
||||
private var metaLine: String {
|
||||
var parts: [String] = []
|
||||
if let piece = entry.pieceTitle {
|
||||
parts.append(piece)
|
||||
}
|
||||
parts.append(FixCardStore.formatted(entry.createdAt, "yyyy-MM-dd HH:mm"))
|
||||
return parts.joined(separator: " · ")
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,13 @@ struct WorkspaceView: View {
|
||||
availableWidth: geo.size.width - DesignTokens.railWidth,
|
||||
)
|
||||
case .sessions:
|
||||
PlaceholderPane(title: "Sessions", detail: "Session lifecycle arrives with S2.3 (#28).")
|
||||
// #28: the Sessions pane — roster + active transcript over the
|
||||
// app-scoped mentor model, the same reach as Learnings' home.
|
||||
SessionsPaneView(
|
||||
model: gate.mentor,
|
||||
posts: gate.posts,
|
||||
binaryPath: gate.gateModel.currentBinaryPath,
|
||||
)
|
||||
case .learnings:
|
||||
// #26: list-only pane over <home>/learnings/ — read side;
|
||||
// promoting a fix card (the fix-card rail) writes the files.
|
||||
@@ -616,24 +622,3 @@ struct PaneHeader<Trailing: View>: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigation-target placeholder (#17 AC: panes exist as targets; real content
|
||||
/// arrives with their tickets — honest copy, no fake controls).
|
||||
struct PlaceholderPane: View {
|
||||
let title: String
|
||||
let detail: String
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 10) {
|
||||
Image(systemName: "hourglass")
|
||||
.font(.largeTitle)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Text(title)
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
Text(detail)
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,17 @@ import Testing
|
||||
/// session/cancel is answered — any other request waits until teardown;
|
||||
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled"
|
||||
/// with no cancel needed; `refuseOnPrompt` answers stopReason "refusal" (no
|
||||
/// chunks).
|
||||
/// chunks); `loadReplay` (#28) adds the lifecycle wire: session/new/load/fork
|
||||
/// all require `mcpServers` (-32602 without, the #44 invariant), session ids
|
||||
/// are minted uniquely (sess-1, sess-2, …), session/load replays
|
||||
/// user+thought+message chunks for ANY minted sess-* id then answers its id
|
||||
/// (a relaunch default-open resumes the newest rostered entry, #28 review
|
||||
/// fix; any other id answers with NO sessionId = unknown), and session/fork
|
||||
/// of sess-1 returns a fresh F-<n> (any other source id returns ""). load/fork
|
||||
/// log "load <id>" / "fork <id>" to stderr so tests can pin the wire call.
|
||||
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
|
||||
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
|
||||
/// the finish-audit interleaving pin's in-flight observable.
|
||||
/// The mode travels in a file next to the fake (self-locating — race-free
|
||||
/// under parallel suites, same convention as ProfileProvisionerTests).
|
||||
/// The fix-card payload travels base64-encoded so shell quoting can't break.
|
||||
@@ -50,8 +60,10 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
|
||||
card=$(print -- '\(fixCardB64)' | base64 -d)
|
||||
framing='{"jsonrpc":"2.0","id":'
|
||||
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":'
|
||||
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \n escapes of multi-line prompts
|
||||
sessn=0
|
||||
forkn=0
|
||||
mcpcheck='import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")'
|
||||
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \\n escapes of multi-line prompts
|
||||
[[ -z "$line" ]] && continue
|
||||
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
|
||||
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
|
||||
@@ -59,8 +71,18 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
|
||||
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
|
||||
elif [[ "$method" == "session/new" ]]; then
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
|
||||
if [[ "$mode" == "loadReplay" ]]; then # #44 invariant: mcpServers required
|
||||
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
||||
if [[ "$ok" == "0" ]]; then
|
||||
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
sessn=$((sessn+1)) # #28: unique id per new — multi-session rosters need distinct ids
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-'"$sessn"'"}}'
|
||||
elif [[ "$method" == "session/prompt" ]]; then
|
||||
psid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
||||
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$psid"'","update":'
|
||||
if [[ "$mode" == "refuseOnPrompt" ]]; then
|
||||
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
|
||||
continue
|
||||
@@ -93,6 +115,51 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
done
|
||||
fi
|
||||
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
|
||||
elif [[ "$method" == "session/load" ]]; then
|
||||
if [[ "$mode" != loadReplay* ]]; then continue; fi
|
||||
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
||||
if [[ "$ok" == "0" ]]; then
|
||||
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
||||
continue
|
||||
fi
|
||||
lsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
||||
print -u2 -- "load $lsid" # the wire call, visible in model.stderrTail
|
||||
if [[ "$mode" == "loadReplayHold" ]]; then
|
||||
# Finish-audit pin support: park the replay until `load-go` lands
|
||||
# beside the fake; the pre-hold stderr line above is the observable
|
||||
# that the load (and the model's replay slot) is in flight.
|
||||
print -u2 -- "hold-load"
|
||||
while [[ ! -f "${0:h}/load-go" ]]; do sleep 0.05; done
|
||||
fi
|
||||
# Any MINTED id replays: a relaunch default-open resumes the newest
|
||||
# rostered session (review fix), so load answers every id session/new
|
||||
# ever issued, not one planted id.
|
||||
rnot='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$lsid"'","update":'
|
||||
if [[ "$lsid" == sess-* ]]; then
|
||||
# Full history replay, wire order, BEFORE the load response — the
|
||||
# real adapter's contract (#28).
|
||||
echo $rnot'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"earlier ask"}}}}'
|
||||
echo $rnot'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"old thinking"}}}}'
|
||||
echo $rnot'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier verdict"}}}}'
|
||||
echo $framing"$rid",'"result":{"sessionId":"'"$lsid"'"}}'
|
||||
else
|
||||
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
|
||||
fi
|
||||
elif [[ "$method" == "session/fork" ]]; then
|
||||
if [[ "$mode" != "loadReplay" ]]; then continue; fi
|
||||
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
||||
if [[ "$ok" == "0" ]]; then
|
||||
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
||||
continue
|
||||
fi
|
||||
fsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
||||
print -u2 -- "fork $fsid"
|
||||
if [[ "$fsid" == "sess-1" ]]; then
|
||||
forkn=$((forkn+1))
|
||||
echo $framing"$rid",'"result":{"sessionId":"F-'"$forkn"'"}}'
|
||||
else
|
||||
echo $framing"$rid",'"result":{"sessionId":""}}' # empty = fork refused
|
||||
fi
|
||||
elif [[ "$method" == "session/cancel" ]]; then
|
||||
print -u2 -- "cancel received"
|
||||
fi
|
||||
@@ -308,12 +375,12 @@ struct ACPClientTests {
|
||||
/// #23 dogfood: the writing-session filter — prose + card events stay,
|
||||
/// raw session/tool rows and thinking are debug-only.
|
||||
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
|
||||
#expect(MentorPaneView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
|
||||
#expect(MentorPaneView.isWritingRow(SessionRow(content: .fixCard(
|
||||
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
|
||||
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .fixCard(
|
||||
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
|
||||
))))
|
||||
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .thought("thinking…"))))
|
||||
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
|
||||
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .thought("thinking…"))))
|
||||
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -389,24 +456,32 @@ struct ACPClientTests {
|
||||
|
||||
// MARK: - Model tests
|
||||
|
||||
@MainActor
|
||||
@Test func `model handshake renders version and streams fix card`() async {
|
||||
@Test @MainActor func `model handshake renders version and streams fix card`() async throws {
|
||||
let fake = makeFakeACP(at: acpTempDir("model"))
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
defer { model.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
|
||||
await model.openSession()
|
||||
guard case let .ready(sessionId) = model.phase else {
|
||||
guard case .ready = model.phase else {
|
||||
Issue.record("expected ready, got \(model.phase)")
|
||||
return
|
||||
}
|
||||
#expect(sessionId == "sess-1")
|
||||
#expect(model.activeEntry?.sessionId == "sess-1")
|
||||
#expect(model.engineVersion == "9.9.9")
|
||||
await model.sendPrompt("hello mentor")
|
||||
let hasCard = model.rows.contains { row in
|
||||
if case let .fixCard(card) = row.content {
|
||||
return card.pattern == "Blame tense"
|
||||
// The card row lands via a client notification Task that can settle just
|
||||
// after the response resumes this test under full-suite load — bounded
|
||||
// settle (house poll pattern); the pin itself is unchanged.
|
||||
var hasCard = false
|
||||
for _ in 0 ..< 250 where !hasCard {
|
||||
hasCard = model.rows.contains { row in
|
||||
if case let .fixCard(card) = row.content {
|
||||
return card.pattern == "Blame tense"
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !hasCard {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
return false
|
||||
}
|
||||
#expect(hasCard)
|
||||
let hasText = model.rows.contains { row in
|
||||
@@ -464,11 +539,11 @@ struct ACPClientTests {
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
defer { model.shutdown() }
|
||||
await model.openSession()
|
||||
guard case let .ready(sessionId) = model.phase else {
|
||||
guard case .ready = model.phase else {
|
||||
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
|
||||
return
|
||||
}
|
||||
#expect(sessionId == "sess-1")
|
||||
#expect(model.activeEntry?.sessionId == "sess-1")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
|
||||
@@ -18,14 +18,15 @@ Owned by the root AGENTS.md contract.
|
||||
|
||||
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
|
||||
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
|
||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub.
|
||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; an unknown id answers WITHOUT a sessionId), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
|
||||
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
|
||||
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
|
||||
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
|
||||
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation.
|
||||
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#28:** one roster pin — a completed pass grows the roster with "Pass 1 · \<title\>" active (the auto-created session).
|
||||
- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass auto-creates its session (rostered "Pass 1 · \<title\>" newest-first, active, pass streams into ITS transcript), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece).
|
||||
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
|
||||
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
|
||||
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
|
||||
|
||||
@@ -238,3 +238,24 @@ private func textRows(of model: MentorSessionModel) -> [String] {
|
||||
)
|
||||
#expect(onDisk.contains("pass_state: Pass-2 Done"))
|
||||
}
|
||||
|
||||
/// #28 (S2.3): every pass auto-creates its session — the roster grows by
|
||||
/// 'Pass N · <title>' and that entry is the active transcript's owner.
|
||||
@Test @MainActor func `running a pass grows the roster with its pass session active`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
let before = mentor.roster.count
|
||||
let post = try PostStore.writeNew(body: "# Rostered Pass\n\nOne session per pass.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
#expect(mentor.roster.count == before + 1)
|
||||
#expect(mentor.roster.first?.name == "Pass 1 · \(post.title)")
|
||||
#expect(mentor.activeEntry == mentor.roster.first)
|
||||
#expect(model.lastError == nil)
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
//
|
||||
// SessionLifecycleTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #28 (S2.3): the session lifecycle model layer — pass auto-create,
|
||||
// freeform new + piece association, resume of engine-owned history
|
||||
// (user turns included) with an honest refusal for unknown sessions,
|
||||
// fork, compact over the prompt rail, and roster persistence across
|
||||
// model instances. Runs over the real client + fake ACP server
|
||||
// (ACPClientTests' fake in its `loadReplay` lifecycle mode).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("SessionLifecycleTests")
|
||||
struct SessionLifecycleTests {
|
||||
/// #28 AC2: the pass's session is rostered newest-first, active, and the
|
||||
/// pass prompt streams into ITS transcript — the default freeform
|
||||
/// session stays untouched while Pass State advances exactly as before.
|
||||
@Test @MainActor func `pass auto-creates its rostered session`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
let defaultSession = try #require(mentor.activeEntry)
|
||||
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
// Rostered newest-first, named by convention, and active.
|
||||
#expect(mentor.roster.first?.name == "Pass 1 · \(post.title)")
|
||||
#expect(mentor.activeEntry == mentor.roster.first)
|
||||
// The prompt streamed into ITS transcript; the wire stub never lands.
|
||||
let entry = try #require(mentor.activeEntry)
|
||||
#expect(texts(in: mentor.transcriptRows(of: entry)).contains("Pass 1 · \(post.title)"))
|
||||
// The streamed verdict lands via a client notification Task that can
|
||||
// settle just after runPass returns under load — bounded settle.
|
||||
var streamed = false
|
||||
for _ in 0 ..< 250 {
|
||||
streamed = texts(in: mentor.transcriptRows(of: entry)).contains(where: { $0.contains("Hello mentor.") })
|
||||
if streamed {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let rows = mentor.transcriptRows(of: entry)
|
||||
#expect(streamed)
|
||||
#expect(!texts(in: rows).contains { $0.contains("Critique the piece") })
|
||||
// The pre-existing freeform session's transcript is untouched.
|
||||
#expect(mentor.transcriptRows(of: defaultSession).isEmpty)
|
||||
// Pass State advanced on the completed turn, exactly as before.
|
||||
for _ in 0 ..< 250 where model.posts.first(where: { $0.id == post.id })?.passState != .pass1Done {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(model.posts.first(where: { $0.id == post.id })?.passState == .pass1Done)
|
||||
}
|
||||
|
||||
/// #28 AC2: freeform sessions are wired session/new, rostered
|
||||
/// newest-first, active; a non-nil pieceTitle rides the entry —
|
||||
/// association by convention only.
|
||||
@Test @MainActor func `freeform new session is rostered newest-first and active`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
defer { mentor.shutdown() }
|
||||
#expect(!mentor.canStartSession) // never opened — nothing may start
|
||||
await mentor.openSession()
|
||||
#expect(mentor.canStartSession)
|
||||
|
||||
let free = await mentor.newSession(name: "Doctor", pieceTitle: nil)
|
||||
#expect(free != nil)
|
||||
#expect(mentor.roster.first == free)
|
||||
#expect(mentor.activeEntry == free)
|
||||
#expect(free?.pieceTitle == nil)
|
||||
|
||||
let titled = await mentor.newSession(name: "Notes", pieceTitle: "Essay X")
|
||||
#expect(titled?.pieceTitle == "Essay X")
|
||||
#expect(mentor.roster.first == titled)
|
||||
// Distinct wire ids — every rostered session is its own session.
|
||||
#expect(Set(mentor.roster.map(\.sessionId)).count == 3)
|
||||
}
|
||||
|
||||
/// #28 AC1+AC4: resume replays the ENGINE's history in wire order (user
|
||||
/// turns included) into the entry's transcript; a session the engine
|
||||
/// does not know returns false honestly — entry stays, explanatory row,
|
||||
/// nothing fabricated.
|
||||
@Test @MainActor func `resume replays engine history and refuses unknown honestly`() async throws {
|
||||
let rosterDir = acpTempDir("resume-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("resume"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
// The rostered entry is back and active — and the default open
|
||||
// already RESUMED it (#28 review fix): the engine does not know the
|
||||
// ghost, so the honest refusal row landed during openSession itself.
|
||||
#expect(mentor.activeEntry == ghost)
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
|
||||
|
||||
// The engine does not know it: false, entry stays, explanatory row.
|
||||
let unknown = await mentor.resumeSession(ghost)
|
||||
#expect(!unknown)
|
||||
#expect(mentor.roster.contains(ghost))
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost).filter { row in
|
||||
if case .text = row.content {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}).contains { $0.contains("does not know") })
|
||||
|
||||
// A session the engine still knows: session/load, then the replayed
|
||||
// history renders in wire order — user turn first, thought lane kept.
|
||||
let known = await mentor.newSession(name: "Second", pieceTitle: nil)
|
||||
#expect(known != nil)
|
||||
let resumed = try await mentor.resumeSession(#require(known))
|
||||
#expect(resumed)
|
||||
#expect(mentor.activeEntry == known)
|
||||
// The replayed rows ride notification Tasks — bounded settle, then
|
||||
// the wire-order pins (user turn first, thought lane kept).
|
||||
let resumedEntry = try #require(known)
|
||||
var settled = false
|
||||
for _ in 0 ..< 250 {
|
||||
settled = mentor.transcriptRows(of: resumedEntry).count >= 3
|
||||
if settled {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let replayed = mentor.transcriptRows(of: resumedEntry)
|
||||
#expect(settled)
|
||||
#expect(texts(in: replayed).first == "You: earlier ask")
|
||||
#expect(replayed.contains { row in
|
||||
if case let .thought(text) = row.content {
|
||||
return text == "old thinking"
|
||||
}
|
||||
return false
|
||||
})
|
||||
#expect(texts(in: replayed).contains("Mentor: earlier verdict"))
|
||||
// The wire calls went out over session/load.
|
||||
#expect(mentor.stderrTail.contains { $0.contains("load ghost") })
|
||||
#expect(mentor.stderrTail.contains { $0.contains("load sess-1") })
|
||||
}
|
||||
|
||||
/// #28 AC1: fork wires session/fork, rosters '<name> (fork)' with the
|
||||
/// same pieceTitle, activates it with a FRESH transcript, and leaves the
|
||||
/// original untouched; an empty-string sessionId from the wire is a
|
||||
/// refusal — honest row, nil return.
|
||||
@Test @MainActor func `fork activates a fresh transcript and refuses unknown honestly`() async throws {
|
||||
let rosterDir = acpTempDir("fork-roster")
|
||||
let source = SessionEntry(sessionId: "sess-1", name: "Essay", pieceTitle: "Pt", createdAt: Date())
|
||||
SessionRoster.save([source], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("fork"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
_ = await mentor.sendPrompt("hello mentor") // history in the original's transcript
|
||||
|
||||
let fork = await mentor.forkActiveSession()
|
||||
#expect(fork?.sessionId == "F-1")
|
||||
#expect(fork?.name == "Essay (fork)")
|
||||
#expect(fork?.pieceTitle == "Pt") // the association travels
|
||||
#expect(mentor.roster.first == fork)
|
||||
#expect(mentor.activeEntry == fork)
|
||||
#expect(try mentor.transcriptRows(of: #require(fork)).isEmpty) // FRESH transcript
|
||||
#expect(!mentor.transcriptRows(of: source).isEmpty) // original untouched
|
||||
#expect(mentor.stderrTail.contains { $0.contains("fork sess-1") })
|
||||
|
||||
// Refusal rig: a session the engine does not know forks into "".
|
||||
let refusalDir = acpTempDir("fork-refusal")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: refusalDir)
|
||||
let refuser = MentorSessionModel(
|
||||
binaryPath: makeFakeACP(at: acpTempDir("fork-refuser"), mode: "loadReplay"),
|
||||
rosterDirectory: refusalDir,
|
||||
)
|
||||
defer { refuser.shutdown() }
|
||||
await refuser.openSession()
|
||||
let refused = await refuser.forkActiveSession()
|
||||
#expect(refused == nil)
|
||||
#expect(refuser.activeEntry == ghost) // the refusal did not switch sessions
|
||||
#expect(texts(in: refuser.transcriptRows(of: ghost)).contains { $0.contains("Fork refused") })
|
||||
}
|
||||
|
||||
/// #28 AC1: compact rides the existing sendPrompt rail — the label
|
||||
/// renders, the raw slash command never does, the summary streams into
|
||||
/// the transcript — and is refused while a turn streams.
|
||||
@Test @MainActor func `compact sends the labeled command and is refused while streaming`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
|
||||
await mentor.compactActiveSession()
|
||||
|
||||
#expect(texts(in: mentor.rows).contains("Compact…"))
|
||||
#expect(!texts(in: mentor.rows).contains { $0.contains("/compress") })
|
||||
#expect(texts(in: mentor.rows).contains { $0.contains("Hello mentor.") }) // summary streamed
|
||||
|
||||
// Refusal rig: compact while a turn streams does nothing.
|
||||
let (busy, busyHome, busyMentor) = try makePassRig(mode: "hangOnPrompt")
|
||||
defer { busyMentor.shutdown() }
|
||||
_ = busy
|
||||
_ = busyHome
|
||||
await busyMentor.openSession()
|
||||
let chat = Task { await busyMentor.sendPrompt("just chatting") }
|
||||
for _ in 0 ..< 250 where !busyMentor.isStreaming {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let before = busyMentor.rows.count
|
||||
await busyMentor.compactActiveSession()
|
||||
#expect(busyMentor.rows.count == before)
|
||||
#expect(!texts(in: busyMentor.rows).contains("Compact…"))
|
||||
busyMentor.shutdown() // frees the held turn — bounds the await below
|
||||
_ = await chat.value
|
||||
}
|
||||
|
||||
/// #28 AC4 (ownership) + review fix (the default open RESUMES): a new
|
||||
/// model over the same roster directory restores every entry — the
|
||||
/// roster FILE carries no transcript payload (pinned against the raw
|
||||
/// JSON) — and openSession session/load's the newest entry so its
|
||||
/// history replays from the engine (nothing fabricated locally).
|
||||
@Test @MainActor func `roster survives relaunch transcripts do not`() async throws {
|
||||
let rosterDir = acpTempDir("relaunch-roster")
|
||||
let fake = makeFakeACP(at: acpTempDir("relaunch"), mode: "loadReplay")
|
||||
let first = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { first.shutdown() }
|
||||
await first.openSession() // creates + persists the default 'Mentor'
|
||||
let notes = await first.newSession(name: "Notes", pieceTitle: "Essay X")
|
||||
#expect(notes != nil)
|
||||
|
||||
// The ownership pin: the roster FILE holds names only — exactly the
|
||||
// four entry keys, no transcript payload of any kind (ADR-0007).
|
||||
let rosterURL = URL(fileURLWithPath: rosterDir).appendingPathComponent("sessions.json")
|
||||
let raw = try JSONSerialization.jsonObject(with: Data(contentsOf: rosterURL))
|
||||
let firstEntry = (raw as? [[String: Any]])?.first ?? [:]
|
||||
#expect(Set(firstEntry.keys) == ["sessionId", "name", "pieceTitle", "createdAt"])
|
||||
|
||||
let second = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { second.shutdown() }
|
||||
#expect(second.roster.count == 2)
|
||||
#expect(second.roster.first == notes) // newest-first, all four fields equal
|
||||
#expect(second.roster.last?.name == "Mentor")
|
||||
#expect(second.activeEntry == nil) // nothing active before open
|
||||
|
||||
await second.openSession()
|
||||
#expect(second.activeEntry == second.roster.first)
|
||||
// The default open RESUMED (#28 review fix): the engine's replay
|
||||
// filled the newest entry's transcript — user turns included — so
|
||||
// prompt/fork/compact never run against unloaded state.
|
||||
let rows = try second.transcriptRows(of: #require(second.activeEntry))
|
||||
#expect(rows.contains { row in
|
||||
if case let .text(text) = row.content {
|
||||
return text.contains("earlier ask")
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
/// #28 AC2, the pane's New-Session choice rail: the open piece in Posts
|
||||
/// is the association target; nothing open (or no Posts) = free-floating
|
||||
/// only. Pure SwiftUI layout needs no test (house rule) — this is the
|
||||
/// posts-coupled helper behind the control.
|
||||
@Test @MainActor func `new-session choice reads Posts' open piece`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
#expect(SessionsPaneView.openPiece(in: model) == nil) // nothing open
|
||||
#expect(SessionsPaneView.openPiece(in: nil) == nil) // no Posts at all
|
||||
|
||||
let post = try PostStore.writeNew(body: "# Open Piece\n", home: home)
|
||||
model.select(post.id, home: home)
|
||||
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(SessionsPaneView.openPiece(in: model)?.id == post.id)
|
||||
}
|
||||
|
||||
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
|
||||
/// resume while a session/load is in flight refuses instead of diverting
|
||||
/// the first's replayed chunks into live streaming buffers.
|
||||
/// `loadReplayHold` parks the load until `load-go` lands beside the
|
||||
/// fake; the pre-hold "hold-load" stderr line is the in-flight
|
||||
/// observable.
|
||||
@Test @MainActor func `concurrent resume refuses while a replay is in flight`() async throws {
|
||||
let dir = acpTempDir("hold-load")
|
||||
let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
|
||||
let rosterDir = acpTempDir("hold-roster")
|
||||
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([known], directory: rosterDir)
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
|
||||
var inFlight = false
|
||||
for _ in 0 ..< 250 {
|
||||
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
|
||||
inFlight = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(inFlight)
|
||||
|
||||
// The slot is taken: the second resume refuses honestly.
|
||||
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
|
||||
let ok = await mentor.resumeSession(other)
|
||||
#expect(!ok)
|
||||
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
|
||||
|
||||
// Release the hold: the parked resume completes and replays.
|
||||
try "go".write(toFile: (dir as NSString).appendingPathComponent("load-go"), atomically: true, encoding: .utf8)
|
||||
var replayed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
|
||||
replayed = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(replayed)
|
||||
}
|
||||
|
||||
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
|
||||
/// refusal lands in its own store, never in the active session's
|
||||
/// transcript.
|
||||
@Test @MainActor func `resume refusal is attributed to the entry not the active session`() async throws {
|
||||
let rosterDir = acpTempDir("attrib-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("attrib"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession() // activates ghost; its load refuses (unknown id)
|
||||
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
|
||||
#expect(second != nil)
|
||||
|
||||
_ = await mentor.resumeSession(ghost) // refuses again
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
|
||||
let secondEntry = try #require(second)
|
||||
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
|
||||
}
|
||||
|
||||
/// Finish-audit: the creation rail refuses while a turn streams — a
|
||||
/// programmatic caller must not switch the active session out from
|
||||
/// under a live turn (Stop would cancel the wrong session).
|
||||
@Test @MainActor func `new session refuses while a turn streams`() async throws {
|
||||
let (_, _, mentor) = try makePassRig(mode: "hangOnPrompt")
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
let chat = Task { await mentor.sendPrompt("just chatting") }
|
||||
for _ in 0 ..< 250 where !mentor.isStreaming {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(mentor.isStreaming)
|
||||
|
||||
let created = await mentor.newSession(name: "Sneaky", pieceTitle: nil)
|
||||
#expect(created == nil)
|
||||
#expect(texts(in: mentor.rows).contains { $0.contains("Session refused — the mentor is mid-turn.") })
|
||||
mentor.shutdown() // frees the held turn — bounds the await below
|
||||
_ = await chat.value
|
||||
}
|
||||
|
||||
/// Finish-audit: the roster file is writer-only (0600) — names carry
|
||||
/// piece titles, and the default umask is group/world-readable.
|
||||
@Test @MainActor func `roster file is writer only`() throws {
|
||||
let rosterDir = acpTempDir("perm-roster")
|
||||
SessionRoster.save([SessionEntry(sessionId: "s", name: "N", pieceTitle: "T", createdAt: Date())], directory: rosterDir)
|
||||
let url = URL(fileURLWithPath: rosterDir).appendingPathComponent("sessions.json")
|
||||
let perms = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int
|
||||
#expect(perms == 0o600)
|
||||
}
|
||||
|
||||
/// Finish-audit: restart() REPLAYS the active transcript from the
|
||||
/// engine (ADR-0007 — the engine owns the words; the pre-crash local
|
||||
/// rows are replaced by the replay, not preserved).
|
||||
@Test @MainActor func `restart replays the active transcript from the engine`() async throws {
|
||||
let rosterDir = acpTempDir("restart-roster")
|
||||
let fake = makeFakeACP(at: acpTempDir("restart"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
_ = await mentor.sendPrompt("hello") // a turn lands in the active session
|
||||
#expect(!mentor.transcriptRows(of: try #require(mentor.activeEntry)).isEmpty)
|
||||
|
||||
if let pid = mentor.childProcessIdentifier {
|
||||
kill(pid, SIGKILL) // crash the child
|
||||
}
|
||||
var crashed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if case .crashed = mentor.phase {
|
||||
crashed = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(crashed)
|
||||
|
||||
await mentor.restart()
|
||||
// The post-restart transcript is the ENGINE's replay — the replay
|
||||
// marker proves the words came from the engine, not the local copy.
|
||||
let rows = mentor.transcriptRows(of: try #require(mentor.activeEntry))
|
||||
#expect(rows.contains { row in
|
||||
if case let .text(text) = row.content {
|
||||
return text.contains("earlier ask")
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func texts(in rows: [SessionRow]) -> [String] {
|
||||
rows.compactMap {
|
||||
if case let .text(text) = $0.content {
|
||||
text
|
||||
} else {
|
||||
nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
# Sessions: Session lifecycle UI (S2.3)
|
||||
|
||||
> **Date:** 2026-10-22
|
||||
> **Type:** issue
|
||||
> **Reference:** [issue #28](https://git.babylondreams.de/AlexKucera/Museion/issues/28) (blocked-by #14, closed)
|
||||
|
||||
## Goal
|
||||
|
||||
Each Session is a conversation with the standard affordances, engine-owned — Museion only UIs them: new/cancel/fork/resume/compact from the Sessions pane, every pass auto-creating its session, freeform sessions free-floating or piece-associated by name/convention, cancel mid-pass, live streaming, transcripts staying behind on an engine swap (ADR-0007).
|
||||
|
||||
## What Was Done
|
||||
|
||||
- **`MentorSessionModel.swift`** rewritten single-session → multi-session: per-session transcripts keyed by wire sessionId, `rows`/`streamingText`/`streamingThought` same-named proxies over the ACTIVE session (all callers compile unchanged). `SessionEntry` + `SessionRoster` (names-only JSON at `~/Library/Application Support/Museion/sessions.json`, injectable dir, hosted-test temp redirect). New API: `newSession(name:pieceTitle:)`, `resumeSession(_)` (session/load, replay-before-response, user turns rendered), `forkActiveSession()`, `compactActiveSession()` (`/compress` over the sendPrompt rail), `beginPassSession(kind:pieceTitle:)`, `canStartSession`, `transcriptRows(of:)`. Phase `.ready` lost its sessionId payload.
|
||||
- **Notification routing**: updates filed under the PARAMS' sessionId; notification→MainActor hops ride `DispatchQueue.main.async` (Task-hops starved under parallel tests; main queue = FIFO with the continuation resume → replay-before-response guaranteed).
|
||||
- **`PostsModel.runPass`**: `beginPassSession` after snapshot, before sendPrompt (flag-after-await + ownership re-guard — see Gotchas).
|
||||
- **`SessionsPaneView.swift`** (new): PaneHeader + New Session control (Menu with "on \<piece\>" variant when Posts has an open piece), roster list (LibraryPostRow strip language, row click = resumeSession), actions row (Fork · Compact, `canStartSession`-disabled), liveness + Stop, transcript via shared renderer.
|
||||
- **`SessionTranscriptView.swift`** (new): transcript rendering extracted verbatim from MentorPaneView (#24 `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` lives here, MentorPaneView delegates.
|
||||
- **`WorkspaceView.swift`**: Sessions placeholder → real pane; `PlaceholderPane` deleted.
|
||||
- **Fake ACP** (`ACPClientTests.swift`): unique ids per session/new, prompt-sid echo, `loadReplay`/`loadReplayHold` modes (replay-before-response; hold parks until `load-go` for interleaving pins), session/fork (F-\<n\> / "" refusal), mcpServers strictness on new/load/fork.
|
||||
- **Tests**: `SessionLifecycleTests.swift` (12 pins — scenarios + finish-audit), `PassRunTests` roster pin, five finish-audit pins (concurrent resume, refusal attribution, mid-turn create refusal, roster 0600, restart-replays-from-engine via real SIGKILL).
|
||||
- **DOX pass**: `Museion/AGENTS.md` (workspace shell, ACP bridge #28 block, MentorPaneView), `MuseionTests/AGENTS.md` (fake modes, SessionLifecycleTests entry, PassRunTests roster pin), persistence-exception line.
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Roster = Museion-side names+ids JSON (no `session/list`) | PRD "association stays by name/convention"; engine list would surface unrelated hermes CLI sessions; transcripts stay engine-owned (ADR-0007) — roster persists the four name fields ONLY |
|
||||
| Compact = `/compress` slash prompt over sendPrompt | The engine's compact surface is a slash command; the label rail hides the raw command |
|
||||
| Relaunch default-open RESUMES (`session/load` newest entry) | Fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state (spec-review catch) |
|
||||
| Restart replaces kept rows with the engine replay | ADR-0007: the engine owns the words; a diverging local copy would lie. The deleted `rows.isEmpty` skip was dead code (activate() resets one line above) |
|
||||
| `DispatchQueue.main.async` for notification hops | `Task { @MainActor }` starved behind parallel test work — replay landed seconds late; main queue is FIFO with the continuation resume, making wire order guaranteed |
|
||||
| Flag-after-await + ownership re-guard in runPass | Flag-before-await breaks the #124 Cancel pin (Stop no-ops during session/new); the re-guard closes the double-click window the await opened |
|
||||
| Two public session-creation names over one private rail | `newSession` (pane) / `beginPassSession` (pass naming) — the seam reads at the call site |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|-----------|-----|
|
||||
| Replay updates landed seconds late or never in tests | `Task { @MainActor }` hops starve under parallel test load | `DispatchQueue.main.async` hops (FIFO with continuation resume) |
|
||||
| #124 Cancel pin hung during pass start | `runningPass` set before the session/new await → Stop observed the flag with `isStreaming` false → cancel no-op | Flag goes live after the awaits + ownership re-guard |
|
||||
| resumeSession wiped the just-replayed transcript | Shared `activate()` reset the store after replay filled it | Replay path activates without reset |
|
||||
| Fast double-click interleaved replays, diverting chunks into live buffers | `replayingSessionId` is one slot; resume never set `isStreaming` | Refuse-while-replaying guard (converged finding, 3 reviewers) |
|
||||
| Restart's kept transcript silently wiped | Dead `rows.isEmpty` skip (activate() resets above it) | Unconditional resume + honest docs (ADR-0007 posture) |
|
||||
| finish-audit suite run hung 14 min | New pin awaited a held `hangOnPrompt` turn nothing cancelled | Free the held turn (`shutdown()`) before awaiting, matching the neighboring pin |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|----------------|
|
||||
| `Museion/MentorSessionModel.swift` | Multi-session model, roster, session lifecycle wire rails, replay handling |
|
||||
| `Museion/PostsModel.swift` | runPass auto-creates its session + ownership re-guard |
|
||||
| `Museion/SessionsPaneView.swift` | New — the Sessions pane |
|
||||
| `Museion/SessionTranscriptView.swift` | New — shared transcript renderer |
|
||||
| `Museion/MentorPaneView.swift` | Transcript extraction, `.ready` payload adaptation |
|
||||
| `Museion/WorkspaceView.swift` | Real Sessions pane wiring, PlaceholderPane deleted |
|
||||
| `MuseionTests/SessionLifecycleTests.swift` | New — 12 lifecycle + finish-audit pins |
|
||||
| `MuseionTests/ACPClientTests.swift` | Fake session-lifecycle wire (new/load/fork, hold mode) |
|
||||
| `MuseionTests/PassRunTests.swift` | Pass-roster pin |
|
||||
| `Museion/AGENTS.md` / `MuseionTests/AGENTS.md` / `AGENTS.md` | DOX pass (#28 contracts, fake modes, index-stats churn) |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Model picker, pane input field, `session/list`, session renaming — deliberate v1 cuts, none ticketed
|
||||
- [ ] `session/load` timeout has no runtime pin (not wire-observable with an instant fake); the fix is `timeout: promptTimeout`
|
||||
- [ ] Transcripts dict grows for the app's life (fine at single-writer load; prune-on-pane-entry if ever felt)
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-10-22 | issue | [20261022-issue28-session-lifecycle-ui_log.md](20261022-issue28-session-lifecycle-ui_log.md) | #28 Session lifecycle: multi-session model + names-only roster, pane, pass auto-create, finish-audit with 7 fixes — 359 tests green |
|
||||
| 2026-10-21 | issue | [20261021-issue27-dismiss-decay-learnings_log.md](20261021-issue27-dismiss-decay-learnings_log.md) | #27 dismiss & decay Learnings: per-type pass clock, frontmatter decay state, consult filtering, two review waves with 5 fixes |
|
||||
| 2026-10-21 | issue | [20261021-issue26-promote-consult-learnings_log.md](20261021-issue26-promote-consult-learnings_log.md) | #26 promote/consult Learnings: teaching-shape files, on-disk-truth promote, symlink guard, Learnings pane — 329 tests green |
|
||||
| 2026-10-20 | issue | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) | #124 cancel-acknowledging hangOnPrompt fake, Cancel-rail pin (RED→GREEN), defer-at-rig-creation teardown ×27 rigs — 316 tests green |
|
||||
|
||||
Reference in new issue
Block a user