refactor(settings): provider facts as data
CI / ci (push) Canceled after 0s

#181: ModelProvider is the provider-descriptor table — label, effort
ladder, flagship, endpoint, env var joined by wire dialect (chat/models
paths + the SSE decoder selector), auth mode (Bearer vs Anthropic's
header pair), keyless (nous rides the Portal login), and the ONE
trailing-slash endpoint trim. The probe's URL builders, auth headers,
and stream-decoder picks select by data; the per-dialect bodies and
decoders stay separate functions, not switch clothing.

ProviderCredential.resolve is the ONE credential rail (provider key,
else the shared Portal session key for keyless providers — official
endpoint ONLY, never a user-set URL). Settings' Test Connection and the
new PassReadiness module both call it; the twice-implemented #175
fallback can no longer drift. One deliberate tightening, reviewer-
blessed: a nous pass profile on a custom base_url with no pasted key now
reads missingKey where the old session-model fallback said ready — the
old copy had no endpoint gate at all.

Pass readiness leaves the session model (PassReadiness.swift maps each
pass surface to ready/missingKey/unknown over the descriptor;
MentorSessionModel stores the verdicts and reads no keys or auth
files). runPass and blindRead run their guards through one shared rail
(guardOpenPieceRun) — identical refusal strings, blockers named
honestly. No app-side model-settings store (ADR-0014 red line).

Rider: the #179 mid-pass repoint pin polls the rig's hasHeldPrompt
before releasing the held turn — runningPass flips before the one-shot
engine parks its prompt, so firing into that window false-failed under
parallel-suite load.

Full suite 668/668 (xcresult executed count). Finish-audit: three
reviewers (ponytail/security/general), zero findings above LOW; two
ponytail trims and one pin tightening applied.

Closes #181
This commit is contained in:
AlexKucera committed 2026-11-10 10:58:29 +01:00
1 parent 218e2db397
commit f49e4b6ca0
15 files changed
+506 -184

No files matched your search

+3 -3
View File
@@ -36,14 +36,14 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, construction + Settings repoint; no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` mirrors the guards; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only).
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, construction + Settings repoint; no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only).
- `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID.
- `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
- `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction.
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
- Prose list machinery — `ProseList.swift` (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); `ProseListTextView.swift` — folds are VIEW state (buffer never changes; hidden scopes styled via `foldedAttributes`), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (`rekey`), the newline gate is `\.isNewline` NEVER literal `\n`/`\r` compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through `ProseDropBridge` into `ingestDrop` (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure `dropIndex` (sampling + bracket + binary search; the SwiftUI closure's `location` is unusable under this hosting, off-screen rects return garbage).
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — `ModelProvider` slugs + effort ladders + pinned switch defaults (nous: Portal endpoint, flagship `anthropic/claude-sonnet-5`, Bearer; an unkeyed nous test falls back to the shared Portal session key ONLY on the official https endpoint — the session credential never rides a user-set URL). Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions); 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot).
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
- Focus mode — transient per-launch (no persistence); `FocusChrome` hover zones + overlay panels float over the measure, never push it; `CaretCentering` is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (`ColdTurkeySeat`/`ColdTurkeyDot`) mounts as overlays on the focused branch only.
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
- `AppGateState.museionHome` — fresh installs resolve once and PIN the winner: legacy `~/Documents/Museion` (dir-ness gated) → `<CloudDocs>/Museion` (resolved at the unprefixed path, never a hard-coded `iCloud~` form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched.
@@ -75,7 +75,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored.
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path).
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss).
+22 -61
View File
@@ -282,13 +282,17 @@ final class MentorSessionModel {
/// (firePendingScopeIfRequested); an in-flight transcript is never
/// torn down mid-stream.
private var pendingScopePieceTitle: String?
/// #137: per-pass readiness (refreshPassReadiness, same-file #137
/// extension) + the injectable read seam (tests). Stored in the class
/// body — extensions carry no stored state.
/// #137: per-pass readiness — refreshed at pane entry (re-entry
/// re-fires the pane's .task — the key-added-in-Settings re-enable
/// path). #181: computed in the PassReadiness module over the provider
/// descriptor (the model reads no keys and no auth files); stored here
/// because the pane observes it. `passReadinessWriter` is the
/// injectable read seam (tests).
private(set) var passReadiness: [PassKind: PassReadiness] = [:]
var passReadinessWriter: (any SettingsWriting)?
/// #175: the shared Portal auth store for the nous keyless readiness
/// fallback — injectable so tests never read the machine's real login.
/// #175: the shared Portal auth store — handed to the readiness
/// module's credential resolution; injectable so tests never read the
/// machine's real login.
var portalAuthPath: String = PortalAuth.defaultAuthPath
/// The gate's winning binary path (no re-probe — map decision). Set by
@@ -713,69 +717,26 @@ extension MentorSessionModel {
host.isOneShotRunning
}
/// #137 (S4): the Run Pass posture — is the pass profile's provider
/// keyed? .unknown NEVER blocks (our own read failure — the spawn's
/// honest failure row owns that path); .missingKey names the provider
/// so the pane can say what's missing and link to Settings.
enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
}
// Per-pass readiness (stored in the class body), refreshed at pane
// entry (re-entry re-fires the pane's .task — the key-added-in-
// Settings re-enable path). `passReadinessWriter` is the injectable
// read seam; nil at refresh time → an ad-hoc HermesSettingsWriter
// over the gate's binary (profileRoot default).
// #137 (S4): the Run Pass posture — is the pass profile's provider
// keyed? .unknown NEVER blocks (our own read failure — the spawn's
// honest failure row owns that path); .missingKey names the provider
// so the pane can say what's missing and link to Settings.
// #181: the enum and the refresh live in the PassReadiness module.
func readiness(for kind: PassKind) -> PassReadiness {
passReadiness[kind] ?? .unknown
}
/// Read each pass profile's provider (readSurface, one task group),
/// then each DISTINCT provider's key (readProviderKey). A surface we
/// can't read maps .unknown; a non-empty key maps .ready; no key maps
/// .missingKey with the provider's label. No binaryPath and no
/// injected writer → readiness stays empty (.unknown everywhere).
/// #181: thin delegate — the reads and the keyless fallback live in
/// the PassReadiness module over the provider descriptor. No
/// binaryPath and no injected writer → readiness stays empty
/// (.unknown everywhere).
func refreshPassReadiness() async {
guard let writer = passReadinessWriter ?? binaryPath.map({ HermesSettingsWriter(hermesBinary: $0) }) else { return }
var providers: [ProfileSurface: ModelProvider] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in [ProfileSurface.pass1, .pass2] {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
providers[surface] = read?.config.provider
}
}
var keys: [ModelProvider: String] = [:]
for provider in Set(providers.values.compactMap(\.self)) {
var key = await (try? writer.readProviderKey(provider: provider)) ?? ""
// #175: nous runs on the shared Portal login — an empty `.env`
// key is not a blocker when the session's agent_key exists (the
// engine's own credential; API key and subscription bill the
// same account credits).
if provider == .nous, key.isEmpty {
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
}
keys[provider] = key
}
for surface in [ProfileSurface.pass1, .pass2] {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let provider = providers[surface] else {
passReadiness[kind] = .unknown
continue
}
if let key = keys[provider], !key.isEmpty {
passReadiness[kind] = .ready
} else {
passReadiness[kind] = .missingKey(providerLabel: provider.label)
}
}
passReadiness = await PassReadiness.refresh(
writer: writer,
portalAuthPath: portalAuthPath,
)
}
/// Send a prompt and stream the reply into the ACTIVE session's
+79
View File
@@ -0,0 +1,79 @@
//
// PassReadiness.swift
// Museion
//
// ## Scenario: pass readiness over the provider descriptor
// From #181
//
// Given the pass profiles' providers read through the settings seam
// When pass readiness refreshes
// Then each pass surface maps to ready / missingKey / unknown through the
// ONE credential resolution (provider key, else the Portal session key
// for keyless providers) — the session model stores the verdicts and
// itself reads no keys and no auth files.
import Foundation
/// #181: per-pass readiness — ready / missingKey / unknown, computed
/// over the provider descriptor. Formerly the session model's #137
/// nested enum: the profile reads (surface provider, `.env` key, Portal
/// auth store) live HERE now; MentorSessionModel stores the verdicts its
/// pane observes.
nonisolated enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
/// Read each pass surface's provider (readSurface, one task group),
/// then resolve each DISTINCT provider's credential through the ONE
/// rail (ProviderCredential — provider key, else the Portal session
/// key for keyless providers). A surface we can't read maps .unknown
/// (our own read failure never blocks — the spawn's honest failure row
/// owns that path); a refused credential maps .missingKey naming the
/// provider. Nil/empty `base_url` means the provider's default family
/// (the family the session key is allowed to ride).
static func refresh(
writer: any SettingsWriting,
portalAuthPath: String,
) async -> [PassKind: PassReadiness] {
let surfaces = [ProfileSurface.pass1, .pass2]
var reads: [ProfileSurface: (config: SurfaceModelConfig, baseURL: String?)] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in surfaces {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
if let read {
reads[surface] = read
}
}
}
var envKeys: [ModelProvider: String] = [:]
for provider in Set(reads.values.map(\.config.provider)) {
envKeys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? ""
}
var verdicts: [PassKind: PassReadiness] = [:]
for surface in surfaces {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let read = reads[surface] else {
verdicts[kind] = .unknown
continue
}
let provider = read.config.provider
let endpoint = read.baseURL.flatMap { $0.isEmpty ? nil : $0 } ?? provider.defaultEndpoint
switch await ProviderCredential.resolve(
provider: provider,
envKey: envKeys[provider] ?? "",
endpoint: endpoint,
portalAuthPath: portalAuthPath,
) {
case .key:
verdicts[kind] = .ready
case .refused:
verdicts[kind] = .missingKey(providerLabel: provider.label)
}
}
return verdicts
}
}
+48 -54
View File
@@ -11,6 +11,50 @@ import Foundation
// MARK: Pass orchestration (#24, S3.1)
// MARK: #181: the ONE guard rail behind runPass and blindRead
extension PostsModel {
/// #181: the shared guard grammar every engine run passes before it
/// touches anything — nothing already running (a pass or a Blind
/// Read, named honestly whichever runner asks), the mentor not
/// mid-reply with its engine ready, and an open SAVED piece (never a
/// draft, the external guest, or a held #111 guard ask). The refusal
/// lands in lastError naming the blocker; answers the open piece's id
/// and session — the run's target — or nil (refused).
func guardOpenPieceRun(
_ action: String,
mentor: MentorSessionModel,
) -> (id: String, session: EditorSession)? {
guard runningPass == nil else {
lastError = "A pass is already running."
return nil
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return nil
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return nil
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return nil
}
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run \(action)."
return nil
}
return (id, session)
}
}
extension PostsModel {
/// #24 (S3.1): run one structured critique pass over the OPEN piece.
/// The pre-pass snapshot lands before the engine sees the text; the
@@ -20,38 +64,14 @@ extension PostsModel {
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, mentor: MentorSessionModel) async {
guard runningPass == nil, !runningBlindRead else {
lastError = "A pass is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
guard let (id, session) = guardOpenPieceRun("a pass", mentor: mentor) else { return }
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings, BEFORE the open-piece guard so nothing writes
// to disk (not even the pre-pass snapshot).
// point at Settings. Nothing has touched disk yet (the snapshot
// comes after this guard).
if case let .missingKey(label) = mentor.readiness(for: kind) {
lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys."
return
}
// The pass targets the open Piece: a never-saved draft has no
// folder, and the external guest and a held #111 guard ask are
// not Pieces.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a pass."
return
}
guard flushOrAbort(id) else { return } // the engine reads disk
// #179: the model owns the Home; an open piece implies a bound one.
guard let home = watchedHome else { return }
@@ -117,33 +137,7 @@ extension PostsModel {
/// the transient transcript and die with it. The writer stays judge of
/// record.
func blindRead(mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// Same open-piece rule as a pass: the read judges ONE saved piece.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a Blind Read."
return
}
guard let (id, session) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return }
guard flushOrAbort(id) else { return }
// #179: the model owns the Home; an open piece implies a bound one.
guard let home = watchedHome,
+18 -22
View File
@@ -142,24 +142,19 @@ nonisolated enum ProviderProbe {
/// Responses API (`/v1/responses`, 2026-10-28 maintainer correction —
/// chat-completions is the retired path). Nous (#175, live-probed
/// 2026-11-05) is plain OpenAI chat-completions on a versioned base.
/// A trailing slash on a hand-edited endpoint never doubles up. A
/// non-URL endpoint is nil (URL(string:) happily percent-encodes "not a
/// url" — the scheme check is what actually rejects garbage; probe
/// reports unreachable, never traps).
/// #181: the paths live on the descriptor's dialect — a trailing slash
/// on a hand-edited endpoint never doubles up. A non-URL endpoint is
/// nil (URL(string:) happily percent-encodes "not a url" — the scheme
/// check is what actually rejects garbage; probe reports unreachable,
/// never traps).
static func chatURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
let path = switch provider {
case .anthropic: "/v1/messages"
case .openaiAPI: "/responses"
case .zai, .nous: "/chat/completions"
}
return httpURL(base + path)
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.chatPath)
}
static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
let path = provider == .anthropic ? "/v1/models" : "/models"
return httpURL(base + path)
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.modelsPath)
}
private static func httpURL(_ string: String) -> URL? {
@@ -172,14 +167,15 @@ nonisolated enum ProviderProbe {
/// Bearer everywhere except Anthropic: `x-api-key` + a pinned
/// `anthropic-version` (factsheet §2.1 — never send none). Nous rides
/// Bearer too — the portal accepts the session agent_key and an API
/// key interchangeably (#175).
/// key interchangeably (#175). #181: the shape keys off the
/// descriptor's auth mode.
static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
switch provider {
case .zai, .openaiAPI, .nous:
switch provider.authMode {
case .bearer:
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
case .anthropic:
case let .headerKey(version):
request.setValue(key, forHTTPHeaderField: "x-api-key")
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
request.setValue(version, forHTTPHeaderField: "anthropic-version")
}
}
@@ -255,10 +251,10 @@ nonisolated enum ProviderProbe {
return failure
}
let (text, finish): (String, String?)
switch provider {
switch provider.dialect {
case .anthropic: (text, finish) = anthropicStream(events)
case .openaiAPI: (text, finish) = responsesStream(events)
case .zai, .nous: (text, finish) = chatCompletionsStream(events)
case .responses: (text, finish) = responsesStream(events)
case .chatCompletions: (text, finish) = chatCompletionsStream(events)
}
if !text.isEmpty {
return .works(latencyMS: latencyMS, modelCount: modelCount)
+130 -36
View File
@@ -89,6 +89,78 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
case .nous: "NOUS_API_KEY"
}
}
/// #181: the wire family the probe speaks. The SELECTOR is data —
/// endpoint paths, auth shape, and the SSE decoder pick ride the
/// dialect; the per-family code (request bodies, stream decoders)
/// stays separate functions, not switch clothing.
nonisolated enum Dialect: Sendable {
/// Anthropic `/v1/messages`, header-key auth, Anthropic SSE.
case anthropic
/// OpenAI Responses `/responses`, Bearer, Responses SSE.
case responses
/// OpenAI chat-completions (`/chat/completions` — z.ai and the
/// Nous Portal), Bearer, chat-completions SSE.
case chatCompletions
/// The chat-call path appended to the endpoint base (callers trim
/// a trailing slash off the base first).
var chatPath: String {
switch self {
case .anthropic: "/v1/messages"
case .responses: "/responses"
case .chatCompletions: "/chat/completions"
}
}
var modelsPath: String {
switch self {
case .anthropic: "/v1/models"
case .responses, .chatCompletions: "/models"
}
}
}
/// #181: the provider's wire family (the probe's dialect selector).
var dialect: Dialect {
switch self {
case .zai, .nous: .chatCompletions
case .anthropic: .anthropic
case .openaiAPI: .responses
}
}
/// #181: the auth-header shape (factsheet §2.1) — Bearer everywhere
/// except Anthropic's `x-api-key` + a pinned `anthropic-version`
/// (never send none).
nonisolated enum AuthMode: Sendable {
/// `Authorization: Bearer <key>`.
case bearer
/// `x-api-key: <key>` plus the pinned version header.
case headerKey(version: String)
}
var authMode: AuthMode {
switch self {
case .zai, .openaiAPI, .nous: .bearer
case .anthropic: .headerKey(version: "2023-06-01")
}
}
/// #175: keyless providers run on the shared Hermes Portal login —
/// the engine's own credential stands in when no API key is pasted
/// (API key and subscription bill the same account credits).
var keyless: Bool {
self == .nous
}
/// The endpoint with any trailing slash trimmed — the ONE
/// normalization every endpoint consumer (the probe's URL builders,
/// the credential rail's official-endpoint gate) compares against;
/// divergent trims would gate or route differently in silence.
nonisolated static func trimmedEndpoint(_ endpoint: String) -> String {
endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
}
}
nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable {
@@ -169,6 +241,44 @@ nonisolated enum PortalAuth {
}
}
/// #181: THE credential resolution — the provider's own API key, else the
/// shared Portal session key for keyless providers. Settings' Test
/// Connection and pass readiness both call this ONE function, so the
/// fallback can no longer drift between them. The implicit session
/// credential only ever rides the OFFICIAL endpoint (#175 finish-audit:
/// cleartext http / foreign host = silent exfiltration with no on-screen
/// cue) — a keyless provider on any other endpoint refuses with the
/// paste-a-key path. Nonisolated async, so the auth-store read never runs
/// on the main actor.
nonisolated enum ProviderCredential {
enum Resolved: Equatable {
case key(String)
case refused(String)
}
static func resolve(
provider: ModelProvider,
envKey: String,
endpoint: String,
portalAuthPath: String,
) async -> Resolved {
if !envKey.isEmpty {
return .key(envKey)
}
guard provider.keyless else {
return .refused("no API key set — paste the key first")
}
let trimmed = ModelProvider.trimmedEndpoint(endpoint)
guard trimmed == provider.defaultEndpoint else {
return .refused("custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)")
}
guard let sessionKey = PortalAuth.sessionKey(authJSONPath: portalAuthPath) else {
return .refused("no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`")
}
return .key(sessionKey)
}
}
/// The Settings page's state (#135): per-surface model configs, per-provider
/// keys, the registry the model combobox reads, and the write path every
/// committed change flows through. #136: hydrated from the profiles at pane
@@ -367,46 +477,30 @@ final class SettingsModel {
/// One probe per provider over the CURRENT key/endpoint state. Guarded
/// against stacking; the empty-key precondition makes an unkeyed probe
/// fail fast without touching the network. #175: an unkeyed NOUS probe
/// falls back to the shared Portal session key — the engine's own
/// credential — and names the login path when neither exists.
/// fail fast without touching the network. #181: the credential —
/// provider key, else the shared Portal session key for keyless
/// providers — resolves through the ONE rail pass readiness also calls.
func testConnection(for provider: ModelProvider) async {
guard testStates[provider] != .running else { return }
testStates[provider] = .running
var key = keyConfig(for: provider).apiKey
if provider == .nous, key.isEmpty {
// Finish-audit #175: the session agent_key is an IMPLICIT
// credential (never pasted, field reads empty) — it only ever
// rides the official https endpoint, never a hand-edited one
// (cleartext http / foreign host = silent exfiltration with no
// on-screen cue). Custom endpoints get the paste-a-key refusal.
let endpoint = keyConfig(for: .nous).endpoint
let trimmed = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
guard trimmed == ModelProvider.nous.defaultEndpoint else {
testStates[provider] = .done(.authFailed(
"custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)",
))
return
}
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
if key.isEmpty {
testStates[provider] = .done(.authFailed(
"no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`",
))
return
}
}
let config = ProviderProbe.Config(
let keyConfig = keyConfig(for: provider)
switch await ProviderCredential.resolve(
provider: provider,
endpoint: keyConfig(for: provider).endpoint,
apiKey: key,
model: probeModel(for: provider),
)
let transport = probeTransport
testStates[provider] = await .done(ProviderProbe.probe(config, transport: transport))
envKey: keyConfig.apiKey,
endpoint: keyConfig.endpoint,
portalAuthPath: portalAuthPath,
) {
case let .key(key):
let config = ProviderProbe.Config(
provider: provider,
endpoint: keyConfig.endpoint,
apiKey: key,
model: probeModel(for: provider),
)
testStates[provider] = await .done(ProviderProbe.probe(config, transport: probeTransport))
case let .refused(message):
testStates[provider] = .done(.authFailed(message))
}
}
/// The model the probe proves generation on: the first surface on this
+2 -1
View File
@@ -251,10 +251,11 @@ private struct ProviderKeyBlock: View {
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
if provider == .nous {
if provider.keyless {
// #175: the engine auths nous through hermes' own Portal
// login (device-code, shared across profiles) — the key
// field is optional and bills the same account credits.
// #181: keyed off the descriptor, like every provider fact.
Text(
"Chats ride your Hermes Portal login — no key needed once hermes is signed in (hermes auth add nous). "
+ "A pasted key bills the same account credits (API or subscription).",