feat(launch): flip to the gateless launch (#151)
CI / ci (push) Canceled after 0s

Wayfinder map #148's terminal slice (decisions #150 architecture,
#149 UX variant A): every launch now opens straight into the
workspace. The engine check (hermes acp --check) runs async from
ContentView.task via AppGateState.startLaunchCheck — provisioning
(x3 profiles) and the daily backup auto-fire the moment it passes
(the gate era's exact onEnginePass chain, moved verbatim; once per
app-launch, first window only, no-op under hosted tests). Nothing
blocks: the blocking gate sheet, the placeholder logo screen,
gateRaised/gateDismissed, EngineGateView, and the
ProvisioningFailureCard sheet are deleted (net -350 lines with the
additions).

Engine state stays visible instead of interrupting: a 44x44 rail
pill above Archive (8pt pulsing accent dot while checking, warning
glyph on an accent-12% wash when failed, nothing at all once
healthy — the slot collapses and the rail spacing closes) and
mono-10 mentor-pane header states (checking... / engine missing /
setup failed / hermes <base> once ready — the BASE version, never
the gate's derived string; session chip renders only once ready).
Failure auto-expands an anchored floating card (340pt, accent
border — floats, never blocks): engine-missing carries #40's
install steps with the gateless correction plus Copy, guide link,
Re-check (disabled-while-checking), stderr + probed path;
provisioning failure rides the same card (failing profile named,
Retry inline). Focus mode recesses the card with the rail. Panes
spawn the engine the moment the check lands (.task(id: binaryPath)
on the nil->value arrival; a nil binary never calls openSession —
that path lands the crash card). state.json semantics unchanged
(About still reads it); #38's no-silent-degradation AC survives,
carried by the pill.

New GatelessLaunchTests pin the seam (hosted-test no-op, chain
armed, pill + mentor-header visibility mappings — flip-verified);
EngineGateTests byte-untouched and green; the dead deferFailure
(#48's Not-Now) deleted with its test. PRD G1 amended; gateless
DOX pass (Museion/AGENTS.md engine section rewritten); CHANGELOG;
devlog. The #149 prototype ships lint-clean.

Verified: full-scheme test 582 passed / 0 failed / 0 skipped
(xcresult executed count, unit + UI), swiftformat lint clean,
swiftlint 0 errors on touched files, finish-audit fanout clean
(ponytail/security/general; 5 fixes applied, header-mapping pins
flip-discriminated and restored).

Closes #151
Closes #139
This commit is contained in:
AlexKucera committed 2026-11-03 16:50:55 +01:00
1 parent 4065c31ec8
commit 55eff3a754
19 files changed
+1721 -384

No files matched your search

+13 -12
View File
@@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Local Contracts
- Entry point: `MuseionApp.swift` (`WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#23:** no `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless `museion-tools` MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires).
- Entry point: `MuseionApp.swift` (`WindowGroup` scene + `about` window; `AppGateState` holds app-scoped state; #151 gateless — `ContentView.task` fires `startLaunchCheck`, the async engine check + auto-fire chain). **#23:** no `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless `museion-tools` MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires).
- `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.
@@ -21,7 +21,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Workspace shell (M1, #17 + #18 / S1.1)
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<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 querieLine truncated
- `WorkspaceView.swift` — the first-frame main surface (#151: gateless — rendered unconditionally by ContentView; the engine check runs async beside it): nav rail (Posts/Sessions/Learnings/Trends + the #151 engine-status pill + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<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 repointeLine 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. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `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). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
- `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; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `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; **#31 (S5.1): the state update iLine truncated
@@ -44,24 +44,25 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
## Engine gate (launch gate, tickets #35–#41)
## Engine check (gateless launch, #35–#41 + #151, map #148)
- `EngineGate.swift` — `EngineProbe` (nonisolated): six-path probe order, `acp --check` health (stdin closed, 5 s timeout, exit-status branching), `acp --version` version, `state.json` writer/reader. `EngineGateModel` (@MainActor @Observable): phases for the UI, `onPass` seam (fires provisioning, #47), `currentBinaryPath` handed to provisioning. `execute(_:timeout:)`/`ProcessOutput` are internal — shared child-process machinery.
- `EngineGateView.swift` — blocking sheet card: checking / pass (version + Start Writing) / fail (two install steps per #40, Re-check, Technical details disclosure). `interactiveDismissDisabled`; sheet never closes itself.
- `state.json` lives at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check; fail records carry no `engineVersion`. Gate renders in-memory; About (`AboutEngineView` in `MuseionApp.swift`) reads the file and never triggers a check.
- Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` fires provisioning (#47) in parallel on pass.
- Tests: `MuseionTests/EngineGateTests.swift` builds fake `hermes` shell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records.
- `EngineGate.swift` — `EngineProbe` (nonisolated): six-path probe order, `acp --check` health (stdin closed, 5 s timeout, exit-status branching), `acp --version` version, `state.json` writer/reader. `EngineGateModel` (@MainActor @Observable): phase machine (idle/checking/pass/fail) — **#151: the pill's state source**, unchanged; `onPass` seam (fires the auto-fire chain), `currentBinaryPath` handed to provisioning. `execute(_:timeout:)`/`ProcessOutput` are internal — shared child-process machinery.
- **#151 — the gateless flip:** `AppGateState.startLaunchCheck()` (called from `ContentView.task`) arms the auto-fire chain (`wireAutoFire` — provisioning `runPass(hermesBinary:)` then `backup.runPass()`, the gate era's exact `onEnginePass` body) and awaits `beginAutomaticCheck()`; `hasStarted` preserves #41's once-per-app-launch, first-window-only rule (⌘N no-ops). No-ops under hosted tests (`XCTestConfigurationFilePath` — the panes' guard pattern; never probe or auto-provision there). ContentView renders `WorkspaceView` unconditionally — the posts scan starts at first frame, concurrent with the check; nothing library-side waits on the gate. The blocking sheet, placeholder logo screen, `gateRaised`/`gateDismissed`, and `EngineGateView`/`ProvisioningFailureCard` are deleted.
- `EngineStatusView.swift` — the status surfaces (#149 variant A, prototype `prototypes/GatelessStatusPrototype.swift`): `EngineStatusSurface.visibility(phase:provisioningFailed:)` (pure, test-pinned — the mapping: idle/pass+healthy → hidden, checking → pulse, fail/pass+provisioning-failed → failed), `EngineStatusPill` (44×44 rail slot above Archive: 8pt pulsing accent dot while checking, `exclamationmark.triangle.fill` on an accent-12% wash when failed, nothing when healthy — the slot collapses and rail spacing closes), `EngineStatusCard` (the anchored fail card: 340pt, bottom-leading at railWidth+12/bottom 14, surface bg, accent-0.5 border, radius 12, shadow — floats, never blocks, never pushes layout; auto-expands on each failure arrival via WorkspaceView's `.onChange(of: visibility)`, chevron collapses, slot click re-opens; WorkspaceView hosts slot + card overlay — focus mode recesses the CARD with the rail, the expanded state surviving for exit-focus). Engine-fail content = #40 copy with the gateless subtitle ("Passes and Sessions need it — the editor keeps working"), the two install steps + Copy + Installation guide link, Re-check (accent, disabled-while-checking, label "Checking…"), Technical details (stderr excerpt + "Probed: <path>"; bare Probed line when stderr is empty). Provisioning failure rides the same card: title "Setup failed", phase rawValue + failing profile mono (#134), the safe-to-retry body, Retry inline (re-runs provisioning; success nils `lastFailure` and the surface disappears — live-read, no snapshot).
- `state.json` lives at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check (Re-check included); fail records carry no `engineVersion`. About (`AboutEngineView` in `MuseionApp.swift`) reads the file and never triggers a check.
- Panes spawn the engine the moment the check lands: `MentorPaneView`/`SessionsPaneView` seed `.task(id: binaryPath)` (nil→value arrival re-fires; a nil binary never calls `openSession` — that path lands the crash card, so the gate's fail state owns the interim). The mentor pane header carries mono-10 engine states beside "Mentor Session" (checking… muted + mini spinner / engine missing accent / setup failed accent / `hermes <base>` once ready — the BASE version, handshake answer first, gate's derived string `+`-stripped meanwhile; drift note keeps its orange help). The session chip renders only once ready; status text wins layout priority. Both panes' idle branches show the honest missing-engine notice when the gate failed (never an eternal "Starting…" spinner — SessionsPaneView takes `gate` for it). The header's state derivation is `MentorEngineStatus.state(phase:provisioningFailed:)` — pure, test-pinned (the outrank rule: engine failure wins over a lingering provisioning failure).
- Tests: `MuseionTests/EngineGateTests.swift` (untouched — probe order, first-stderr reporting, timeout kill, state records, onPass-fires-per-passing-check, once-per-model) + `MuseionTests/GatelessLaunchTests.swift` (#151: startLaunchCheck hosted-test no-op, wireAutoFire arms the chain, the pill visibility mapping incl. provisioning-failure-under-passed-gate, the mentor header mapping).
## Profile provisioning (S2.1 #43–#48; #134 Profiles S1)
- `ProfileProvisioner.swift` — the #134 surface registry + the provisioner. **`ProfileSurface`** (nonisolated enum, chat/pass1/pass2; declaration order = provision order — chat first so the resident surface is healthy before any pass-profile failure stops the loop): `profileName` (museion adopted in place / museion-pass1 / museion-pass2, Sessions rides Chat per #126), `allocatedSkills` (#133 table: P1 10 · P2 9 · Chat 11 — #58 adds owned-insight on all three; persona pair never co-occurring), `init?(passKind:)` (the PassKind→profile seam), and the #132 fresh-seed defaults as constants (`defaultModelProvider` anthropic, `defaultModelID` claude-sonnet-5-5, `outputBudgetTokens` 24000 — reasoning_effort never written). **`ProfileProvisioner.perform`** (nonisolated): one idempotent pass = master-seed + per-surface phases. Phase 0 master: every manifest skill seeded additively as REAL dirs into the ONE master copy at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable) — `seed-manifest.txt` is still the shipped-set list (kebab-validated at the trust boundary); temp+rename per skill, never touch present ones, orphaned `.`-temps swept, `.DS_Store` purged. Then per surface (first failure wins; the next pass heals): **create** — dir-check first, `hermes profile create <name> --no-alias --no-skills` only when missing (#43 already-exists semantics); `museion` is adopted, never re-created (ADR-0014). **configure** — the #132 defaults written through the engine's own CLI (`hermes -p <profile> config set model.provider/model.default/model.extra_body.max_tokens 24000 --force`, provider first — switching providers clears a stale inherited base_url, live-probed; #128: never rely on create-time inheritance); success is WIRE-VERIFIED (`exit 0` + `✓ Set <key>` on stdout — not exit code alone, finish-audit) and a marker write that fails surfaces as a configure-phase failure (an unrecorded configure must not count as done). MARKER-GATED by `.museion-provisioned` in the profile dir so a re-pass is a no-op and a user's later Settings change survives: runs for fresh creates and for an unconfigured PASS profile (interrupted before its marker landed — Retry heals); the adopted museion is NEVER configured (its glm-5.3-max is the user's until Settings switches it). **skills** — per profile, symlink each manifest name into the master: an existing link (live or dangling) is never retargeted; a copy-era REAL dir swaps to a symlink only on `treesByteMatch` against the MASTER (the link's target — identical to the payload on first seed; `.DS_Store` filtered from both listings so a Finder-browsed dir still migrates) with move-aside → link → delete-aside, restored on failure; a diverged dir stays a copy, untracked/user skills never touched (G3a); a missing skill links only when the surface ALLOCATES it (curation). **register** — museion-tools per profile (ADR-0008 amendment): `-p <profile> mcp list` skip / `mcp add` with repeated-y stdin, both binaries required (nil = test seam). `Outcome.seeded(copied:present:)` aggregates master copies + links; `.failed(profile:phase:excerpt:)` names the profile (nil for payload-level failures) — phases create/copy/register/configure. `ProvisioningModel` unchanged in shape; `runPass` gained `masterRoot`.
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented`); phase rawValue is the title with the failing profile name in mono beneath (#134 — with three profiles, "which one?" is the first question; nil profile hides the row), excerpt behind Technical details; card snapshots the failure into `@State`; Retry re-runs the whole idempotent pass, Not Now defers to next launch. Provisioning still never hand-writes profile config — mcp registration AND the model defaults both go through the engine's own `hermes` CLI (#44 as amended by #23/ADR-0008 and #134/ADR-0014: the provisioner writes no config.yaml bytes itself, but a FRESH pass profile's config.yaml IS legitimately written by `config set` — byte-identity now holds only for adopted/engine-owned configs, test-pinned).
- Provisioning failure UX (#48, reborn #151): rides the rail fail card (`EngineStatusCard`'s setup branch — `EngineStatusView.swift`) — the blocking-sheet `ProvisioningFailureCard` is deleted; phase rawValue + failing profile name in mono (#134 — with three profiles, "which one?" is the first question; nil profile hides the row), excerpt behind Technical details; Retry re-runs the whole idempotent pass (a success nils `lastFailure` and the surface disappears; Not-Now defer died with the sheet and the dead `deferFailure` method is deleted with its test — collapse is view-state, the orange pill stays until a pass succeeds, #38's no-silent-degradation carried by the pill). Provisioning still never hand-writes profile config — mcp registration AND the model defaults both go through the engine's own `hermes` CLI (#44 as amended by #23/ADR-0008 and #134/ADR-0014: the provisioner writes no config.yaml bytes itself, but a FRESH pass profile's config.yaml IS legitimately written by `config set` — byte-identity now holds only for adopted/engine-owned configs, test-pinned).
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 12 mentor skills ship (#58 added owned-insight); the master seeds all 12, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profiles at `<binaryDir>/profiles/<name>`, speaks `-p <any-profile> mcp list`/`mcp add` with per-profile marker/invocation files and `config set` with a per-profile argv log + `config-set-fails`/`mcp-add-fails` knobs, logs every `profile create`), injected profile/payload/master dirs, manifest ↔ payload correspondence. **#134:** `ProfileSurfaceTests.swift` (own file) pins the registry (names/order, PassKind mapping, allocation counts + persona split, defaults, allocation ⊆ bundled manifest), ×3 provisioning with exact config-set command lines, master-once + per-allocation symlinks, re-pass no-op (config-set log byte-stable, no re-creates), adopted-museion untouched, marker heal/no-stomp, failing provision names the profile, configure-phase failure. `ProfileSkillMigrationTests.swift` (own file) pins the byte-match migration (browsed dir with `.DS_Store` still migrates, content identical through the swap; diverged stays a copy; untracked untouched; a symlinked entry inside a copy-era dir refuses the match — never followed, finish-audit). Failure-path tests in `ProfileProvisionerFailureTests.swift` (config.yaml byte-identity through failed/nil-skip/CLI-registering passes, fresh-profile case in its own test, copy-phase catch, path traversal, orphan sweep).
## Profile backup (S2.6, #15 map / #50)
- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on gate pass **after** the provisioning pass finishes (await chain in `ContentView.onEnginePass` — a failed provision doesn't skip the backup). **#134/#129 — one stamp, three subdirs:** the sources are the three surface profiles from `ProfileSurface.allCases`; a missing profile dir is simply absent from the stamp (only NO profile at all → `.skippedProfileMissing`); NEVER the profiles root (non-Museion profiles are not ours to back up). Any-live-skip-all: every existing profile dir must be idle or the WHOLE stamp skips (one stamp = one consistent point in time) — per-dir `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + the `ps ax -o command=` scan for `profiles/museion` / `-p museion` (already substring-matches the pass profiles; `psScan` injectable for tests) → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: per profile into `<stamp>/<name>/`, recursive walk with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars; dir symlinks resolve (`fileExists(isDirectory:)` follows) so profile skill symlinks snapshot as content, keeping restores self-contained (#133 folded). A file vanishing mid-copy is skipped. Install: copy into `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, prune past 7 after a successful rename. `RESTORE.md` documents the three folders (written once into the Backups root). Failure = one os_log line, never an alert; constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`).
- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on check pass **after** the provisioning pass finishes (await chain in `AppGateState.wireAutoFire` — a failed provision doesn't skip the backup). **#134/#129 — one stamp, three subdirs:** the sources are the three surface profiles from `ProfileSurface.allCases`; a missing profile dir is simply absent from the stamp (only NO profile at all → `.skippedProfileMissing`); NEVER the profiles root (non-Museion profiles are not ours to back up). Any-live-skip-all: every existing profile dir must be idle or the WHOLE stamp skips (one stamp = one consistent point in time) — per-dir `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + the `ps ax -o command=` scan for `profiles/museion` / `-p museion` (already substring-matches the pass profiles; `psScan` injectable for tests) → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: per profile into `<stamp>/<name>/`, recursive walk with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars; dir symlinks resolve (`fileExists(isDirectory:)` follows) so profile skill symlinks snapshot as content, keeping restores self-contained (#133 folded). A file vanishing mid-copy is skipped. Install: copy into `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, prune past 7 after a successful rename. `RESTORE.md` documents the three folders (written once into the Backups root). Failure = one os_log line, never an alert; constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`).
- `BackupModel` (@MainActor @Observable): app-scoped (`AppGateState.backup`), runs the pass off-main, guards stacking, records `lastOutcome` (informational only — no UI).
- UI: Help → **Open Backup Folder** (`OpenBackupFolderButton` in `MuseionApp.swift`) reveals the Backups root in Finder; restore docs live in `RESTORE.md` beside the snapshots.
- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan (`makeProfileFixture(at:name:)` builds any profile): liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept). **#134:** one stamp carries all three profile dirs with RESTORE.md naming them, a live PASS-profile pid skips the whole stamp (nothing half-written), missing pass profiles snapshot the rest.
@@ -79,8 +80,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `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`/`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; **#30 dogfood: the REAL 0.21.5 load response carries NO top-level `sessionId` — the id rides `_meta.hermes.sessionProvenance.acpSessionId`, so extraction accepts both shapes and empty-everywhere alone means the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session; the top-level-only read made every real-engine resume fail as "unknown"**), `forkActiveSession()` (wire session/fork → "<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), `beginBrainstormSession(pieceTitle:)` (#30: the brainstorm flavor — a "Brainstorm" rostered session whose first turn is `brainstormPrompt`, the normal prompt rail, no new machinery; pinned: roster head + labeled opener + raw prompt absent + reply streams into ITS transcript), `draftCandidateText()` / `draftCandidateText(in:)` (#30: the New-Post-from-Session candidate — the LAST "Mentor: " text row, prefix stripped; user/thought/card/research/raw rows never prefill, blank bodies skipped, and the refusal/connection-shaped rows sharing the display prefix are excluded — ponytail-marked until SessionRow carries speaker identity), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. **#29 (S8.1–S8.3) research candidates:** `ResearchCandidate` (nonisolated: piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote` — `appendToolCall` routes on PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses via `ResearchCandidate.batch` (one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted). `setResearchDisposition(rowID:_:)` flips the ACTIVE session's row in place (unknown id = no-op). `isWritingRow` keeps `.researchNote` visible in the writing voice.
**#137 (S4, ADR-0014) per-surface engine lifecycle:** passes run on their OWN one-shot engines — `runPass(kind:stub:pieceTitle:)` spawns `ACPEngineClient(binaryPath:, profile: ProfileSurface(passKind:))` (museion-passN), streams the verdict into a TRANSIENT unrostered transcript under `passTranscriptKey` ("pass", the active entry lives only for the run — #129: passes are never rostered; `handleNotification` maps the pass wire sid onto the key), and tears the engine down at the verdict (`teardownPassEngine`; onCrash deliberately nil — a pass-engine crash lands the honest failure row, never the crash card; KNOWN EDGE, accepted v1: a chat-engine crash mid-pass flips the pane while the pass completes underneath). **#122: the spawn/session/new/teardown block is ONE private rail — `runOneShot(profile:name:prompt:pieceTitle:)` — shared by `runPass` and `runBlindRead(prompt:pieceTitle:reveal:)` (the Blind Read rides the CHAT profile `museion`: context-free = a fresh session, not a different judge — decision #120; the reveal row appends only on `.ended` with stopReason ≠ "refusal" — a refusal still ends .ended, and a 2×-document prompt makes length refusals realistic — after the turn-end flush, so the mapping can never leak to the judge). `name` ("Pass 1"/"Blind Read") composes the label; the rail's failure rows speak `\(label) failed` so a Blind Read spawn failure never reads "Pass failed".** The turn pipeline is ONE `turnCore(client:wireSid:key:prompt:label:)` shared by sendPrompt and the pass run (label row, session/prompt, stopReason mapping, buffer flush); `sendPrompt` refuses the pass surface with a visible row (read-only transcript). Restart posture: `restart()` (crash button) and `requestRestart()` (model-change, Settings fires it) share `respawn()` — teardown, fresh spawn, resume the PRE-restart active rostered session (not blindly the newest); `requestRestart` defers to turn end while `isStreaming` (`pendingRestart`, fired from both turn-end defers — a reply is never cut mid-stream) and ignores .idle/.starting (a future spawn reads fresh config). `stopStreaming` routes `session/cancel` to the PASS engine while a pass runs. Internal test observables: `passEngineChildPid`, `isPassEngineRunning`. **Run Pass readiness (#137 acceptance 3, slice B):** `PassReadiness` (ready | missingKey(providerLabel) | unknown) per kind, stored in the class body (`passReadiness`; `passReadinessWriter` = injectable read seam, nil → ad-hoc `HermesSettingsWriter` over the gate's binary, no binaryPath → stays empty); `refreshPassReadiness()` reads both pass profiles' providers in ONE task group, then each DISTINCT provider's key — an unreadable surface maps `.unknown` (never block on our own read failure). `PostsModel.runPass` guards `.missingKey` BEFORE the open-piece guard: `lastError` names the provider and nothing touches disk, not even the pre-pass snapshot.
- `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 or (#122) `posts.runningBlindRead` — one Cancel rail ends either run) ↔ **#122: Blind Read** (bordered, beside Run — disabled with the reason in help: no open post, `!posts.openPieceHasSnapshot` ("run a Pass first"), or the engine can't take the turn; one click fires `posts.blindRead`; help otherwise names it advisory-only, records nothing) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing <provider> key —` line under the state row carries a borderless accent **Open Settings** button (`onOpenSettings`, threaded MentorPaneView→PostsPaneView→WorkspaceView's `selection = .settings`, ArchivePaneView closure precedent), the disabled Run's help names the reason, and `.unknown` never disables (the spawn's honest failure owns that path). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). The header's session chip hides while the transient pass transcript (`passTranscriptKey`) owns the active surface, and the pane's `.task` runs `refreshPassReadiness()` before the hosted-test guard — pane re-entry re-fires it, so a key added in Settings re-enables Run Pass. `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:)` + EditorSessioLine 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).
- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (**#151: mono-10 engine states beside the title — checking… / engine missing / setup failed / `hermes <base>` once ready, gate's phase machine the source, session chip only once ready, status text wins layout priority; the running version + orange drift note render inside the ready state** — **#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 or (#122) `posts.runningBlindRead` — one Cancel rail ends either run) ↔ **#122: Blind Read** (bordered, beside Run — disabled with the reason in help: no open post, `!posts.openPieceHasSnapshot` ("run a Pass first"), or the engine can't take the turn; one click fires `posts.blindRead`; help otherwise names it advisory-only, records nothing) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing <provider> key —` line under the state row carries a borderless accent **Open Settings** button (`onOpenSettings`, threaded MentorPaneView→PostsPaneView→WorkspaceView's `selection = .settings`, ArchivePaneView closure precedent), the disabled Run's help names the reason, and `.unknown` never disables (the spawn's honest failure owns that path). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). The header's session chip hides while the transient pass transcript (`passTranscriptKey`) owns the active surface, and the pane's `.task(id: binaryPath)` runs `refreshPassReadiness()` before the hosted-test guard — #151: keyed on the nil→value arrival so the engine spawns the moment the gateless check lands (a nil binary never calls openSession); re-fires re-run it, so a key added in Settings re-enables Run Pass. `gate: AppGateState?` (#151 header states) + `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes all three. **#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 mLine truncated
- Wiring: `AppGateState.mentor` is the app-scoped model ( #151: PostsPaneView's mentor column passes `gate.gateModel.currentBinaryPath` as `binaryPath`; the pane re-seeds `mentor.binaryPath` on the nil→value arrival — 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.
## Work Guidance
+6 -63
View File
@@ -12,72 +12,15 @@ enum AppMetadata {
nonisolated static let tagline = "The Agentic Writing Environment"
}
/// #151: gateless launch — the workspace IS the first frame (the posts scan
/// starts immediately, concurrent with the engine check). The check runs
/// async; the rail pill and mentor header surface the states; provisioning
/// + backup auto-fire on pass.
struct ContentView: View {
@Environment(AppGateState.self) private var gate
/// #48: provisioning failure presents only once the gate sheet has fully
/// dismissed — keying on `gateDismissed` (set in the sheet's onDismiss,
/// which fires at dismissal completion) rather than `!gateRaised` (which
/// flips at dismissal start); macOS can drop a sheet presented during
/// another sheet's dismissal animation.
private var failurePresented: Binding<Bool> {
Binding(
get: { gate.provisioning.hasFailure && gate.gateDismissed },
set: {
if !$0 {
gate.provisioning.deferFailure()
}
},
)
}
var body: some View {
@Bindable var gate = gate
Group {
// #17: post-gate main surface is the workspace shell (nav rail +
// Posts/Sessions/Learnings/Settings). Gate pass hands over the probe's
// winning binary — no re-probe.
if gate.gateModel.currentBinaryPath != nil {
WorkspaceView()
} else {
VStack(spacing: 8) {
Image(systemName: "books.vertical")
.font(.largeTitle)
Text(AppMetadata.name)
.font(.title)
.bold()
Text(AppMetadata.tagline)
.foregroundStyle(.secondary)
}
.padding(32)
}
}
.frame(minWidth: 480, minHeight: 320)
.sheet(isPresented: $gate.gateRaised) {
EngineGateView(
model: gate.gateModel,
onEnginePass: {
// #47: provisioning runs in parallel on pass; idempotent, so re-fires
// are no-ops. Alert UX on failure is #48.
// #50: backup runs after the provision pass finishes — success or
// failure; a failed provision doesn't skip the backup.
Task {
await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath)
await gate.backup.runPass()
}
},
onDismiss: {
gate.gateRaised = false
gate.gateDismissed = true
},
)
}
.sheet(isPresented: failurePresented) {
ProvisioningFailureCard(model: gate.provisioning) {
Task { await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath) }
}
.interactiveDismissDisabled()
}
WorkspaceView()
.task { await gate.startLaunchCheck() }
}
}
-245
View File
@@ -1,245 +0,0 @@
//
// EngineGateView.swift
// Museion
//
// Ceiling note: a pathological all-hang machine holds the checking card up to
// ~N×5 s (per-candidate timeout, ticket #36) — not 5 s total.
//
import SwiftUI
/// The launch Engine gate: one blocking card, three states (tickets #38/#40/#41).
/// Shown once per app-launch over the first window; the sheet never closes itself.
struct EngineGateView: View {
/// Shared app-scoped model — one check per app-launch even if ⌘N opens more windows (#41).
let model: EngineGateModel
/// Fires the moment a check passes — provisioning (#13) starts here, in parallel (ticket #41).
var onEnginePass: (@MainActor @Sendable () -> Void)?
/// Unlock point: pass-card dismissal (ticket #41). The sheet's only exit.
var onDismiss: (@MainActor @Sendable () -> Void)?
var body: some View {
VStack(spacing: 14) {
switch model.phase {
case .idle, .checking:
checkingCard
case let .pass(engineVersion, binaryPath):
passCard(engineVersion: engineVersion, binaryPath: binaryPath)
case let .fail(firstProbePath, stderrExcerpt):
failCard(firstProbePath: firstProbePath, stderrExcerpt: stderrExcerpt)
}
}
.padding(24)
.frame(width: 460)
.onAppear {
model.onPass = onEnginePass
Task { await model.beginAutomaticCheck() }
}
.interactiveDismissDisabled()
}
// MARK: Checking (ticket #41) — spinner, no buttons; per-candidate timeout flips the card to fail
private var checkingCard: some View {
VStack(spacing: 14) {
ProgressView()
.controlSize(.regular)
.padding(.bottom, 2)
Text("Checking the Engine…")
.font(.title3)
Text("Running hermes acp --check")
.font(.callout)
.foregroundStyle(.secondary)
}
}
// MARK: Pass (ticket #40) — check icon, version, explicit dismiss; no re-check
private func passCard(engineVersion: String, binaryPath: String) -> some View {
VStack(spacing: 14) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 30))
.foregroundStyle(.secondary)
Text("Engine ready")
.font(.title3)
Text("Hermes \(engineVersion) answered the health check. The mentor is available.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
Text(binaryPath)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
.lineLimit(1)
.truncationMode(.middle)
Button("Start Writing") {
onDismiss?()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
}
}
// MARK: Fail (ticket #40) — two install steps, re-check, collapsed stderr
private func failCard(firstProbePath: String, stderrExcerpt: String) -> some View {
VStack(spacing: 14) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30))
.foregroundStyle(.orange)
Text("Museion needs its engine")
.font(.title3)
Text("The Hermes engine wasn't found or didn't answer. Museion is paused until it's installed — Passes and Sessions need it.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
installSteps
Button("Re-check") {
Task { await model.runCheck() }
}
.buttonStyle(.borderedProminent)
if !stderrExcerpt.isEmpty {
DisclosureGroup("Technical details") {
VStack(alignment: .leading, spacing: 6) {
Text(stderrExcerpt)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
Text("Probed: \(firstProbePath)")
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
.frame(maxWidth: .infinity, alignment: .leading)
} else {
Text("Probed: \(firstProbePath)")
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
}
}
}
/// Ticket #40: exactly two steps + the docs link. Nothing else.
private var installSteps: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top, spacing: 8) {
Text("1.").monospacedDigit().foregroundStyle(.secondary)
VStack(alignment: .leading, spacing: 4) {
Text(installCommand)
.font(.system(size: 11, design: .monospaced))
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
Button {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(installCommand, forType: .string)
} label: {
Label("Copy", systemImage: "doc.on.doc")
}
.controlSize(.small)
.buttonStyle(.link)
.font(.system(size: 11))
}
}
HStack(alignment: .top, spacing: 8) {
Text("2.").monospacedDigit().foregroundStyle(.secondary)
Text("Come back here and click Re-check.")
}
Link("Installation guide", destination: URL(string: "https://hermes-agent.nousresearch.com/docs")!)
.font(.system(size: 11))
.frame(maxWidth: .infinity)
}
.padding(12)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8))
}
private let installCommand = "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"
}
/// #48: provisioning failure card — separate from the gate, which never re-raises.
/// Presented only after the gate sheet has been dismissed.
struct ProvisioningFailureCard: View {
let model: ProvisioningModel
/// Retry re-runs the whole idempotent pass with the gate's binary (#45).
let onRetry: () -> Void
/// Snapshot taken when the card appears; a successful Retry nils
/// `model.lastFailure` mid-presentation, and reading it live would blank
/// the card during its dismiss animation.
@State private var failure: ProfileProvisioner.Outcome?
var body: some View {
if let failure, case let .failed(profile, phase, excerpt) = failure {
VStack(spacing: 14) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30))
.foregroundStyle(.orange)
Text(phase.rawValue)
.font(.title3)
if let profile {
// #134: the card names the failing profile — with three
// surface profiles, "which one?" is the first question.
Text(profile)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
}
Text("Museion couldn't finish setting up the writing profiles. Nothing is lost — the setup is safe to run again.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
if !excerpt.isEmpty {
DisclosureGroup("Technical details") {
Text(excerpt)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
.frame(maxWidth: .infinity, alignment: .leading)
}
HStack {
Button("Not Now") {
model.deferFailure()
}
.keyboardShortcut(.cancelAction)
Button("Retry") {
onRetry()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
}
}
.padding(24)
.frame(width: 460)
.onAppear(perform: refreshIfNewFailure)
.onChange(of: model.lastFailure) {
refreshIfNewFailure()
}
}
}
/// Refresh only on a new failure — never on clearing, so the card stays
/// rendered until the sheet dismisses it.
private func refreshIfNewFailure() {
if case .failed = model.lastFailure {
failure = model.lastFailure
}
}
}
#Preview {
EngineGateView(model: EngineGateModel())
}
#Preview("provisioning failure") {
ProvisioningFailureCard(
model: ProvisioningModel(),
onRetry: {},
)
}
+393
View File
@@ -0,0 +1,393 @@
//
// EngineStatusView.swift
// Museion
//
// #151 (map #148): the gateless engine-status surfaces — the rail pill
// and the anchored fail card (#149's variant-A verdict, prototype
// prototypes/GatelessStatusPrototype.swift). Quiet when healthy: once the
// engine answered and provisioning finished, nothing renders anywhere.
//
import SwiftUI
/// The pill/card state derivation — pure, test-pinned (#151). The gate's
/// phase machine is the source; a provisioning failure rides the same
/// failed surface under a passed gate.
enum EngineStatusSurface {
enum Visibility: Equatable {
case hidden
case pulsing
case failed
}
static func visibility(phase: EngineGateModel.Phase, provisioningFailed: Bool) -> Visibility {
switch phase {
case .idle: .hidden
case .checking: .pulsing
case .pass: provisioningFailed ? .failed : .hidden
case .fail: .failed
}
}
}
/// #149 variant A: the 44×44 rail slot above Archive — an 8pt pulsing
/// accent dot while checking (no text), the warning glyph on an accent-12%
/// wash when failed, nothing at all once healthy (the slot collapses and
/// the rail spacing closes). Slot click re-opens a collapsed fail card.
struct EngineStatusPill: View {
let visibility: EngineStatusSurface.Visibility
/// Opens the anchored card (only meaningful in the failed state).
var onOpen: () -> Void
var body: some View {
Button(action: onOpen) {
ZStack {
if visibility == .failed {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.accent.opacity(0.12))
}
switch visibility {
case .pulsing:
Circle()
.fill(DesignTokens.accent)
.frame(width: 8, height: 8)
.pulsing()
case .failed:
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 15))
.foregroundStyle(DesignTokens.accent)
case .hidden:
EmptyView()
}
}
.frame(width: 44, height: 44)
}
.buttonStyle(.plain)
.help(helpText)
.accessibilityLabel(helpText)
}
private var helpText: String {
switch visibility {
case .pulsing: "Checking the engine"
case .failed: "Engine problem — click for details"
case .hidden: ""
}
}
}
/// The anchored fail card (#149): 340pt wide, bottom-leading at
/// railWidth + 12 / bottom 14 — surface bg, accent-0.5 border, radius 12,
/// shadow. Floats over content; never blocks, never pushes layout. Engine
/// failure and provisioning failure ride the same shell (#40 copy with the
/// gateless subtitle — nothing pauses).
struct EngineStatusCard: View {
let gate: AppGateState
let onCollapse: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 8) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(DesignTokens.accent)
Text(title)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer()
Button(action: onCollapse) {
Image(systemName: "chevron.down")
.font(.system(size: 10, weight: .semibold))
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.help("Collapse to the pill")
.accessibilityLabel("Collapse to the pill")
}
if case .fail = gate.gateModel.phase {
engineContent
} else {
setupContent
}
}
.padding(16)
.frame(width: 340, alignment: .leading)
.background(DesignTokens.surface, in: RoundedRectangle(cornerRadius: 12))
.overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(DesignTokens.accent.opacity(0.5)))
.shadow(radius: 16, y: 4)
}
private var title: String {
if case .fail = gate.gateModel.phase {
return "Museion needs its engine"
}
return "Setup failed"
}
// MARK: Engine missing (#40 copy, gateless correction)
@ViewBuilder
private var engineContent: some View {
if case let .fail(firstProbePath, stderrExcerpt) = gate.gateModel.phase {
VStack(alignment: .leading, spacing: 12) {
Text(
"The Hermes engine wasn't found or didn't answer. Passes and Sessions need it — the editor keeps working.",
)
.font(.system(size: 12.5))
.foregroundStyle(DesignTokens.muted)
.fixedSize(horizontal: false, vertical: true)
installSteps
recheckRow
technicalDetails(stderrExcerpt: stderrExcerpt, firstProbePath: firstProbePath)
}
}
}
/// Ticket #40: exactly two steps + the docs link. Nothing else.
private var installSteps: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top, spacing: 8) {
Text("1.").monospacedDigit().foregroundStyle(DesignTokens.muted)
VStack(alignment: .leading, spacing: 4) {
Text(installCommand)
.font(.system(size: 11, design: DesignTokens.mono))
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
Button {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(installCommand, forType: .string)
} label: {
Label("Copy", systemImage: "doc.on.doc")
}
.controlSize(.small)
.buttonStyle(.link)
.font(.system(size: 11))
}
}
HStack(alignment: .top, spacing: 8) {
Text("2.").monospacedDigit().foregroundStyle(DesignTokens.muted)
Text("Come back here and click Re-check.")
.font(.system(size: 12))
}
Link("Installation guide", destination: URL(string: "https://hermes-agent.nousresearch.com/docs")!)
.font(.system(size: 11))
}
.padding(12)
.background(DesignTokens.background, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(DesignTokens.border))
}
private let installCommand = "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"
/// Re-check (#149): accent, disabled while checking, label "Checking…".
private var recheckRow: some View {
HStack {
Button {
Task { await gate.gateModel.runCheck() }
} label: {
HStack(spacing: 6) {
if gate.gateModel.phase == .checking {
ProgressView().controlSize(.small)
}
Text(gate.gateModel.phase == .checking ? "Checking…" : "Re-check")
}
.frame(minWidth: 120)
}
.buttonStyle(.borderedProminent)
.tint(DesignTokens.accent)
.disabled(gate.gateModel.phase == .checking)
Spacer()
}
}
/// stderr excerpt + the probed path. Empty stderr keeps the bare
/// Probed line (the not-found case answers nothing).
@ViewBuilder
private func technicalDetails(stderrExcerpt: String, firstProbePath: String) -> some View {
if !stderrExcerpt.isEmpty {
DisclosureGroup("Technical details") {
VStack(alignment: .leading, spacing: 6) {
Text(stderrExcerpt)
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.textSelection(.enabled)
probedLine(firstProbePath)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
} else {
probedLine(firstProbePath)
}
}
private func probedLine(_ firstProbePath: String) -> some View {
Text("Probed: \(firstProbePath)")
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted.opacity(0.7))
}
// MARK: Provisioning failure (#48 reborn, non-modal)
/// Live-reads the model: a successful Retry nils `lastFailure` and the
/// whole surface disappears — no dismiss-animation snapshot needed.
@ViewBuilder
private var setupContent: some View {
if case let .failed(profile, phase, excerpt) = gate.provisioning.lastFailure {
VStack(alignment: .leading, spacing: 12) {
Text(phase.rawValue)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let profile {
// #134: the card names the failing profile — with three
// surface profiles, "which one?" is the first question.
Text(profile)
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted.opacity(0.7))
}
Text(
"Museion couldn't finish setting up the writing profiles. Nothing is lost — the setup is safe to run again.",
)
.font(.system(size: 12.5))
.foregroundStyle(DesignTokens.muted)
.fixedSize(horizontal: false, vertical: true)
HStack {
Button("Retry") {
Task {
await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath)
}
}
.buttonStyle(.borderedProminent)
.tint(DesignTokens.accent)
Spacer()
}
if !excerpt.isEmpty {
DisclosureGroup("Technical details") {
Text(excerpt)
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
}
}
}
}
}
// MARK: - Mentor header states (#151, #149's contract)
/// The mentor pane header's mono-10 engine states, one per gate verdict:
/// "checking the engine…" muted + mini spinner / "engine missing" accent
/// with help / "setup failed" accent / `hermes <base>` once ready. The
/// gate's phase machine is the source; nil gate (previews) derives from
/// the mentor model alone.
struct MentorEngineStatus: View {
let gate: AppGateState?
let model: MentorSessionModel
/// #151: one state per gate verdict (internal — the pure mapping's
/// pins name the cases).
enum EngineState {
case checking
case engineMissing
case setupFailed
case ready
}
/// The gate-driven mapping, pure and test-pinned (#151) — engine
/// failure outranks a lingering provisioning failure (no engine →
/// Retry can't run anyway).
static func state(phase: EngineGateModel.Phase, provisioningFailed: Bool) -> EngineState {
switch phase {
case .idle, .checking: .checking
case .fail: .engineMissing
case .pass: provisioningFailed ? .setupFailed : .ready
}
}
/// No gate (previews): derive from the mentor model alone.
private var state: EngineState {
if let gate {
Self.state(phase: gate.gateModel.phase, provisioningFailed: gate.provisioning.hasFailure)
} else {
model.phase == .idle ? .checking : .ready
}
}
var body: some View {
switch state {
case .checking:
HStack(spacing: 5) {
ProgressView().controlSize(.mini)
Text("checking the engine…")
}
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.layoutPriority(1)
case .engineMissing:
Text("engine missing")
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
.help("Passes and Sessions need the Hermes engine")
case .setupFailed:
Text("setup failed")
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
.help("Profile setup didn't finish — retry from the rail's status card")
case .ready:
// The BASE version (handshake answer first, the gate's derived
// string `+`-stripped meanwhile — the drift-note contract),
// plus the advisory drift note when they diverge.
if !readyVersion.isEmpty {
HStack(spacing: 8) {
Text("hermes \(readyVersion)")
.lineLimit(1)
.truncationMode(.middle)
if let note = model.versionNote {
Text(note)
.help(note)
.foregroundStyle(.orange)
}
}
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(.tertiary)
.layoutPriority(1)
}
}
}
private var readyVersion: String {
if let engineVersion = model.engineVersion {
return engineVersion
}
if case let .pass(version, _)? = gate?.gateModel.phase {
return String(version.prefix(while: { $0 != "+" }))
}
return ""
}
}
/// The checking dot's pulse (#149: 8pt accent dot, pulsing). The
/// repeatForever animation rides the onAppear state flip — a constant
/// animation value never starts.
private struct PulsingModifier: ViewModifier {
@State private var dim = false
func body(content: Content) -> some View {
content
.opacity(dim ? 0.35 : 1)
.animation(.easeInOut(duration: 0.55).repeatForever(autoreverses: true), value: dim)
.onAppear { dim = true }
}
}
private extension View {
func pulsing() -> some View {
modifier(PulsingModifier())
}
}
+43 -16
View File
@@ -16,6 +16,10 @@ struct MentorPaneView: View {
@Environment(\.openWindow) private var openWindow
/// Set post-gate by ContentView: the probe's winning binary (no re-probe).
var binaryPath: String?
/// #151: the app-scoped gate — the header's engine states read the
/// gate's phase machine (nil = previews; the pane then derives from
/// the mentor model alone).
var gate: AppGateState?
/// #24 (S3.1): app-scoped Posts state for the pass bar (nil = no pass
/// surface, previews).
var posts: PostsModel?
@@ -36,12 +40,14 @@ struct MentorPaneView: View {
init(
model: MentorSessionModel,
binaryPath: String?,
gate: AppGateState? = nil,
posts: PostsModel? = nil,
home: URL? = nil,
onOpenSettings: (() -> Void)? = nil,
) {
_model = State(initialValue: model)
self.binaryPath = binaryPath
self.gate = gate
self.posts = posts
self.home = home
self.onOpenSettings = onOpenSettings
@@ -53,8 +59,27 @@ struct MentorPaneView: View {
Divider()
switch model.phase {
case .idle, .starting:
ProgressView("Starting the mentor engine…")
if case .fail? = gate?.gateModel.phase {
// #151: the gateless check answered "no engine" — an
// eternal "Starting…" spinner would lie. The rail card
// carries the install steps.
VStack(spacing: 10) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 24))
.foregroundStyle(DesignTokens.accent)
Text("The Hermes engine is missing")
.font(.system(size: 14, weight: .semibold, design: DesignTokens.serif))
Text("Install steps are one click away at the rail's status icon — the editor keeps working.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
.padding(.horizontal, 24)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
case .ready:
modePicker
if let kind = passKind {
@@ -90,20 +115,28 @@ 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 {
// #151: keyed on binaryPath — the gateless check lands AFTER the
// pane mounts, so re-seeding rides the nil→value arrival and the
// engine spawns the moment the check passes.
.task(id: binaryPath) {
// #28 review: an honest if-let — the ?? self-assignment was a no-op.
if let binaryPath {
model.binaryPath = binaryPath
}
// #137: the Run Pass posture over the pass profiles' keys —
// a no-op without a binaryPath; pane re-entry re-fires this
// task, so a key added in Settings re-enables Run Pass.
// a no-op without a binaryPath; every re-fire of this task
// re-runs it, so a key added in Settings re-enables Run Pass.
await model.refreshPassReadiness()
// 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).
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
await model.openSession()
// #151: openSession with a nil binary would land the crash
// card ("no engine binary path available") — the honest
// missing-engine states own the no-binary interim.
if binaryPath != nil {
await model.openSession()
}
}
}
@@ -115,20 +148,14 @@ struct MentorPaneView: View {
.foregroundStyle(.secondary)
Text("Mentor Session")
.font(.headline)
if let version = model.engineVersion {
Text(version)
.font(.caption)
.foregroundStyle(.tertiary)
}
if let note = model.versionNote {
Text(note)
.font(.caption)
.foregroundStyle(.orange)
.help(note)
}
.fixedSize()
MentorEngineStatus(gate: gate, model: model)
Spacer()
// #137: the transient pass transcript carries no session id — the
// chip stays hidden while a pass run owns the active surface.
// #151: renders only once ready — no live session exists while
// the engine is missing or checking (#149); status text wins
// layout priority.
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId, sessionId != MentorSessionModel.passTranscriptKey {
Text("session \(sessionId.prefix(8))")
.font(.caption2)
+30 -6
View File
@@ -8,8 +8,11 @@
import AppKit
import SwiftUI
/// App-scoped gate state — raised once per app-launch, first window only (ticket #41).
/// The model is shared so ⌘N during the gate can't start a second concurrent check.
/// App-scoped state. #151: gateless — every launch runs the engine check
/// async beside the workspace (`startLaunchCheck` from ContentView.task);
/// provisioning + backup auto-fire on pass. Nothing blocks; the rail pill
/// and mentor header surface the states. The model is shared so ⌘N during
/// a check can't start a second concurrent one (ticket #41's rule).
@MainActor
@Observable
final class AppGateState {
@@ -19,10 +22,6 @@ final class AppGateState {
/// drags are starved by it — field-verified 2026-11-02) routes image
/// drops to the editor through this handle.
let proseDrop = ProseDropBridge()
var gateRaised = true
/// True once the gate sheet's onDismiss fired (dismissal completion, #48) —
/// the provisioning failure card presents only after this.
var gateDismissed = false
let gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
/// #50: daily backup pass, sequenced after provisioning finishes.
@@ -62,6 +61,31 @@ final class AppGateState {
/// (b3daac9: Documents, not the account root; TCC note in ADR-0004).
nonisolated static let defaultMuseionHome = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Documents/Museion", isDirectory: true)
/// #151: the gateless launch check — arms the auto-fire chain, then
/// runs the once-per-launch async check (`beginAutomaticCheck`'s
/// `hasStarted` preserves #41's one-check-per-launch, first-window-only
/// rule; ⌘N re-entry no-ops). Called from `ContentView.task`.
func startLaunchCheck() async {
// Hosted unit tests run this app as their runner — the panes'
// guard pattern: never probe or auto-provision there.
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
wireAutoFire()
await gateModel.beginAutomaticCheck()
}
/// The auto-fire chain — the exact onEnginePass body from the gate era,
/// moved verbatim: provisioning (#47, idempotent — re-fires per passing
/// Re-check are no-ops), then the daily backup (#50 — a failed
/// provision doesn't skip it).
func wireAutoFire() {
gateModel.onPass = { [gateModel, provisioning, backup] in
Task {
await provisioning.runPass(hermesBinary: gateModel.currentBinaryPath)
await backup.runPass()
}
}
}
}
/// #23: no `@main` here — MuseionLauncher (MCPServer.swift) branches
+1
View File
@@ -161,6 +161,7 @@ struct PostsPaneView: View {
MentorPaneView(
model: mentor,
binaryPath: mentorBinaryPath,
gate: gate,
posts: model,
home: home,
onOpenSettings: onOpenSettings,
-5
View File
@@ -631,11 +631,6 @@ final class ProvisioningModel {
lastFailure != nil
}
/// Not Now (#48): defer to the next launch's silent retry.
func deferFailure() {
lastFailure = nil
}
/// One idempotent pass, off the main actor. Guarded against stacking (#45:
/// onPass fires per passing check; a pass already in flight absorbs re-fires).
func runPass(
+30 -6
View File
@@ -23,6 +23,9 @@ struct SessionsPaneView: View {
var binaryPath: String?
/// #29 (S8.3): the Home a kept research note lands in.
var home: URL?
/// #151: the app-scoped gate — the detail column's idle branch reads
/// the gate's fail verdict (nil = previews).
var gate: AppGateState?
/// #30 (S2.7): the staged New Post from Session ask — the editable
/// draft candidate; nil = no sheet. The sheet is pane-local: this pane
/// holds posts + home, so no WorkspaceView staging is needed.
@@ -65,11 +68,13 @@ struct SessionsPaneView: View {
)
}
// Same lazy lifecycle as MentorPaneView: idempotent open — whichever
// surface the writer reaches first spawns the engine.
.task {
if let binaryPath {
model.binaryPath = binaryPath
}
// surface the writer reaches first spawns the engine. #151: keyed
// on binaryPath (nil→value arrival) so the pane spawns the moment
// the gateless check lands; a nil binary never spawns (openSession
// would land the crash card).
.task(id: binaryPath) {
guard let binaryPath else { return }
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 }
@@ -107,8 +112,27 @@ struct SessionsPaneView: View {
private var sessionDetail: some View {
switch model.phase {
case .idle, .starting:
ProgressView("Starting the mentor engine…")
if case .fail? = gate?.gateModel.phase {
// #151: the same honest notice as the Mentor pane — the
// roster stays readable, the detail column never lies with
// an eternal "Starting…" spinner.
VStack(spacing: 10) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 24))
.foregroundStyle(DesignTokens.accent)
Text("The Hermes engine is missing")
.font(.system(size: 14, weight: .semibold, design: DesignTokens.serif))
Text("Install steps are one click away at the rail's status icon — the roster below stays readable.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
.padding(.horizontal, 24)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
case .crashed:
crashedNote
case .ready:
+53
View File
@@ -17,6 +17,10 @@ import SwiftUI
struct WorkspaceView: View {
@Environment(AppGateState.self) private var gate
@State private var selection: Pane = .posts
/// #151: the fail card's expansion — auto-expands on each failure
/// arrival (`.onChange` of the visibility); chevron collapses, slot
/// click re-opens.
@State private var statusCardExpanded = false
enum Pane: Hashable {
case posts
@@ -85,6 +89,24 @@ struct WorkspaceView: View {
}
}
}
// #151: the anchored fail card — floats over content, never
// blocks, never pushes layout (bottom-leading at railWidth + 12,
// bottom 14 — #149's geometry). Fail auto-expands; chevron
// collapses; slot click re-opens. Focus mode recesses the card
// with the rail (chrome recedes for deep work; the pill stays
// hover-reachable, and exiting focus restores the card — the
// expanded state survives).
.overlay(alignment: .bottomLeading) {
if statusVisibility == .failed, statusCardExpanded, !gate.isFocused {
EngineStatusCard(gate: gate) {
statusCardExpanded = false
}
.padding(.leading, DesignTokens.railWidth + 12)
.padding(.bottom, 14)
.transition(.opacity.combined(with: .move(edge: .bottom)))
}
}
.animation(.spring(duration: 0.3), value: statusVisibility)
.background(DesignTokens.background)
// #94: the ONE Origin ask per import batch. Dismissal without an
// answer (Esc/Cancel) drops the batch.
@@ -126,6 +148,15 @@ struct WorkspaceView: View {
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #151: every failure arrival auto-expands the card — a fresh
// engine fail, a provisioning fail landing, a Re-check that fails
// again. Collapse is the reader's call (chevron), re-open the
// slot's.
.onChange(of: statusVisibility) { _, newValue in
if newValue == .failed {
statusCardExpanded = true
}
}
// #92/#94: the editor column lives in Posts — a guest buffer or an
// import's opened post surfaces there, whatever pane was showing.
.onChange(of: gate.posts.externalSession != nil) { _, isUp in
@@ -195,6 +226,15 @@ struct WorkspaceView: View {
)
}
/// #151: the pill/card state — the gate's phase machine plus the
/// provisioning failure verdict.
private var statusVisibility: EngineStatusSurface.Visibility {
EngineStatusSurface.visibility(
phase: gate.gateModel.phase,
provisioningFailed: gate.provisioning.hasFailure,
)
}
@ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View {
@Bindable var gate = gate
@@ -221,6 +261,7 @@ struct WorkspaceView: View {
posts: gate.posts,
binaryPath: gate.gateModel.currentBinaryPath,
home: gate.museionHome,
gate: gate,
)
case .learnings:
// #26: list-only pane over <home>/learnings/ — read side;
@@ -271,6 +312,17 @@ struct WorkspaceView: View {
// #32: Trends after Learnings — measurement beside memory.
RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line")
Spacer()
// #151: the engine-status slot above Archive (#149 variant A) —
// quiet-when-healthy: nothing renders once the engine answered
// and provisioning finished; the slot collapses and the rail
// spacing closes.
if statusVisibility != .hidden {
EngineStatusPill(visibility: statusVisibility) {
if statusVisibility == .failed {
statusCardExpanded = true
}
}
}
// #108: Archive at the rail bottom, above Settings (prototype's
// box icon).
RailButton(pane: .archive, selection: $selection, label: "Archive", systemImage: "archivebox")
@@ -280,6 +332,7 @@ struct WorkspaceView: View {
.padding(.vertical, 8)
.frame(width: DesignTokens.railWidth)
.frame(maxHeight: .infinity)
.animation(.easeInOut(duration: 0.2), value: statusVisibility)
}
}