diff --git a/AGENTS.md b/AGENTS.md index 4a236df..52eeea9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6356 symbols, 27823 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (6377 symbols, 27886 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -201,6 +201,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-05 | [20261105-issue175-nous-portal-provider_log.md](docs/devlog/20261105-issue175-nous-portal-provider_log.md) | | 2026-11-05 | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](docs/devlog/20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) | | 2026-11-04 | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](docs/devlog/20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) | | 2026-11-04 | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](docs/devlog/20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) | @@ -210,6 +211,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md) | | 2026-11-04 | [20261104-issue160-cold-turkey-contract-render_log.md](docs/devlog/20261104-issue160-cold-turkey-contract-render_log.md) | | 2026-11-04 | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](docs/devlog/20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) | -| 2026-11-04 | [20261104-issue155-shared-conversation-surface-editorial-voice_log.md](docs/devlog/20261104-issue155-shared-conversation-surface-editorial-voice_log.md) | -| 2026-11-03 | [20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md](docs/devlog/20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 293d6aa..03e9116 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **settings:** Nous Portal as a fourth provider (#175) — Settings offers `nous` (hermes' own slug) on every surface and the Provider Keys page: endpoint `https://inference-api.nousresearch.com/v1`, env `NOUS_API_KEY`, the 5-level OpenAI-compatible effort ladder, and switch flagship `anthropic/claude-sonnet-5` (live-probed: the portal's docs-listed Hermes-4 ids 404 — the inference API serves the OpenRouter catalog, 385 vendor-prefixed ids, so the switch keeps the app's sonnet posture billed through Nous). Test Connection speaks plain OpenAI chat-completions (Bearer, `/chat/completions` + `/models`, the 512 cap — no z.ai thinking knobs) and an unkeyed test falls back to the shared Portal session's agent_key from `~/.hermes/auth.json` — the engine's own credential, since hermes' nous runtime is OAuth-only and a portal API key and subscription bill the same account credits. The implicit session key only ever rides the official https endpoint: a hand-edited endpoint with an empty key refuses pre-network (paste-a-key), and no key + no login names `hermes auth add nous`. Pass readiness rides the same fallback (a logged-in Portal machine reads .ready with no key — Run Pass no longer demands a key the feature says isn't needed; finish-audit HIGH). A pasted key still lands in all three profiles' `.env` as future-proofing — a later hermes release honoring `NOUS_API_KEY` for inference lights up with zero Museion changes. +8 tests (dialect, bare-envelope 404/401 decode, session-key fallback, custom-endpoint refusal, keyless readiness) with a flip-verified pair (both guards deleted → exactly the two new pins fail). Suite 635 (issue #175) + - **mentor:** The VOICE payload (#58, wayfinder map #56) — Sandeep Swadia's VOICE framework distilled into the bundled skill set: new skill `owned-insight` (Owned + Insightful bound as one — fingerprints with the Cornell homogenization evidence, pseudo-profundity, the so-what test, the belief-difference frame; drill example; QRC), the retelling-test card in reader-psychology (child-simple restatement — the Pass plays the source's independent reader), the earn-the-next-line card in prose-craft's new Engagement section (diagnoses absent tension, never manufactures it — the source's craft ceiling), and the interview-me-first stance in session-persona (the verbatim four untouched). `owned-insight` joins the #133 allocation on all three surfaces (P1 10 · P2 9 · Chat 11), rides seed-manifest, fires as FC-11 in the sample Pass, and lands as PRD G14. Verified stays with S8's research rail; the five pitfalls dissolve into existing coverage. Suite 574 (issues #56–#58) ### Changed diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 258984d..5383fcb 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -40,7 +40,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus. - Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **#142 paragraph-scoped fold maintenance:** a `shouldChangeText` override records the last accepted single-line edit (range + UTF-16 delta, `pendingPlainEdit`); `refreshFolds` routes it to the in-place re-key (`rekey` — pure, `RekeyOutcome`: survivors shifted by delta, marker-line edits kill the fold and return the scope for un-hiding, scope-interior edits grow/shrink it and flag the edited line for re-hide + caret park) — no parents rescan, no `setAttributedString` swap. The single-line gate is `\.isNewline`, never a literal `"\n"`/`"\r"` compare — `"\r\n"` is ONE grapheme equal to neither, and a CRLF-carrying edit must reach the full pass (finish-audit pin); `apply()` nulls `pendingPlainEdit` outright — structural edits reshape blocks even when the replacement is single-line (a childless unterminated block's outdent; finish-audit pin, `performOutdent` internal for it). A font probe at each survivor's scope head guards the path: hidden styling still present, else fall back to the full pass (wholesale restyles like the fence-flip self-heal this way); dead-scope un-hides are bounds-hardened at the sink. Full pass stays for structural edits, wholesale loads, and toggleFold. `Fold` carries the hidden `scope` (shift-maintained; the full pass re-derives it). **Chrome rendering (#115 field findings, #142 rework):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render as one TINY per-glyph CALayer (contents = a small flipped NSImage raster, `isGeometryFlipped` on the overlay layer so sublayer frames speak lineRect's top-left y) in the click-through `ProseChromeView` overlay (deferred one main-queue tick past textDidChange) — NEVER a document-sized bitmap (~35M pixels per keystroke on a tall doc, #142/F2); glyph rasters are cached by string (`chromeGlyphImages` — 50k parents share a handful of images; layers stay unculled because scroll fires no refresh, ponytail-noted); an edit at/after every parent line skips the rebuild outright (`parentsUnmoved`), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting. **#141 illustration ingest:** window-level SwiftUI `.dropDestination`s STARVE every deeper drag destination — an NSTextView registered for `.fileURL` never received one callback, and a nested editor-level SwiftUI destination never fired either, while `WorkspaceView`'s #91 window destination claimed every drag (green copy badge, silent refusal; field-verified 2026-11-02 via stderr tracing — the docs' nested/innermost-first destination model does NOT hold; one window-level target is the whole routing surface). Routing inside its perform: a PURE-markdown set (`allSatisfy` — a mixed md+image set falls through and refuses loudly, finish-audit 2026-11-02; images must not vanish silently behind the md) forwards through `openExternal` (#91's open-as-guest preserved), everything else bridges through `ProseDropBridge` (app-scoped on `AppGateState.proseDrop`, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) into `ProseListTextView.ingestDrop(_:)`: gates = non-nil `ingestFolder` (saved posts only — drafts/guests get the strip) + every file publishable (#34's `Micropub.mimeType` set; mixed md+image refuses too), then copies each URL via `PostStore.ingestImage` and inserts the joined `illustrationRef`s at the drop point. The source must be a PLAIN file — a dropped symlink refuses (`IngestError.isLink`: `copyItem` would land the LINK itself and the #34 rail would refuse the whole send; finish-audit 2026-11-02, empirically verified), a Finder folder with an image extension refuses (`isFolder`); collisions ride `FixCardStore.uniqueFile` (`-2`/`-3`, the research-note helper — no bespoke loop). Drop-point mapping (the hard-won part, #115's family): the SwiftUI closure's `location` is UNUSABLE under this hosting; the pointer's screen position (`NSEvent.mouseLocation`) maps to an index via `firstRect(forCharacterRange:)` — its y is bottom-up screen coords like the mouse (no flip), non-contiguous layout makes OFF-SCREEN characters return garbage rects (whole-doc searches converge on the layout boundary), so `dropIndex(length:targetY:bandMinY:bandMaxY:rectY:)` — a `nonisolated static` PURE function (pinned by tests without a window) — SAMPLES the document (512 points), keeps only rects inside the viewport band (plain NSView geometry), brackets the drop between two in-band samples, binary-searches the bracket; a pointer above every in-band sample clamps to the first visible char, below all to the last in-band sample, no in-band evidence to 0 (never the old silent index-0-on-garbage), then slides the index to the next whitespace gap (never splices inside a word or an existing ref; dogfood-verified 2026-11-02, landing within one line). `alt` selected (offset +2, length 3) and scrolled to, with `CaretCentering.syncTypewriterInset` re-synced after the edit — without it the typewriter inset is stale and the editor freezes scrolling until the next keypress; one shouldChangeText step = one undo, didChangeText driving the coordinator (reattribute + session.edit + folds); refusals land in the transient `showIngestNotice` strip (mono-11 rust pill pinned to the scroll view's top-center, auto-hide ~4 s), multi-image ingest is non-atomic by design (ponytail comment). Outline surfaces have no ProseTextView → the bridge is nil → image drags bounce (AC4), markdown forwards. Reading mode swaps the surface away — no editor drop target while reading. -- Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). **#136:** `ModelRegistry` (the lenient `~/.hermes/provider_models_cache.json` load, memoized via `loadedDefault`) lives here — the combobox's own data source. `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models, `ZaiKeyType` endpoint families, `SettingsModel` (@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders), `hydrate()` reads each profile's model block IN PARALLEL through the writer's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending write task — 2026-10-28 audit fix, no mid-hydrate stomp); reads only — hydrate never writes), `testConnection(for:)` runs the probe per provider (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectable `writeDebounce`, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach `.env`; tests pass 0); `awaitPendingWrites()` is the tests' sync point; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset ` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are ignored by hermes for other providers — and pre-lands for any later provider switch; var names from hermes' own registry, `ModelProvider.envVarName`: GLM_API_KEY/ANTHROPIC_API_KEY/OPENAI_API_KEY; foreign lines preserved byte-for-byte via pure `upsertEnv`; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pasted `key\nOTHER_VAR=x` is an env-file injection — the error rides `lastWriteError`); an `NSLock` serializes the read→upsert→write across concurrent cross-provider key writes (the same three files — a racing last writer would drop the other's var); 0600 — hermes' own .env posture; an EMPTY key leaves `.env` alone — the field sets, never removes; the zai `model.base_url` write-through rides only the profiles on zai — `profiles` is that target list, not the .env list), `readSurface` hydrates via `config get` ×4 (provider/model/effort/base_url) and `readProviderKey` reads each provider's var back (first non-empty across the three `.env` files) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main inside `Task.detached`; secrets never ride argv and never reach `lastWriteError`; `hermesBinary` nil (pre-gate) refuses writes honestly. `ProviderProbe.swift` — Test Connection (factsheet §4, live-probed wire shapes 2026-10-27, corrected 2026-10-28 after dogfood): step 1 `GET /models` (key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — **every request carries `Content-Type: application/json`** (the 2026-10-28 live incident: without it URLSession defaults to form-urlencoded — z.ai answers HTTP 200 with an error envelope, OpenAI can't parse the body at all; curl set it, the app didn't, Anthropic tolerated it); zai pins the stable GLM wire (`thinking:enabled`+`reasoning_effort:low`) at `{endpoint}/chat/completions`; **OpenAI speaks the RESPONSES API** (`{endpoint}/responses`, `input` + `max_output_tokens` — maintainer correction 2026-10-28, chat-completions is the retired path); Anthropic posts `{endpoint}/v1/messages` (`max_tokens` required) authing via `x-api-key` + pinned `anthropic-version` 2023-06-01, never Bearer; the token cap is **512** (`probeTokenCap` — the live tail proved 64 starves reasoning models: glm-5.3 burned 64/64 on thinking, finish=length, zero content); decode is honest per the factsheet envelopes — zai `error.code` 1113 → wrongKeyType, 401s → authFailed (Anthropic detail carries `request_id`), transport errors → unreachable, `finish=length`/`max_tokens`/`incomplete` + empty content → starved, an empty 200 → requestFailed, and **errors riding a 2xx decode as the provider error** (z.ai's 200-carried content-type envelope live-probed; OpenAI nests it under `response.error`); `works` carries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); the `Transport` closure is injectable (production buffers the streamed response over URLSession); URL builders are nil-safe (a garbage endpoint reads unreachable, never traps). The Provider Keys page carries a per-provider **Test Connection** button + one-line verdict (`TestConnectionResult`: accent "✓ works · N ms · N models" / orange decoded failures). DesignTokens gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480. **#137 (S4):** `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures); `SettingsPaneView` takes the closure and WorkspaceView wires it to `gate.mentor.requestRestart()`, so a committed Chat model change restarts the resident engine in place (deferred to turn end while streaming, slice A's API). +- Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship; **#175:** the nous block carries the Portal note — chats ride the hermes Portal login, a pasted key bills the same account credits, `hermes auth add nous` signs in). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). **#136:** `ModelRegistry` (the lenient `~/.hermes/provider_models_cache.json` load, memoized via `loadedDefault`) lives here — the combobox's own data source. `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models (**#175 adds `nous` — Nous Portal: endpoint `https://inference-api.nousresearch.com/v1`, env `NOUS_API_KEY`, switch flagship `anthropic/claude-sonnet-5` keeping the app's sonnet posture — the portal's catalog is the vendor-prefixed router list, live-probed; ladder = the 5-level OpenAI-compatible set hermes clamps nous to; engine auth rides the hermes Portal login, API key and subscription bill the same account credits), `ZaiKeyType` endpoint families, `SettingsModel` (@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders), `hydrate()` reads each profile's model block IN PARALLEL through the writer's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending write task — 2026-10-28 audit fix, no mid-hydrate stomp); reads only — hydrate never writes), `testConnection(for:)` runs the probe per provider (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network; **#175:** an unkeyed NOUS test falls back to `PortalAuth.sessionKey` — the shared `~/.hermes/auth.json` device-code agent_key read off-main, the engine's own nous credential — and names `hermes auth add nous` when neither key nor login exists; **the fallback fires only on the official https endpoint** — a hand-edited nous endpoint with an empty key refuses pre-network ("paste an API key"): the implicit session credential never rides a user-set URL, cleartext http included; `probeTransport`/`portalAuthPath` are injectable init params so the fallback tests run offline), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectable `writeDebounce`, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach `.env`; tests pass 0); `awaitPendingWrites()` is the tests' sync point; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset ` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are ignored by hermes for other providers — and pre-lands for any later provider switch; var names from hermes' own registry, `ModelProvider.envVarName`: GLM_API_KEY/ANTHROPIC_API_KEY/OPENAI_API_KEY; foreign lines preserved byte-for-byte via pure `upsertEnv`; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pasted `key\nOTHER_VAR=x` is an env-file injection — the error rides `lastWriteError`); an `NSLock` serializes the read→upsert→write across concurrent cross-provider key writes (the same three files — a racing last writer would drop the other's var); 0600 — hermes' own .env posture; an EMPTY key leaves `.env` alone — the field sets, never removes; the zai `model.base_url` write-through rides only the profiles on zai — `profiles` is that target list, not the .env list), `readSurface` hydrates via `config get` ×4 (provider/model/effort/base_url) and `readProviderKey` reads each provider's var back (first non-empty across the three `.env` files) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main inside `Task.detached`; secrets never ride argv and never reach `lastWriteError`; `hermesBinary` nil (pre-gate) refuses writes honestly. `ProviderProbe.swift` — Test Connection (factsheet §4, live-probed wire shapes 2026-10-27, corrected 2026-10-28 after dogfood): step 1 `GET /models` (key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — **every request carries `Content-Type: application/json`** (the 2026-10-28 live incident: without it URLSession defaults to form-urlencoded — z.ai answers HTTP 200 with an error envelope, OpenAI can't parse the body at all; curl set it, the app didn't, Anthropic tolerated it); zai pins the stable GLM wire (`thinking:enabled`+`reasoning_effort:low`) at `{endpoint}/chat/completions`; **OpenAI speaks the RESPONSES API** (`{endpoint}/responses`, `input` + `max_output_tokens` — maintainer correction 2026-10-28, chat-completions is the retired path); Anthropic posts `{endpoint}/v1/messages` (`max_tokens` required) authing via `x-api-key` + pinned `anthropic-version` 2023-06-01, never Bearer; **nous (#175, live-probed 2026-11-05) speaks PLAIN OpenAI chat-completions** (`{endpoint}/chat/completions`, `messages` + the 512 cap, NO thinking knobs — the portal is a router: `/models` answers ~385 vendor-prefixed ids) with Bearer auth — a pasted key OR the shared Portal session's agent_key both work; error decode falls back to a bare root `message` (the portal's `{status, message}` envelope carries no error object — a bad model id answers 404 + message, and `Hermes-4.3-36B`-style docs ids 404: the catalog is the router list, so the switch flagship is `anthropic/claude-sonnet-5`); the token cap is **512** (`probeTokenCap` — the live tail proved 64 starves reasoning models: glm-5.3 burned 64/64 on thinking, finish=length, zero content); decode is honest per the factsheet envelopes — zai `error.code` 1113 → wrongKeyType, 401s → authFailed (Anthropic detail carries `request_id`), transport errors → unreachable, `finish=length`/`max_tokens`/`incomplete` + empty content → starved, an empty 200 → requestFailed, and **errors riding a 2xx decode as the provider error** (z.ai's 200-carried content-type envelope live-probed; OpenAI nests it under `response.error`); `works` carries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); the `Transport` closure is injectable (production buffers the streamed response over URLSession); URL builders are nil-safe (a garbage endpoint reads unreachable, never traps). The Provider Keys page carries a per-provider **Test Connection** button + one-line verdict (`TestConnectionResult`: accent "✓ works · N ms · N models" / orange decoded failures). DesignTokens gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480. **#137 (S4):** `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures); `SettingsPaneView` takes the closure and WorkspaceView wires it to `gate.mentor.requestRestart()`, so a committed Chat model change restarts the resident engine in place (deferred to turn end while streaming, slice A's API). - Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. **#162 (Cold Turkey S2, map #158):** the chrome lineage grows the lock — `ColdTurkeySeat` (one bottom-center seat: the arm-bar before Start, the live readout while locked, the completion note fading ~6 s; the arm-bar carries a chip that BLENDS into the focus ground — 2026-11-04 dogfood amendment: the ground's own color + the faintest token hairline, no shadow, because the bare seat let the document text show through; readout + note stay bare mono; readout = numerals + 2px hairline, terracotta numerals inside the last 20 %, piece title absent; the arm value is directly typeable — parsed and clamped at every read — with ± steppers for coarse moves; defaults 250 words / 5 min, ranges 1…1000 words / 1…60 min — what's typed is what arms, the 2026-11-04 dogfood amendments; the readout and completion note carry the same blending chip) and `ColdTurkeyDot` (the persistent muted pip bottom-right, label on hover, click opens the arm-bar — hidden while the bar is up, a block runs, or nothing prose is open). The arm-bar's Esc = a hidden `.cancelAction` button (the PostEditorView ⌘S rail — `.onExitCommand` never fires behind the hosting view, the #109 probe). Both mount as overlays on PostsPaneView's focused ZStack only, so lock transitions never restructure the editor column (the #87 remount hazard / typing-continuity AC). `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `
    ` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
     - `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`; non-file URLs read back as nil — the Home is always a folder). **#171:** fresh installs (no stored override) resolve once and PIN the winner, so the Home never silently moves: (2) legacy `~/Documents/Museion` exists as a directory (`existingDirectory` gate — a stray plain file is not a Home and falls through) → pin it (existing Homes migrate manually, never silently), (3) `/Museion` when iCloud Drive is present (CloudDocs resolved dynamically at the unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path — never a hard-coded `iCloud~` form; plain FileManager probing, no ubiquity entitlements per ADR-0009), (4) else the silent Documents fallback — no dialog, no rail pill. The ladder + probes live in `HomeResolution.swift` (`resolvedInitialHome`/`liveCloudDocsDir`/`existingDirectory`); init takes injectable probes + defaults — hosted tests drive the ladder without touching the machine's real iCloud state, and the DEFAULT construction under hosted tests takes an early return (legacy fallback Home): neither the real probes nor the pin run, so the runner app's real iCloud state and defaults are never touched. Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
    @@ -81,7 +81,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
     - `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (#137: `init(binaryPath:profile:)` — default `museion` for chat, pass engines pass their own profile; ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
     - `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): engine state machine (idle/starting/ready/crashed; `isStreaming` Bool; **#28: `.ready` carries NO sessionId — session ids live in the roster**). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`; **#28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)**), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks). **#28: the handshake is initialize ONLY — sessions are created separately (`newSession`/`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 → " (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.
    +  **#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). **#175:** an unkeyed NOUS provider falls back to `PortalAuth.sessionKey` (injectable `MentorSessionModel.portalAuthPath`) — a logged-in Portal machine reads `.ready` with no key; no key AND no login reads `.missingKey("Nous Portal")` honestly. `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 (**#156 contract `.pane-head`: serif-15/600 "Mentor" title (icon + "Session" died, settled #5) + engine status + mono-10 muted-0.75 session chip — checking… / engine missing / setup failed unchanged (#151); ready = the semantic green dot (`DesignTokens.readyGreen`, the sole palette exception) + lowercase mono `ready`, base version in the tooltip, orange drift note still visible when gate and handshake disagree; gate's phase machine the source, chip only once ready, status text wins layout priority**; **#155: the Debug toggle moved to the shared composer's trailing edge** (`debugBinding` — mono-10 lowercase text toggle; the header keeps title + engine status + session chip) — `@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 as collapsed `ThinkingBlock`s (the engine's thinking — kept out of the critique text; live thinking mounts the block open, spinner toggle, #155)), composer — **#155: restyled per contract inside the shared surface** (the pane's own freeform-input/liveness row died with the #30 move; liveness is the floating chip, Stop is the Send slot), crash card (**#156 `.state-card`: accent tri — danger = terracotta, no second hue — serif-14/600 head, sans-12 muted body, Restart as the solid-accent `MonoButton`; last prompt mono-11 muted, stderr tail behind Technical details; crash card lives in the file-scope `private extension MentorPaneView` — type_body_length posture; the idle/starting interim is the same quiet mono voice, and the missing-engine card already spoke it**). **#24 (S3.1) → #156:** the segmented **Pass 1 | Pass 2 | Chat** picker is DEAD (settled #4 — chat is not a mode; the bar always carries, transcript + composer always present, the pass's streamed critique renders in the same transcript). `PassBarView` (private, owns `@State kind: PassKind`) per the #154 contract: the compact selector — Pass 1 / Pass 2 text tabs, mono-10 uppercase tracked, active = fg ink + 2pt accent underline — then the `PASS N · STATE` status line (mono-10 uppercase tracked, the open piece's Pass State, library's post-meta voice), the sans-11 muted cost line (`PassContext.estimateTokens` "· ~N tokens" or "Open a post to run a pass."), then the actions as `MonoButton` (private, #156 `.btn`: mono-11, h 28, radius 6, three looks — accent solid / surface+border / accent outline; #155 sendButton precedent, hand-drawn fills — borderedProminent carries the system tint): Cancel (outline, only while `posts.runningPass` streams or (#122) `posts.runningBlindRead` — one Cancel rail ends either run) ↔ **#122: Blind Read** (secondary, 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 (solid accent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing  key —` line under the actions 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). 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; **#156 ruling: a plain mono row — no card, no hairline of its own, a link not content**). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `title(of:)`), Cancel/Promote; ONE confirm → `promoteCard`, refusal inline orange with buttons kept (ApplyAskSheet posture). **#29 (S8.3):** the transcript renders `.researchNote` as full candidate cards (NOT one-line events — a handful of notes curates in place, no palette): serif-13 title, mono-11 muted url, selectable note, muted-italic quote; pending offers Keep + Reject (mono-11 bordered; hidden when the pane's `home` is nil — previews), kept/rejected dim 0.45 (closed-card voice) with meta `kept · research/` / `rejected`; the Mentor pane passes its `home`, the Sessions pane gains `home: URL?` (WorkspaceView hands `gate.museionHome`). Keep = ask-before (G9): `ResearchKeepSheet` (own file, PromoteAskSheet posture — "Keep this research note?", the nothing-saves-until-you-keep line, note preview, Cancel/Keep; ONE confirm → `PostStore.writeResearchNote` → disposition flips, refusal inline orange with buttons kept). Reject = no confirm (Dismiss-button voice — vanishes, nothing recorded). The sheet state lives in SessionTranscriptView (`pendingKeep`, `.sheet(item:)` over the transcript — never inside a lazy row).
     - Wiring: `AppGateState.mentor` is the app-scoped model ( #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.
    diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift
    index 4dc7a2f..52745a7 100644
    --- a/Museion/MentorSessionModel.swift
    +++ b/Museion/MentorSessionModel.swift
    @@ -222,11 +222,14 @@ final class MentorSessionModel {
     	/// #137: a model-change restart requested mid-turn — fires at turn end
     	/// (firePendingRestartIfRequested), whichever engine streamed.
     	private var pendingRestart = false
    -	/// #137 (S4): per-pass readiness (refreshPassReadiness, same-file #137
    +	/// #137: per-pass readiness (refreshPassReadiness, same-file #137
     	/// extension) + the injectable read seam (tests). Stored in the class
     	/// body — extensions carry no stored state.
     	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.
    +	var portalAuthPath: String = PortalAuth.defaultAuthPath
     
     	/// The gate's winning binary path (no re-probe — map decision). Set by the
     	/// app when the gate passes; tests inject directly.
    @@ -716,7 +719,18 @@ extension MentorSessionModel {
     		}
     		var keys: [ModelProvider: String] = [:]
     		for provider in Set(providers.values.compactMap(\.self)) {
    -			keys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? ""
    +			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
    diff --git a/Museion/ProviderProbe.swift b/Museion/ProviderProbe.swift
    index 9b8bb6a..abea6e0 100644
    --- a/Museion/ProviderProbe.swift
    +++ b/Museion/ProviderProbe.swift
    @@ -113,6 +113,11 @@ nonisolated enum ProviderProbe {
     		case .anthropic:
     			body["messages"] = [user]
     			body["max_tokens"] = Self.probeTokenCap // required
    +		case .nous:
    +			// #175: plain OpenAI chat-completions — live-probed, the portal
    +			// router takes no thinking knobs and answers finish=stop.
    +			body["messages"] = [user]
    +			body["max_tokens"] = Self.probeTokenCap
     		}
     		request.httpBody = try? JSONSerialization.data(withJSONObject: body)
     		applyAuth(&request, provider: config.provider, key: config.apiKey)
    @@ -135,17 +140,18 @@ nonisolated enum ProviderProbe {
     	/// z.ai's endpoint carries its version segment already (`…/paas/v4`);
     	/// Anthropic's base is bare and appends `/v1`; OpenAI speaks the
     	/// Responses API (`/v1/responses`, 2026-10-28 maintainer correction —
    -	/// chat-completions is the retired path). 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).
    +	/// 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).
     	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: "/chat/completions"
    +		case .zai, .nous: "/chat/completions"
     		}
     		return httpURL(base + path)
     	}
    @@ -164,10 +170,12 @@ nonisolated enum ProviderProbe {
     	}
     
     	/// Bearer everywhere except Anthropic: `x-api-key` + a pinned
    -	/// `anthropic-version` (factsheet §2.1 — never send none).
    +	/// `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).
     	static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
     		switch provider {
    -		case .zai, .openaiAPI:
    +		case .zai, .openaiAPI, .nous:
     			request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
     		case .anthropic:
     			request.setValue(key, forHTTPHeaderField: "x-api-key")
    @@ -218,7 +226,10 @@ nonisolated enum ProviderProbe {
     		let envelope = (root["error"] as? [String: Any]) ?? [:]
     		let code = envelope["code"] as? String ?? ""
     		let type = envelope["type"] as? String ?? ""
    -		let message = (envelope["message"] as? String) ?? "HTTP \(status)"
    +		// #175: the portal's envelope is bare {status, message} — no error
    +		// object — so fall back to the root message (existing providers
    +		// always carry an error object; the fallback is invisible to them).
    +		let message = (envelope["message"] as? String) ?? (root["message"] as? String) ?? "HTTP \(status)"
     		let requestID = (root["request_id"] as? String).map { " (request \($0))" } ?? ""
     
     		if provider == .zai, code == "1113" {
    @@ -247,7 +258,7 @@ nonisolated enum ProviderProbe {
     		switch provider {
     		case .anthropic: (text, finish) = anthropicStream(events)
     		case .openaiAPI: (text, finish) = responsesStream(events)
    -		case .zai: (text, finish) = chatCompletionsStream(events)
    +		case .zai, .nous: (text, finish) = chatCompletionsStream(events)
     		}
     		if !text.isEmpty {
     			return .works(latencyMS: latencyMS, modelCount: modelCount)
    diff --git a/Museion/SettingsModel.swift b/Museion/SettingsModel.swift
    index 23c16e7..5e4474c 100644
    --- a/Museion/SettingsModel.swift
    +++ b/Museion/SettingsModel.swift
    @@ -23,19 +23,21 @@
     import Foundation
     import Observation
     
    -/// The three providers Settings offers (#135). Raw values are Hermes' own
    -/// provider slugs (`CANONICAL_PROVIDERS`) — the same ids key the registry
    -/// cache; OpenAI's slug is `openai-api`.
    +/// The providers Settings offers (#135; Nous Portal #175). Raw values are
    +/// Hermes' own provider slugs (`CANONICAL_PROVIDERS`) — the same ids key
    +/// the registry cache; OpenAI's slug is `openai-api`.
     nonisolated enum ModelProvider: String, CaseIterable, Sendable {
     	case zai
     	case anthropic
     	case openaiAPI = "openai-api"
    +	case nous
     
     	var label: String {
     		switch self {
     		case .zai: "z.ai"
     		case .anthropic: "Anthropic"
     		case .openaiAPI: "OpenAI"
    +		case .nous: "Nous Portal"
     		}
     	}
     
    @@ -44,39 +46,47 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
     	var effortOptions: [ReasoningEffort] {
     		switch self {
     		case .zai: [.low, .high, .max]
    -		case .anthropic, .openaiAPI: [.low, .medium, .high, .xhigh, .max]
    +		case .anthropic, .openaiAPI, .nous: [.low, .medium, .high, .xhigh, .max]
     		}
     	}
     
     	/// The model a provider switch lands on (prototype #130's pinned
     	/// flagships — registry order is capability-sorted, not default-sorted;
     	/// #136 dogfood: OpenAI's flagship is gpt-6.1-sol, the current
    -	/// Responses-era default).
    +	/// Responses-era default). #175: the portal's catalog is the
    +	/// vendor-prefixed router list — the switch keeps the app's sonnet
    +	/// posture (live-probed: `anthropic/claude-sonnet-5` generates).
     	var switchDefaultModel: String {
     		switch self {
     		case .zai: "glm-5.3"
     		case .anthropic: "claude-sonnet-5"
     		case .openaiAPI: "gpt-6.1-sol"
    +		case .nous: "anthropic/claude-sonnet-5"
     		}
     	}
     
     	/// Default endpoint families (factsheet §1; z.ai's is key-type keyed).
    +	/// #175: the Nous Portal inference API (portal.nousresearch.com/api-docs).
     	var defaultEndpoint: String {
     		switch self {
     		case .zai: ZaiKeyType.standard.endpoint
     		case .anthropic: "https://api.anthropic.com"
     		case .openaiAPI: "https://api.openai.com/v1"
    +		case .nous: "https://inference-api.nousresearch.com/v1"
     		}
     	}
     
     	/// #136: the `.env` var Hermes' own provider registry maps each slug to
     	/// (`hermes_cli/auth.py` live-read): zai→GLM_API_KEY (ZAI_/Z_AI_ are
    -	/// aliases), anthropic→ANTHROPIC_API_KEY, openai-api→OPENAI_API_KEY.
    +	/// aliases), anthropic→ANTHROPIC_API_KEY, openai-api→OPENAI_API_KEY,
    +	/// nous→NOUS_API_KEY (the plugin profile's env var — the engine's model
    +	/// auth rides the Portal login, the key bills the same account credits).
     	var envVarName: String {
     		switch self {
     		case .zai: "GLM_API_KEY"
     		case .anthropic: "ANTHROPIC_API_KEY"
     		case .openaiAPI: "OPENAI_API_KEY"
    +		case .nous: "NOUS_API_KEY"
     		}
     	}
     }
    @@ -134,6 +144,31 @@ nonisolated struct ProviderKeyConfig: Equatable, Sendable {
     	var apiKey: String = ""
     }
     
    +/// #175: the shared Portal session's inference key from the Hermes auth
    +/// store (`~/.hermes/auth.json` — where the device-code login's agent_key
    +/// lives; profiles inherit it via the shared nous state). This is the
    +/// credential the engine itself runs nous on (API key and subscription
    +/// bill the same account credits). Read-only and lenient: a missing or
    +/// foreign-shaped store is nil, never an error. Nonisolated so the model's
    +/// fallback can read it off-main.
    +/// ponytail: agent_key_expires_at is not checked — a stale key probes
    +/// honestly (the portal's 401 decodes authFailed); parse the expiry if a
    +/// stale-key verdict ever misleads.
    +nonisolated enum PortalAuth {
    +	static let defaultAuthPath = ("~/.hermes/auth.json" as NSString).expandingTildeInPath
    +
    +	static func sessionKey(authJSONPath: String = defaultAuthPath) -> String? {
    +		guard let data = try? Data(contentsOf: URL(fileURLWithPath: authJSONPath)),
    +		      let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
    +		      let providers = parsed["providers"] as? [String: Any],
    +		      let nous = providers["nous"] as? [String: Any],
    +		      let agentKey = (nous["agent_key"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines),
    +		      !agentKey.isEmpty
    +		else { return nil }
    +		return agentKey
    +	}
    +}
    +
     /// 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
    @@ -152,6 +187,10 @@ final class SettingsModel {
     	private(set) var testStates: [ModelProvider: TestState] = [:]
     
     	private let writer: any SettingsWriting
    +	/// #175: injected so the nous Test Connection tests run offline.
    +	private let probeTransport: ProviderProbe.Transport
    +	/// #175: the shared Hermes auth store — the nous fallback's agent_key.
    +	private let portalAuthPath: String
     	/// #137 (S4): fired after a SUCCESSFUL chat-surface write ONLY — the
     	/// resident chat engine restarts to read the new model block
     	/// (WorkspaceView wires it to MentorSessionModel.requestRestart).
    @@ -170,10 +209,14 @@ final class SettingsModel {
     		writer: any SettingsWriting = NoopSettingsWriter(),
     		surfaces: [ProfileSurface: SurfaceModelConfig]? = nil,
     		writeDebounce: TimeInterval = 0.35,
    +		probeTransport: @escaping ProviderProbe.Transport = ProviderProbe.urlSessionTransport,
    +		portalAuthPath: String = PortalAuth.defaultAuthPath,
     	) {
     		self.registry = registry
     		self.writer = writer
     		self.writeDebounce = writeDebounce
    +		self.probeTransport = probeTransport
    +		self.portalAuthPath = portalAuthPath
     		self.surfaces = surfaces
     			?? Dictionary(uniqueKeysWithValues: ProfileSurface.allCases.map { ($0, .surfaceDefault) })
     		keys = Dictionary(
    @@ -324,18 +367,46 @@ 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.
    +	/// 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.
     	func testConnection(for provider: ModelProvider) async {
     		guard testStates[provider] != .running else { return }
     		testStates[provider] = .running
    -		let keyConfig = keyConfig(for: provider)
    +		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(
     			provider: provider,
    -			endpoint: keyConfig.endpoint,
    -			apiKey: keyConfig.apiKey,
    +			endpoint: keyConfig(for: provider).endpoint,
    +			apiKey: key,
     			model: probeModel(for: provider),
     		)
    -		testStates[provider] = await .done(ProviderProbe.probe(config))
    +		let transport = probeTransport
    +		testStates[provider] = await .done(ProviderProbe.probe(config, transport: transport))
     	}
     
     	/// The model the probe proves generation on: the first surface on this
    diff --git a/Museion/SettingsPagesView.swift b/Museion/SettingsPagesView.swift
    index 94737b0..de59e4e 100644
    --- a/Museion/SettingsPagesView.swift
    +++ b/Museion/SettingsPagesView.swift
    @@ -220,6 +220,17 @@ private struct ProviderKeyBlock: View {
     					.font(.system(size: 11.5))
     					.foregroundStyle(DesignTokens.muted)
     			}
    +			if provider == .nous {
    +				// #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.
    +				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).",
    +				)
    +				.font(.system(size: 11.5))
    +				.foregroundStyle(DesignTokens.muted)
    +			}
     			// #136: Test Connection (factsheet §4) — /models count + a
     			// minimal streaming chat; latency + model count on success,
     			// the honest decoded verdict otherwise.
    diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md
    index 5ec771d..d7ea34c 100644
    --- a/MuseionTests/AGENTS.md
    +++ b/MuseionTests/AGENTS.md
    @@ -48,7 +48,7 @@ Owned by the root AGENTS.md contract.
     - ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `
      ` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013). - `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes. - `ProseRekeyTests.swift` (#142, F1 — scenario header at file top; own file, split from ProseListTests at the file-length ceiling) — `ProseFoldRekeyTests` drives the keystroke pipeline through the REAL seams (`shouldChangeText` records → storage mutates → `refreshFolds`): a single-line edit above re-keys in place with hidden styling intact (no storage swap), typing on the marker line kills the fold AND restores its scope to view, a multi-line edit still takes the full pass, and a wholesale restyle (the fence-flip shape) self-heals into the full pass via the font probe; `ProseRekeyMathTests` pins the pure `rekey` math exactly (shift above, untouched below, death + translated diedScope, boundary-insertion deaths at both marker-content edges, scope-interior deletion → shrunk scope + rehide range + caret park). The painted-layer chrome skip itself is unpinnable headless (needs a window) — dogfood owns it. -- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the Responses dialect** — `input` + `max_output_tokens` + `gpt-6.1-sol`, messages/max_completion_tokens/max_tokens asserted ABSENT, URL `/v1/responses`; trailing-slash + garbage-endpoint nil-safety via the http(s)-scheme check) and `probe()` over canned transports — no-key fail-fast, end-to-end works with model count + reply, a /models auth failure short-circuits the chat step, transport errors → unreachable. `SettingsModelTests`' switch-default pin rides the gpt-6.1-sol flagship. **#137 B2 (scenario header in `SettingsModelWritePathTests.swift`):** the chat-restart hook — a successful chat-surface write fires `onChatSurfaceWrite` after `awaitPendingWrites()`, pass-surface edits and key writes never do, and a failed chat write (`failSurfaceWrites`) never does either. +- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. **#175 (nous):** the nous provider facts pin (slug/label/endpoint/NOUS_API_KEY) lives here too (SettingsModelTests' file-length ceiling), an unkeyed nous Test Connection borrows the shared `~/.hermes/auth.json` agent_key as Bearer (`PortalAuth.sessionKey`; injectable `portalAuthPath` + `probeTransport` — offline canned transport), and no-key-no-login authFails naming `hermes auth add nous`; the custom-endpoint refusal pin (a hand-edited nous endpoint with an empty key authFails pre-network — the session key never rides a user-set URL); **EngineLifecycleTests** carries the readiness counterpart (`nous pass readiness rides the portal login without a key` — `.ready` via the injected `portalAuthPath`, `.missingKey("Nous Portal")` with no login); ProviderProbeTests pins the bare-envelope **401 → authFailed** (the fallback credential's own failure mode). `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed, **#175 nous chat-completions** + the portal's bare `{status, message}` envelope decoding requestFailed with the message — the error-object-less shape) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the Responses dialect** — `input` + `max_output_tokens` + `gpt-6.1-sol`, messages/max_completion_tokens/max_tokens asserted ABSENT, URL `/v1/responses`; trailing-slash + garbage-endpoint nil-safety via the http(s)-scheme check) and `probe()` over canned transports — no-key fail-fast, end-to-end works with model count + reply, a /models auth failure short-circuits the chat step, transport errors → unreachable. `SettingsModelTests`' switch-default pin rides the gpt-6.1-sol flagship; **#175:** the nous switch lands on `anthropic/claude-sonnet-5` (the router-catalog flagship, registry-known via the fixture's `.nous` row) and the ladder pin covers nous. **#137 B2 (scenario header in `SettingsModelWritePathTests.swift`):** the chat-restart hook — a successful chat-surface write fires `onChatSurfaceWrite` after `awaitPendingWrites()`, pass-surface edits and key writes never do, and a failed chat write (`failSurfaceWrites`) never does either. - `PersonaLoadOrderTests.swift` (#1) — persona-content pins over the REAL bundled payload (`ProfileProvisioner.defaultPayloadRoot()`): both personas carry the `## Draft first, rules last` load-order doctrine (pass-persona 1.5 / session-persona 1.2, the PRD prompt-end rule), and the section is verbatim-shared between the pair (the four-shared-sections contract, ref/writing skills/AGENTS.md). Verified layout lives in `docs/research/prompt-layout-factsheet.md`. ## Verification diff --git a/MuseionTests/EngineLifecycleTests.swift b/MuseionTests/EngineLifecycleTests.swift index 89a2615..9ec08d8 100644 --- a/MuseionTests/EngineLifecycleTests.swift +++ b/MuseionTests/EngineLifecycleTests.swift @@ -250,6 +250,33 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool { // link; once the key is provided via Settings, Run Pass re-enables (pane // re-entry refreshes). +// Scenario: Keyless Nous pass readiness — From user story #175 +// Given a pass surface switched to Nous Portal and hermes logged into +// the Portal (the shared auth.json session — the engine's credential; +// the .env key is optional and bills the same account credits) +// When refreshPassReadiness runs +// Then the pass reads .ready with NO key (the session agent_key stands +// in), and with no login either it names the missing key honestly. +@Test @MainActor func `nous pass readiness rides the portal login without a key`() async throws { + let mentor = MentorSessionModel() + let writer = RecordingWriter() + writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .nous, model: "anthropic/claude-sonnet-5", effort: nil), nil) + mentor.passReadinessWriter = writer + + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-readiness-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let authPath = dir.appendingPathComponent("auth.json").path + try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8) + mentor.portalAuthPath = authPath + await mentor.refreshPassReadiness() + #expect(mentor.readiness(for: .pass1) == .ready) + + // No key and no login — the honest missing-key verdict. + mentor.portalAuthPath = dir.appendingPathComponent("missing.json").path + await mentor.refreshPassReadiness() + #expect(mentor.readiness(for: .pass1) == .missingKey(providerLabel: "Nous Portal")) +} + /// B1 readiness pins: refreshPassReadiness over the injected RecordingWriter /// — keyed provider reads .ready, an unkeyed one reads .missingKey with its /// label, a key landing re-enables on the next refresh (the pane's .task), diff --git a/MuseionTests/ProviderProbeTests.swift b/MuseionTests/ProviderProbeTests.swift index 7bc1d00..e1bdc8f 100644 --- a/MuseionTests/ProviderProbeTests.swift +++ b/MuseionTests/ProviderProbeTests.swift @@ -107,7 +107,55 @@ struct ProviderProbeTests { #expect(foreignStatus == 502) } - // MARK: Chat decode — the three SSE dialects + // MARK: Chat decode — the SSE dialects + + // Scenario: Nous Portal decode — From user story #175 + // Given the portal's OpenAI-compatible chat SSE (live-captured + // 2026-11-05: delta.content chunks, finish stop) and its bare + // {status, message} error envelope (no error object — a bad model id + // answers HTTP 404 + message) + // When the probe decodes a nous response + // Then content decodes works, and the error decodes requestFailed + // carrying the portal's own message — never a bare "HTTP 404". + @Test func `nous sse decodes works and the portal error envelope carries its message`() { + let sse = """ + data: {"choices":[{"delta":{"content":"Hi there!"},"finish_reason":null}]} + + data: {"choices":[{"delta":{},"finish_reason":"stop"}]} + + data: [DONE] + """ + guard case .works = ProviderProbe.decodeChat( + provider: .nous, body: Data(sse.utf8), modelCount: 385, latencyMS: 900, + ) else { + Issue.record("expected works over the portal SSE") + return + } + guard case let .requestFailed(status, detail) = ProviderProbe.decodeError( + status: 404, + body: probeData( + #"{"status":404,"message":"Model 'x' not found in our configuration."}"#, + ), + provider: .nous, + ) else { + Issue.record("expected requestFailed for the portal envelope") + return + } + #expect(status == 404) + #expect(detail.contains("not found")) + // Finish-audit #175: the fallback credential's own failure mode — + // 401 over the bare envelope decodes authFailed carrying the + // message (an expired/revoked agent_key). + guard case let .authFailed(authDetail) = ProviderProbe.decodeError( + status: 401, + body: probeData(#"{"status":401,"message":"token expired"}"#), + provider: .nous, + ) else { + Issue.record("expected authFailed for the bare 401 envelope") + return + } + #expect(authDetail.contains("token expired")) + } @Test func `zai sse content decodes works and empty length decodes starved`() { let sse = """ diff --git a/MuseionTests/ProviderProbeTransportTests.swift b/MuseionTests/ProviderProbeTransportTests.swift index eaf4110..12a83e5 100644 --- a/MuseionTests/ProviderProbeTransportTests.swift +++ b/MuseionTests/ProviderProbeTransportTests.swift @@ -56,6 +56,27 @@ struct ProviderProbeTransportTests { #expect(request.url?.absoluteString == "\(ZaiKeyType.coding.endpoint)/chat/completions") } + /// #175: Nous Portal is plain OpenAI chat-completions on the wire — + /// live-probed 2026-11-05 (messages body answers finish=stop; the + /// portal router has no z.ai-style thinking knobs) — Bearer auth like + /// z.ai/openai, `/chat/completions` + `/models` on the versioned base. + @Test func `nous chat speaks the plain chat completions dialect`() throws { + let config = ProviderProbe.Config( + provider: .nous, endpoint: ModelProvider.nous.defaultEndpoint, apiKey: "sk-nous", model: "anthropic/claude-sonnet-5", + ) + let request = try #require(ProviderProbe.makeChatRequest(config)) + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer sk-nous") + #expect(request.url?.absoluteString == "https://inference-api.nousresearch.com/v1/chat/completions") + #expect(ProviderProbe.modelsURL(for: .nous, endpoint: ModelProvider.nous.defaultEndpoint)? + .absoluteString == "https://inference-api.nousresearch.com/v1/models") + let bodyData = try #require(request.httpBody) + let body = try #require(String(bytes: bodyData, encoding: .utf8)) + #expect(body.contains(#""messages""#)) + #expect(body.contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#)) + #expect(!body.contains("thinking")) // no z.ai reasoning knobs on the portal router + #expect(!body.contains("reasoning_effort")) + } + @Test func `openai chat speaks the responses api and urls append cleanly`() throws { let config = ProviderProbe.Config( provider: .openaiAPI, endpoint: "https://api.openai.com/v1/", apiKey: "sk-oai", model: "gpt-6.1-sol", diff --git a/MuseionTests/SettingsModelTests.swift b/MuseionTests/SettingsModelTests.swift index cf67b4b..3bf83cf 100644 --- a/MuseionTests/SettingsModelTests.swift +++ b/MuseionTests/SettingsModelTests.swift @@ -124,6 +124,9 @@ func liveShapedRegistry() -> ModelRegistry { .zai: ["glm-4.5", "glm-5", "glm-5.3", "glm-5.3-flashx"], .anthropic: ["claude-fable-5.1", "claude-opus-5-5", "claude-sonnet-5", "claude-sonnet-4-6"], .openaiAPI: ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4-mini"], + // #175: the portal's router catalog shape — vendor-prefixed ids, the + // switch flagship first. + .nous: ["anthropic/claude-sonnet-5", "z-ai/glm-5.3", "openai/gpt-5.5"], ]) } @@ -135,6 +138,9 @@ struct SettingsModelTests { #expect(ModelProvider.zai.effortOptions == [.low, .high, .max]) #expect(ModelProvider.openaiAPI.effortOptions == [.low, .medium, .high, .xhigh, .max]) #expect(ModelProvider.anthropic.effortOptions == [.low, .medium, .high, .xhigh, .max]) + // #175: hermes clamps nous on the widest OpenAI-compatible vocabulary + // (OPENAI_COMPAT_WIRE_EFFORTS — the Museion-facing subset). + #expect(ModelProvider.nous.effortOptions == [.low, .medium, .high, .xhigh, .max]) } @Test @MainActor func `effort unset is the leading default state`() { @@ -184,6 +190,11 @@ struct SettingsModelTests { #expect(model.config(for: .chat).model == "gpt-6.1-sol") model.setProvider(.anthropic, for: .chat) #expect(model.config(for: .chat).model == "claude-sonnet-5") + // #175: the portal switch keeps the app's sonnet posture — same + // default model, routed and billed through Nous. + model.setProvider(.nous, for: .chat) + #expect(model.config(for: .chat).model == "anthropic/claude-sonnet-5") + #expect(!model.isCustom(.chat)) } @Test @MainActor func `an empty registry leaves every model custom free text stays first class`() { diff --git a/MuseionTests/SettingsModelWritePathTests.swift b/MuseionTests/SettingsModelWritePathTests.swift index 089b6c3..a976859 100644 --- a/MuseionTests/SettingsModelWritePathTests.swift +++ b/MuseionTests/SettingsModelWritePathTests.swift @@ -149,6 +149,103 @@ struct SettingsModelWritePathTests { #expect(model.probeModel(for: .zai) == ModelProvider.zai.switchDefaultModel) } + // Scenario: Nous Portal as a fourth provider — From user story #175 + // Given Hermes' own registry offers the `nous` slug (OpenAI-compatible + // inference API — one account bill behind key and subscription alike) + // When Settings offers Nous Portal + // Then the pinned facts match the live-probed wire: the portal inference + // endpoint, the env var hermes' tooling maps the slug to, and the label. + @Test func `nous provider facts pin the portal wire`() { + #expect(ModelProvider.nous.rawValue == "nous") + #expect(ModelProvider.nous.label == "Nous Portal") + #expect(ModelProvider.nous.defaultEndpoint == "https://inference-api.nousresearch.com/v1") + #expect(ModelProvider.nous.envVarName == "NOUS_API_KEY") + } + + // Scenario: Test Connection on an unkeyed Nous Portal — From user story #175 + // Given hermes logged into the Nous Portal (the shared auth.json session — + // the engine's own credential; API key and subscription bill the same + // account credits) + // When the user tests Nous with no key pasted + // Then the probe borrows the session's agent_key as its Bearer — and with + // no session either, it names the portal login path, not a bare "no key". + @Test @MainActor func `nous connection borrows the shared portal session key`() async throws { + final class AuthSaw: @unchecked Sendable { var header: String? } + let saw = AuthSaw() + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-auth-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let authPath = dir.appendingPathComponent("auth.json").path + try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8) + + let model = SettingsModel( + registry: liveShapedRegistry(), + writer: RecordingWriter(), + writeDebounce: 0, + probeTransport: { request in + saw.header = request.value(forHTTPHeaderField: "Authorization") + if request.url!.path.hasSuffix("/models") { + return (probeData(#"{"object":"list","data":[{},{},{},{}]}"#), probeHTTPResponse(200)) + } + return ( + Data("data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"},\"finish_reason\":\"stop\"}]}\n\n".utf8), + probeHTTPResponse(200), + ) + }, + portalAuthPath: authPath, + ) + await model.testConnection(for: .nous) + #expect(saw.header == "Bearer ak-shared-123") + guard case let .done(outcome) = model.testStates[.nous], case .works = outcome else { + Issue.record("expected works over the session key, got \(String(describing: model.testStates[.nous]))") + return + } + } + + /// Finish-audit #175: the implicit session credential never rides a + /// hand-edited endpoint — a custom endpoint with an empty key refuses + /// before any network, pointing at the key field. + @Test @MainActor func `nous session key never rides a custom endpoint`() async throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-gate-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let authPath = dir.appendingPathComponent("auth.json").path + try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8) + + let model = SettingsModel( + registry: liveShapedRegistry(), + writer: RecordingWriter(), + writeDebounce: 0, + probeTransport: { _ in + Issue.record("a custom endpoint must never receive the session key") + throw URLError(.badURL) + }, + portalAuthPath: authPath, + ) + model.setEndpoint("http://proxy.example/v1", for: .nous) + await model.testConnection(for: .nous) + guard case let .done(outcome) = model.testStates[.nous], case let .authFailed(detail) = outcome else { + Issue.record("expected the custom-endpoint refusal, got \(String(describing: model.testStates[.nous]))") + return + } + #expect(detail.contains("paste an API key")) + } + + @Test @MainActor func `nous connection with no key and no login names the portal path`() async { + let missing = FileManager.default.temporaryDirectory + .appendingPathComponent("nous-auth-missing-\(UUID().uuidString)").path + let model = SettingsModel( + registry: liveShapedRegistry(), + writer: RecordingWriter(), + writeDebounce: 0, + portalAuthPath: missing, + ) + await model.testConnection(for: .nous) + guard case let .done(outcome) = model.testStates[.nous], case let .authFailed(detail) = outcome else { + Issue.record("expected authFailed, got \(String(describing: model.testStates[.nous]))") + return + } + #expect(detail.contains("hermes auth add nous")) + } + // Scenario: Saving a Chat model change reaches the resident engine // From user story #137 acceptance 2 // Given the Settings pane is open diff --git a/docs/devlog/20261105-issue175-nous-portal-provider_log.md b/docs/devlog/20261105-issue175-nous-portal-provider_log.md new file mode 100644 index 0000000..25e79c4 --- /dev/null +++ b/docs/devlog/20261105-issue175-nous-portal-provider_log.md @@ -0,0 +1,67 @@ +# Add Nous Portal Provider (#175) + +> **Date:** 2026-11-05 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/175 + +## Goal + +Add the Nous Portal as a fourth provider in Settings, so chats and passes can run on Nous models using API-key and subscription credits (one account bill behind both, per the portal docs — the owner confirmed this reading mid-session). + +## What Was Done + +- `ModelProvider` gains `.nous` — slug `nous`, label "Nous Portal", endpoint `https://inference-api.nousresearch.com/v1`, env `NOUS_API_KEY`, 5-level effort ladder (hermes' `OPENAI_COMPAT_WIRE_EFFORTS`), switch flagship `anthropic/claude-sonnet-5` (Museion/SettingsModel.swift). +- `ProviderProbe` speaks the nous dialect: plain OpenAI chat-completions (`/chat/completions`, `messages` + the 512 cap, no thinking knobs), Bearer auth, existing chat-completions SSE decoder; `decodeErrorRoot` falls back to a bare root `message` (the portal's `{status, message}` envelope carries no error object) (Museion/ProviderProbe.swift). +- New `PortalAuth` enum (SettingsModel.swift): lenient read of the shared `~/.hermes/auth.json` session `agent_key` — the credential the engine itself runs nous on. +- `SettingsModel.testConnection`: an unkeyed nous test falls back to the session agent_key, **gated to the official https endpoint** — a hand-edited endpoint with an empty key refuses pre-network; no key and no login names `hermes auth add nous`. `probeTransport`/`portalAuthPath` injectable init seams. +- `MentorSessionModel.refreshPassReadiness` (finish-audit HIGH fix): an unkeyed nous pass falls back to `PortalAuth.sessionKey` (injectable `portalAuthPath`) — a logged-in Portal machine reads `.ready` with no key; the UI no longer demands a key the feature says isn't needed. +- Provider Keys page: the nous block carries the Portal-login note (chats ride the hermes Portal login; a pasted key bills the same account credits). +- Tests: 8 new/extended pins across SettingsModelTests, SettingsModelWritePathTests, ProviderProbeTests, ProviderProbeTransportTests, EngineLifecycleTests (provider facts, ladder, switch default, request dialect, SSE decode + bare-envelope 404/401, session-key fallback, custom-endpoint refusal, keyless readiness). +- DOX pass: Museion/AGENTS.md + MuseionTests/AGENTS.md updated (provider facts, probe dialect, fallback semantics, readiness, pins). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Flagship `anthropic/claude-sonnet-5`, not a Hermes-4 model | Live-probed: the docs' `Hermes-4.3-36B` ids **404** on the real endpoint — the portal serves the OpenRouter catalog (`/v1/models` = 385 vendor-prefixed ids). Sonnet keeps the app's everywhere-default posture, billed through Nous. | +| One pasted key covers API + subscription credits | The portal docs: "Add API credits **or** activate a subscription, then generate an API key" — the key is the billing instrument for both (owner confirmed). No dual-mode UI needed. | +| Engine auth rides the Portal login; key optional | Hermes' nous runtime is OAuth-only (`resolve_nous_runtime_credentials`, shared across profiles; `NOUS_API_KEY` does not drive engine inference today). The `.env` write stays as future-proofing — a later hermes release lights it up with zero Museion changes. | +| No `model.base_url` write for nous | Hermes derives nous routing from auth state (`_nous_effective_routing`); `config set model.provider` clears stale base_url anyway. | +| Session-key fallback gated to the official endpoint | Finish-audit security finding: the implicit credential (never pasted, empty field) must not silently ride a user-edited URL (cleartext http / foreign host) with no on-screen cue. | +| Readiness fallback at the shared gate | One guard in `refreshPassReadiness` covers both pass kinds — patching only the probe would have left Run Pass blocked. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Nous model dropdown missed `anthropic/claude-sonnet-5.5` | The dropdown reads hermes' `~/.hermes/provider_models_cache.json` (ADR-0014, zero HTTP from Museion); the cache was written 2026-09-03, before 5.5 existed (381 cached vs 385 live) | `hermes model --refresh` wipes + re-fetches — but it exits before fetching nous unless the provider is walked; filled the cache by calling hermes' own `fetch_nous_models` + `_store_cache_entry` through its venv (hermes' code, its fingerprint, its lock) | +| `hermes model --refresh` refuses to run through a pipe | The picker guards non-TTY stdin | Run interactively (the owner's run wiped the cache and exited after 4 providers — nous never re-fetched) | +| Finish-audit HIGH: keyless nous passes blocked by Run Pass | `refreshPassReadiness` mapped empty `.env` key → `.missingKey` with no Portal-login fallback — contradicting the feature's own UI note | Fallback to `PortalAuth.sessionKey` in the readiness gate, pinned | +| Scoped flip run "passed" with a guard deleted | `EngineLifecycleTests` has no `@Suite` — its free functions don't run under `-only-testing` suite filters (the #31 lesson, re-confirmed) | Flip verdict needs the full suite; it failed with exactly the two new pins | +| swiftlint orphaned_doc_comment | A `//` scenario block between a `///` doc block and its test detaches the doc (#143 lesson) | Scenario blocks go above the `///` block | +| `@unchecked Sendable` / `@escaping` compile errors | Test transport closure captured a mutable box; stored closure param | `final class AuthSaw: @unchecked Sendable`; `@escaping` on the init param | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/SettingsModel.swift` | `.nous` case + all five switches; `PortalAuth`; endpoint-gated session-key fallback in `testConnection`; injectable seams | +| `Museion/ProviderProbe.swift` | nous dialect (URL/body/auth/decode); bare-root-message error fallback | +| `Museion/MentorSessionModel.swift` | readiness nous fallback + injectable `portalAuthPath` | +| `Museion/SettingsPagesView.swift` | nous Portal-login note on the Provider Keys page | +| `MuseionTests/SettingsModelTests.swift` | registry fixture `.nous` row; ladder + switch-default pins | +| `MuseionTests/SettingsModelWritePathTests.swift` | nous facts, session-key fallback, custom-endpoint refusal pins | +| `MuseionTests/ProviderProbeTests.swift` | nous SSE decode + bare-envelope 404/401 pins | +| `MuseionTests/ProviderProbeTransportTests.swift` | nous chat-completions dialect pin | +| `MuseionTests/EngineLifecycleTests.swift` | keyless nous readiness pin | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass + gitnexus counters | + +## Open Items & Next Steps + +- [ ] Dogfood: Settings ▸ a surface ▸ Provider → Nous Portal ▸ Test Connection (no key needed on this machine) ▸ run a chat/pass. +- [ ] Deferred (ceiling comment on `PortalAuth`): parse `agent_key_expires_at` if a stale-key verdict ever misleads — today the portal's 401 decodes `authFailed` honestly. +- [ ] The hermes picker's `--refresh` not re-fetching nous on early exit is an upstream hermes wart — worth a report to the hermes repo if it recurs. + +--- + +*Log written by write-log skill. Verification cited: `xcodebuild test` (unit + UI) 635/635 passed, exit 0, 2026-11-05 16:0x; flip-cycle 632-passed/2-failed with both new guards deleted, restored sha-verified.* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 9a66786..2d77d89 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-05 | issue | [20261105-issue175-nous-portal-provider_log.md](20261105-issue175-nous-portal-provider_log.md) | Fourth provider `nous`: plain chat-completions probe, session-key fallback gated to the official endpoint, keyless readiness (#175) | | 2026-11-05 | issue | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) | Fresh installs pin `/Museion` with a legacy-dir guard; injectable probe seam, 9 tests (#171) | | 2026-11-04 | issue | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) | #158: Cold Turkey map closed — frontier empty, build on main, hotkey fog parked; #140 ready to close | | 2026-11-04 | issue | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) | #166: preset chips ruled NO — typeable value + defaults + steppers cover arming; frontier now empty |