From f49e4b6ca048718702cca37ab589863dfd5cdd19 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 10 Nov 2026 10:58:29 +0100 Subject: [PATCH] refactor(settings): provider facts as data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #181: ModelProvider is the provider-descriptor table — label, effort ladder, flagship, endpoint, env var joined by wire dialect (chat/models paths + the SSE decoder selector), auth mode (Bearer vs Anthropic's header pair), keyless (nous rides the Portal login), and the ONE trailing-slash endpoint trim. The probe's URL builders, auth headers, and stream-decoder picks select by data; the per-dialect bodies and decoders stay separate functions, not switch clothing. ProviderCredential.resolve is the ONE credential rail (provider key, else the shared Portal session key for keyless providers — official endpoint ONLY, never a user-set URL). Settings' Test Connection and the new PassReadiness module both call it; the twice-implemented #175 fallback can no longer drift. One deliberate tightening, reviewer- blessed: a nous pass profile on a custom base_url with no pasted key now reads missingKey where the old session-model fallback said ready — the old copy had no endpoint gate at all. Pass readiness leaves the session model (PassReadiness.swift maps each pass surface to ready/missingKey/unknown over the descriptor; MentorSessionModel stores the verdicts and reads no keys or auth files). runPass and blindRead run their guards through one shared rail (guardOpenPieceRun) — identical refusal strings, blockers named honestly. No app-side model-settings store (ADR-0014 red line). Rider: the #179 mid-pass repoint pin polls the rig's hasHeldPrompt before releasing the held turn — runningPass flips before the one-shot engine parks its prompt, so firing into that window false-failed under parallel-suite load. Full suite 668/668 (xcresult executed count). Finish-audit: three reviewers (ponytail/security/general), zero findings above LOW; two ponytail trims and one pin tightening applied. Closes #181 --- AGENTS.md | 5 +- Museion/AGENTS.md | 6 +- Museion/MentorSessionModel.swift | 83 +++------ Museion/PassReadiness.swift | 79 +++++++++ Museion/PostsModelPasses.swift | 102 +++++------ Museion/ProviderProbe.swift | 40 ++--- Museion/SettingsModel.swift | 166 ++++++++++++++---- Museion/SettingsPagesView.swift | 3 +- MuseionTests/AGENTS.md | 4 +- MuseionTests/PassRunTests.swift | 2 +- MuseionTests/PostsModelTests.swift | 8 +- MuseionTests/ProviderCredentialTests.swift | 117 ++++++++++++ MuseionTests/ScriptedEngine.swift | 8 + ...-provider-descriptor-pass-readiness_log.md | 66 +++++++ docs/devlog/INDEX.md | 1 + 15 files changed, 506 insertions(+), 184 deletions(-) create mode 100644 Museion/PassReadiness.swift create mode 100644 MuseionTests/ProviderCredentialTests.swift create mode 100644 docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md diff --git a/AGENTS.md b/AGENTS.md index 1f093dc..7034e90 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** (6786 symbols, 31918 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** (6832 symbols, 32511 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). @@ -194,6 +194,7 @@ This project is indexed by GitNexus as **museion** (6786 symbols, 31918 relation - Sequential bounded-poll loops each arm their OWN deadline — a shared one starves the later loop, which then fails on the earlier flush's stale observable (zeros, never nil) (#147) - A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147) - One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180) +- A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181) ### Trust boundaries - A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6) - A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34) @@ -206,6 +207,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-10 | [20261110-issue181-provider-descriptor-pass-readiness_log.md](docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md) | | 2026-11-10 | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | | 2026-11-09 | [20261109-issue179-postsmodel-write-rail_log.md](docs/devlog/20261109-issue179-postsmodel-write-rail_log.md) | | 2026-11-09 | [20261109-issue178-extract-engine-host-transport-seam_log.md](docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md) | @@ -215,5 +217,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 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) | -| 2026-11-04 | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](docs/devlog/20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 544e7da..6e28b83 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -36,14 +36,14 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4). - `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends. - Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept. -- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, construction + Settings repoint; no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` mirrors the guards; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, construction + Settings repoint; no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). - `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID. - `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load. - `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction. - `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump). - Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling). - Prose list machinery — `ProseList.swift` (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); `ProseListTextView.swift` — folds are VIEW state (buffer never changes; hidden scopes styled via `foldedAttributes`), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (`rekey`), the newline gate is `\.isNewline` NEVER literal `\n`/`\r` compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through `ProseDropBridge` into `ingestDrop` (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure `dropIndex` (sampling + bracket + binary search; the SwiftUI closure's `location` is unusable under this hosting, off-screen rects return garbage). -- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — `ModelProvider` slugs + effort ladders + pinned switch defaults (nous: Portal endpoint, flagship `anthropic/claude-sonnet-5`, Bearer; an unkeyed nous test falls back to the shared Portal session key ONLY on the official https endpoint — the session credential never rides a user-set URL). Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions); 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). +- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself. - Focus mode — transient per-launch (no persistence); `FocusChrome` hover zones + overlay panels float over the measure, never push it; `CaretCentering` is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (`ColdTurkeySeat`/`ColdTurkeyDot`) mounts as overlays on the focused branch only. - Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed. - `AppGateState.museionHome` — fresh installs resolve once and PIN the winner: legacy `~/Documents/Museion` (dir-ness gated) → `/Museion` (resolved at the unprefixed path, never a hard-coded `iCloud~` form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched. @@ -75,7 +75,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit. - `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p `; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. -- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path). +- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable). - `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm). - Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index e88a28a..e844b28 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -282,13 +282,17 @@ final class MentorSessionModel { /// (firePendingScopeIfRequested); an in-flight transcript is never /// torn down mid-stream. private var pendingScopePieceTitle: String? - /// #137: per-pass readiness (refreshPassReadiness, same-file #137 - /// extension) + the injectable read seam (tests). Stored in the class - /// body — extensions carry no stored state. + /// #137: per-pass readiness — refreshed at pane entry (re-entry + /// re-fires the pane's .task — the key-added-in-Settings re-enable + /// path). #181: computed in the PassReadiness module over the provider + /// descriptor (the model reads no keys and no auth files); stored here + /// because the pane observes it. `passReadinessWriter` is the + /// injectable read seam (tests). private(set) var passReadiness: [PassKind: PassReadiness] = [:] var passReadinessWriter: (any SettingsWriting)? - /// #175: the shared Portal auth store for the nous keyless readiness - /// fallback — injectable so tests never read the machine's real login. + /// #175: the shared Portal auth store — handed to the readiness + /// module's credential resolution; injectable so tests never read the + /// machine's real login. var portalAuthPath: String = PortalAuth.defaultAuthPath /// The gate's winning binary path (no re-probe — map decision). Set by @@ -713,69 +717,26 @@ extension MentorSessionModel { host.isOneShotRunning } - /// #137 (S4): the Run Pass posture — is the pass profile's provider - /// keyed? .unknown NEVER blocks (our own read failure — the spawn's - /// honest failure row owns that path); .missingKey names the provider - /// so the pane can say what's missing and link to Settings. - enum PassReadiness: Equatable { - case ready - case missingKey(providerLabel: String) - case unknown - } - - // Per-pass readiness (stored in the class body), refreshed at pane - // entry (re-entry re-fires the pane's .task — the key-added-in- - // Settings re-enable path). `passReadinessWriter` is the injectable - // read seam; nil at refresh time → an ad-hoc HermesSettingsWriter - // over the gate's binary (profileRoot default). + // #137 (S4): the Run Pass posture — is the pass profile's provider + // keyed? .unknown NEVER blocks (our own read failure — the spawn's + // honest failure row owns that path); .missingKey names the provider + // so the pane can say what's missing and link to Settings. + // #181: the enum and the refresh live in the PassReadiness module. func readiness(for kind: PassKind) -> PassReadiness { passReadiness[kind] ?? .unknown } - /// Read each pass profile's provider (readSurface, one task group), - /// then each DISTINCT provider's key (readProviderKey). A surface we - /// can't read maps .unknown; a non-empty key maps .ready; no key maps - /// .missingKey with the provider's label. No binaryPath and no - /// injected writer → readiness stays empty (.unknown everywhere). + /// #181: thin delegate — the reads and the keyless fallback live in + /// the PassReadiness module over the provider descriptor. No + /// binaryPath and no injected writer → readiness stays empty + /// (.unknown everywhere). func refreshPassReadiness() async { guard let writer = passReadinessWriter ?? binaryPath.map({ HermesSettingsWriter(hermesBinary: $0) }) else { return } - var providers: [ProfileSurface: ModelProvider] = [:] - await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in - for surface in [ProfileSurface.pass1, .pass2] { - group.addTask { await (surface, try? writer.readSurface(surface)) } - } - for await (surface, read) in group { - providers[surface] = read?.config.provider - } - } - var keys: [ModelProvider: String] = [:] - for provider in Set(providers.values.compactMap(\.self)) { - var key = await (try? writer.readProviderKey(provider: provider)) ?? "" - // #175: nous runs on the shared Portal login — an empty `.env` - // key is not a blocker when the session's agent_key exists (the - // engine's own credential; API key and subscription bill the - // same account credits). - if provider == .nous, key.isEmpty { - let path = portalAuthPath - key = await Task.detached(priority: .utility) { - PortalAuth.sessionKey(authJSONPath: path) ?? "" - }.value - } - keys[provider] = key - } - for surface in [ProfileSurface.pass1, .pass2] { - let kind: PassKind = surface == .pass1 ? .pass1 : .pass2 - guard let provider = providers[surface] else { - passReadiness[kind] = .unknown - continue - } - if let key = keys[provider], !key.isEmpty { - passReadiness[kind] = .ready - } else { - passReadiness[kind] = .missingKey(providerLabel: provider.label) - } - } + passReadiness = await PassReadiness.refresh( + writer: writer, + portalAuthPath: portalAuthPath, + ) } /// Send a prompt and stream the reply into the ACTIVE session's diff --git a/Museion/PassReadiness.swift b/Museion/PassReadiness.swift new file mode 100644 index 0000000..6991586 --- /dev/null +++ b/Museion/PassReadiness.swift @@ -0,0 +1,79 @@ +// +// PassReadiness.swift +// Museion +// + +// ## Scenario: pass readiness over the provider descriptor +// From #181 +// +// Given the pass profiles' providers read through the settings seam +// When pass readiness refreshes +// Then each pass surface maps to ready / missingKey / unknown through the +// ONE credential resolution (provider key, else the Portal session key +// for keyless providers) — the session model stores the verdicts and +// itself reads no keys and no auth files. + +import Foundation + +/// #181: per-pass readiness — ready / missingKey / unknown, computed +/// over the provider descriptor. Formerly the session model's #137 +/// nested enum: the profile reads (surface provider, `.env` key, Portal +/// auth store) live HERE now; MentorSessionModel stores the verdicts its +/// pane observes. +nonisolated enum PassReadiness: Equatable { + case ready + case missingKey(providerLabel: String) + case unknown + + /// Read each pass surface's provider (readSurface, one task group), + /// then resolve each DISTINCT provider's credential through the ONE + /// rail (ProviderCredential — provider key, else the Portal session + /// key for keyless providers). A surface we can't read maps .unknown + /// (our own read failure never blocks — the spawn's honest failure row + /// owns that path); a refused credential maps .missingKey naming the + /// provider. Nil/empty `base_url` means the provider's default family + /// (the family the session key is allowed to ride). + static func refresh( + writer: any SettingsWriting, + portalAuthPath: String, + ) async -> [PassKind: PassReadiness] { + let surfaces = [ProfileSurface.pass1, .pass2] + var reads: [ProfileSurface: (config: SurfaceModelConfig, baseURL: String?)] = [:] + await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in + for surface in surfaces { + group.addTask { await (surface, try? writer.readSurface(surface)) } + } + for await (surface, read) in group { + if let read { + reads[surface] = read + } + } + } + var envKeys: [ModelProvider: String] = [:] + for provider in Set(reads.values.map(\.config.provider)) { + envKeys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? "" + } + var verdicts: [PassKind: PassReadiness] = [:] + for surface in surfaces { + let kind: PassKind = surface == .pass1 ? .pass1 : .pass2 + guard let read = reads[surface] else { + verdicts[kind] = .unknown + continue + } + let provider = read.config.provider + let endpoint = read.baseURL.flatMap { $0.isEmpty ? nil : $0 } ?? provider.defaultEndpoint + switch await ProviderCredential.resolve( + provider: provider, + envKey: envKeys[provider] ?? "", + endpoint: endpoint, + portalAuthPath: portalAuthPath, + ) { + case .key: + verdicts[kind] = .ready + case .refused: + verdicts[kind] = .missingKey(providerLabel: provider.label) + } + } + return verdicts + } +} diff --git a/Museion/PostsModelPasses.swift b/Museion/PostsModelPasses.swift index c66387c..cbd93fc 100644 --- a/Museion/PostsModelPasses.swift +++ b/Museion/PostsModelPasses.swift @@ -11,6 +11,50 @@ import Foundation // MARK: Pass orchestration (#24, S3.1) +// MARK: #181: the ONE guard rail behind runPass and blindRead + +extension PostsModel { + /// #181: the shared guard grammar every engine run passes before it + /// touches anything — nothing already running (a pass or a Blind + /// Read, named honestly whichever runner asks), the mentor not + /// mid-reply with its engine ready, and an open SAVED piece (never a + /// draft, the external guest, or a held #111 guard ask). The refusal + /// lands in lastError naming the blocker; answers the open piece's id + /// and session — the run's target — or nil (refused). + func guardOpenPieceRun( + _ action: String, + mentor: MentorSessionModel, + ) -> (id: String, session: EditorSession)? { + guard runningPass == nil else { + lastError = "A pass is already running." + return nil + } + guard !runningBlindRead else { + lastError = "A Blind Read is already running." + return nil + } + guard !mentor.isStreaming else { + lastError = "The mentor is mid-reply — stop it or wait." + return nil + } + guard mentor.phase.isReady else { + lastError = "The mentor engine isn't ready — wait for it or restart it." + return nil + } + guard let session, + let id = session.postID, + id == selectedPostID, + draft == nil, + externalSession == nil, + outlineGuardPieceID == nil + else { + lastError = "Open a saved post to run \(action)." + return nil + } + return (id, session) + } +} + extension PostsModel { /// #24 (S3.1): run one structured critique pass over the OPEN piece. /// The pre-pass snapshot lands before the engine sees the text; the @@ -20,38 +64,14 @@ extension PostsModel { /// and never when fix cards resolve. Passes run in any order /// (advancePassState is monotonic). func runPass(_ kind: PassKind, mentor: MentorSessionModel) async { - guard runningPass == nil, !runningBlindRead else { - lastError = "A pass is already running." - return - } - guard !mentor.isStreaming else { - lastError = "The mentor is mid-reply — stop it or wait." - return - } - guard mentor.phase.isReady else { - lastError = "The mentor engine isn't ready — wait for it or restart it." - return - } + guard let (id, session) = guardOpenPieceRun("a pass", mentor: mentor) else { return } // #137 (S4): the pass profile's provider has no key — name it and - // point at Settings, BEFORE the open-piece guard so nothing writes - // to disk (not even the pre-pass snapshot). + // point at Settings. Nothing has touched disk yet (the snapshot + // comes after this guard). if case let .missingKey(label) = mentor.readiness(for: kind) { lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys." return } - // The pass targets the open Piece: a never-saved draft has no - // folder, and the external guest and a held #111 guard ask are - // not Pieces. - guard let session, - let id = session.postID, - id == selectedPostID, - draft == nil, - externalSession == nil, - outlineGuardPieceID == nil - else { - lastError = "Open a saved post to run a pass." - return - } guard flushOrAbort(id) else { return } // the engine reads disk // #179: the model owns the Home; an open piece implies a bound one. guard let home = watchedHome else { return } @@ -117,33 +137,7 @@ extension PostsModel { /// the transient transcript and die with it. The writer stays judge of /// record. func blindRead(mentor: MentorSessionModel) async { - guard runningPass == nil else { - lastError = "A pass is already running." - return - } - guard !runningBlindRead else { - lastError = "A Blind Read is already running." - return - } - guard !mentor.isStreaming else { - lastError = "The mentor is mid-reply — stop it or wait." - return - } - guard mentor.phase.isReady else { - lastError = "The mentor engine isn't ready — wait for it or restart it." - return - } - // Same open-piece rule as a pass: the read judges ONE saved piece. - guard let session, - let id = session.postID, - id == selectedPostID, - draft == nil, - externalSession == nil, - outlineGuardPieceID == nil - else { - lastError = "Open a saved post to run a Blind Read." - return - } + guard let (id, session) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return } guard flushOrAbort(id) else { return } // #179: the model owns the Home; an open piece implies a bound one. guard let home = watchedHome, diff --git a/Museion/ProviderProbe.swift b/Museion/ProviderProbe.swift index abea6e0..8855d5a 100644 --- a/Museion/ProviderProbe.swift +++ b/Museion/ProviderProbe.swift @@ -142,24 +142,19 @@ nonisolated enum ProviderProbe { /// Responses API (`/v1/responses`, 2026-10-28 maintainer correction — /// chat-completions is the retired path). Nous (#175, live-probed /// 2026-11-05) is plain OpenAI chat-completions on a versioned base. - /// A trailing slash on a hand-edited endpoint never doubles up. A - /// non-URL endpoint is nil (URL(string:) happily percent-encodes "not a - /// url" — the scheme check is what actually rejects garbage; probe - /// reports unreachable, never traps). + /// #181: the paths live on the descriptor's dialect — a trailing slash + /// on a hand-edited endpoint never doubles up. A non-URL endpoint is + /// nil (URL(string:) happily percent-encodes "not a url" — the scheme + /// check is what actually rejects garbage; probe reports unreachable, + /// never traps). static func chatURL(for provider: ModelProvider, endpoint: String) -> URL? { - let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint - let path = switch provider { - case .anthropic: "/v1/messages" - case .openaiAPI: "/responses" - case .zai, .nous: "/chat/completions" - } - return httpURL(base + path) + let base = ModelProvider.trimmedEndpoint(endpoint) + return httpURL(base + provider.dialect.chatPath) } static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? { - let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint - let path = provider == .anthropic ? "/v1/models" : "/models" - return httpURL(base + path) + let base = ModelProvider.trimmedEndpoint(endpoint) + return httpURL(base + provider.dialect.modelsPath) } private static func httpURL(_ string: String) -> URL? { @@ -172,14 +167,15 @@ nonisolated enum ProviderProbe { /// Bearer everywhere except Anthropic: `x-api-key` + a pinned /// `anthropic-version` (factsheet §2.1 — never send none). Nous rides /// Bearer too — the portal accepts the session agent_key and an API - /// key interchangeably (#175). + /// key interchangeably (#175). #181: the shape keys off the + /// descriptor's auth mode. static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) { - switch provider { - case .zai, .openaiAPI, .nous: + switch provider.authMode { + case .bearer: request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") - case .anthropic: + case let .headerKey(version): request.setValue(key, forHTTPHeaderField: "x-api-key") - request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version") + request.setValue(version, forHTTPHeaderField: "anthropic-version") } } @@ -255,10 +251,10 @@ nonisolated enum ProviderProbe { return failure } let (text, finish): (String, String?) - switch provider { + switch provider.dialect { case .anthropic: (text, finish) = anthropicStream(events) - case .openaiAPI: (text, finish) = responsesStream(events) - case .zai, .nous: (text, finish) = chatCompletionsStream(events) + case .responses: (text, finish) = responsesStream(events) + case .chatCompletions: (text, finish) = chatCompletionsStream(events) } if !text.isEmpty { return .works(latencyMS: latencyMS, modelCount: modelCount) diff --git a/Museion/SettingsModel.swift b/Museion/SettingsModel.swift index 5e4474c..a11f76e 100644 --- a/Museion/SettingsModel.swift +++ b/Museion/SettingsModel.swift @@ -89,6 +89,78 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable { case .nous: "NOUS_API_KEY" } } + + /// #181: the wire family the probe speaks. The SELECTOR is data — + /// endpoint paths, auth shape, and the SSE decoder pick ride the + /// dialect; the per-family code (request bodies, stream decoders) + /// stays separate functions, not switch clothing. + nonisolated enum Dialect: Sendable { + /// Anthropic `/v1/messages`, header-key auth, Anthropic SSE. + case anthropic + /// OpenAI Responses `/responses`, Bearer, Responses SSE. + case responses + /// OpenAI chat-completions (`/chat/completions` — z.ai and the + /// Nous Portal), Bearer, chat-completions SSE. + case chatCompletions + + /// The chat-call path appended to the endpoint base (callers trim + /// a trailing slash off the base first). + var chatPath: String { + switch self { + case .anthropic: "/v1/messages" + case .responses: "/responses" + case .chatCompletions: "/chat/completions" + } + } + + var modelsPath: String { + switch self { + case .anthropic: "/v1/models" + case .responses, .chatCompletions: "/models" + } + } + } + + /// #181: the provider's wire family (the probe's dialect selector). + var dialect: Dialect { + switch self { + case .zai, .nous: .chatCompletions + case .anthropic: .anthropic + case .openaiAPI: .responses + } + } + + /// #181: the auth-header shape (factsheet §2.1) — Bearer everywhere + /// except Anthropic's `x-api-key` + a pinned `anthropic-version` + /// (never send none). + nonisolated enum AuthMode: Sendable { + /// `Authorization: Bearer `. + case bearer + /// `x-api-key: ` plus the pinned version header. + case headerKey(version: String) + } + + var authMode: AuthMode { + switch self { + case .zai, .openaiAPI, .nous: .bearer + case .anthropic: .headerKey(version: "2023-06-01") + } + } + + /// #175: keyless providers run on the shared Hermes Portal login — + /// the engine's own credential stands in when no API key is pasted + /// (API key and subscription bill the same account credits). + var keyless: Bool { + self == .nous + } + + /// The endpoint with any trailing slash trimmed — the ONE + /// normalization every endpoint consumer (the probe's URL builders, + /// the credential rail's official-endpoint gate) compares against; + /// divergent trims would gate or route differently in silence. + nonisolated static func trimmedEndpoint(_ endpoint: String) -> String { + endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint + } } nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable { @@ -169,6 +241,44 @@ nonisolated enum PortalAuth { } } +/// #181: THE credential resolution — the provider's own API key, else the +/// shared Portal session key for keyless providers. Settings' Test +/// Connection and pass readiness both call this ONE function, so the +/// fallback can no longer drift between them. The implicit session +/// credential only ever rides the OFFICIAL endpoint (#175 finish-audit: +/// cleartext http / foreign host = silent exfiltration with no on-screen +/// cue) — a keyless provider on any other endpoint refuses with the +/// paste-a-key path. Nonisolated async, so the auth-store read never runs +/// on the main actor. +nonisolated enum ProviderCredential { + enum Resolved: Equatable { + case key(String) + case refused(String) + } + + static func resolve( + provider: ModelProvider, + envKey: String, + endpoint: String, + portalAuthPath: String, + ) async -> Resolved { + if !envKey.isEmpty { + return .key(envKey) + } + guard provider.keyless else { + return .refused("no API key set — paste the key first") + } + let trimmed = ModelProvider.trimmedEndpoint(endpoint) + guard trimmed == provider.defaultEndpoint else { + return .refused("custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)") + } + guard let sessionKey = PortalAuth.sessionKey(authJSONPath: portalAuthPath) else { + return .refused("no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`") + } + return .key(sessionKey) + } +} + /// The Settings page's state (#135): per-surface model configs, per-provider /// keys, the registry the model combobox reads, and the write path every /// committed change flows through. #136: hydrated from the profiles at pane @@ -367,46 +477,30 @@ final class SettingsModel { /// One probe per provider over the CURRENT key/endpoint state. Guarded /// against stacking; the empty-key precondition makes an unkeyed probe - /// fail fast without touching the network. #175: an unkeyed NOUS probe - /// falls back to the shared Portal session key — the engine's own - /// credential — and names the login path when neither exists. + /// fail fast without touching the network. #181: the credential — + /// provider key, else the shared Portal session key for keyless + /// providers — resolves through the ONE rail pass readiness also calls. func testConnection(for provider: ModelProvider) async { guard testStates[provider] != .running else { return } testStates[provider] = .running - var key = keyConfig(for: provider).apiKey - if provider == .nous, key.isEmpty { - // Finish-audit #175: the session agent_key is an IMPLICIT - // credential (never pasted, field reads empty) — it only ever - // rides the official https endpoint, never a hand-edited one - // (cleartext http / foreign host = silent exfiltration with no - // on-screen cue). Custom endpoints get the paste-a-key refusal. - let endpoint = keyConfig(for: .nous).endpoint - let trimmed = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint - guard trimmed == ModelProvider.nous.defaultEndpoint else { - testStates[provider] = .done(.authFailed( - "custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)", - )) - return - } - let path = portalAuthPath - key = await Task.detached(priority: .utility) { - PortalAuth.sessionKey(authJSONPath: path) ?? "" - }.value - if key.isEmpty { - testStates[provider] = .done(.authFailed( - "no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`", - )) - return - } - } - let config = ProviderProbe.Config( + let keyConfig = keyConfig(for: provider) + switch await ProviderCredential.resolve( provider: provider, - endpoint: keyConfig(for: provider).endpoint, - apiKey: key, - model: probeModel(for: provider), - ) - let transport = probeTransport - testStates[provider] = await .done(ProviderProbe.probe(config, transport: transport)) + envKey: keyConfig.apiKey, + endpoint: keyConfig.endpoint, + portalAuthPath: portalAuthPath, + ) { + case let .key(key): + let config = ProviderProbe.Config( + provider: provider, + endpoint: keyConfig.endpoint, + apiKey: key, + model: probeModel(for: provider), + ) + testStates[provider] = await .done(ProviderProbe.probe(config, transport: probeTransport)) + case let .refused(message): + testStates[provider] = .done(.authFailed(message)) + } } /// The model the probe proves generation on: the first surface on this diff --git a/Museion/SettingsPagesView.swift b/Museion/SettingsPagesView.swift index 1453205..d940400 100644 --- a/Museion/SettingsPagesView.swift +++ b/Museion/SettingsPagesView.swift @@ -251,10 +251,11 @@ private struct ProviderKeyBlock: View { .font(.system(size: 11.5)) .foregroundStyle(DesignTokens.muted) } - if provider == .nous { + if provider.keyless { // #175: the engine auths nous through hermes' own Portal // login (device-code, shared across profiles) — the key // field is optional and bills the same account credits. + // #181: keyed off the descriptor, like every provider fact. Text( "Chats ride your Hermes Portal login — no key needed once hermes is signed in (hermes auth add nous). " + "A pasted key bills the same account credits (API or subscription).", diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index d9c2772..70e9813 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -39,12 +39,12 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — - `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface. - `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay. - `FixCardApplyTests` — fix-card apply/skip/done lifecycle. -- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally). +- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load). - `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop. - `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest. - `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe. - `ProseListTests`, `ProseRekeyTests` — prose list model + fold rendering, fold rekey pipeline. -- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests` — settings model, real CLI write path, probe decode + request builders. +- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests`, `ProviderCredentialTests` — settings model, real CLI write path, probe decode + request builders, the #181 ONE credential resolution (pasted key wins, keyless fallback on the official endpoint, custom-endpoint and no-login refusals). - `WordBoundaryTruncationTests`, `PolishSeamTests`, `ResearchCandidateTests`, `PersonaLoadOrderTests` — UI pure seams, research candidates, persona payload contract (the four-shared-sections + load-order pins). ## Verification diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index 4011e56..f8da5fb 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -110,7 +110,7 @@ func textRows(of model: MentorSessionModel) -> [String] { await model.runPass(.pass1, mentor: mentor) - #expect(model.lastError?.contains("post") == true) + #expect(model.lastError == "Open a saved post to run a pass.") // Nothing landed on disk — the draft never even materialized a folder. #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts").path)) } diff --git a/MuseionTests/PostsModelTests.swift b/MuseionTests/PostsModelTests.swift index 3675ba4..0d7542f 100644 --- a/MuseionTests/PostsModelTests.swift +++ b/MuseionTests/PostsModelTests.swift @@ -581,9 +581,13 @@ struct PostsModelWriteRailTests { try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true) rig.model.bind(home: homeB) // the Settings repoint, mid-pass // Release the held turn as a NORMALLY ended one — .ended + no refusal. - // #require: nothing held means the parked prompt already timed out - // under machine load — fail loudly, not on a confusing nil strip. + // Poll for the PARK first: runningPass flips before the one-shot + // engine spawns, so ending the hold in that window false-fails + // under load (the #30/#147 flake family). #require afterwards: + // nothing held after the poll means the parked prompt hit its + // deadline — fail loudly, not on a confusing nil strip. let engine = try #require(rig.mentor.host.oneShot as? ScriptedEngine) + try await pollUntil { engine.hasHeldPrompt } try #require(engine.endHeldPrompt()) await run.value diff --git a/MuseionTests/ProviderCredentialTests.swift b/MuseionTests/ProviderCredentialTests.swift new file mode 100644 index 0000000..19f7b67 --- /dev/null +++ b/MuseionTests/ProviderCredentialTests.swift @@ -0,0 +1,117 @@ +// +// ProviderCredentialTests.swift +// MuseionTests +// + +// ## Scenario: one credential resolution behind probe and readiness +// From #181 +// +// Given a provider, its `.env` key (possibly empty), and the endpoint the +// key would ride +// When the ONE credential resolution runs — Settings' Test Connection and +// pass readiness both call it +// Then a pasted key always wins, a keyless provider on its official +// endpoint borrows the shared Portal session key, and every other empty +// case refuses honestly — the implicit session credential never rides a +// user-set URL. + +import Foundation +@testable import Museion +import Testing + +@Suite("Provider credential resolution") +struct ProviderCredentialTests { + /// Writes a portal auth store carrying `agent_key` and answers its path. + private func makeAuthFile(key: String) throws -> String { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("cred-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let path = dir.appendingPathComponent("auth.json").path + try #"{"providers":{"nous":{"agent_key":"\#(key)"}}}"#.write(toFile: path, atomically: true, encoding: .utf8) + return path + } + + /// A pasted key always wins — no provider's resolution touches the + /// Portal auth store when its own key is set. + @Test func `pasted key wins for every provider`() async { + let missingAuth = FileManager.default.temporaryDirectory + .appendingPathComponent("cred-missing-\(UUID().uuidString)").path + for provider in ModelProvider.allCases { + let resolved = await ProviderCredential.resolve( + provider: provider, + envKey: "sk-pasted", + endpoint: provider.defaultEndpoint, + portalAuthPath: missingAuth, + ) + #expect(resolved == .key("sk-pasted")) + } + } + + /// A keyed provider with no key refuses the paste path — the probe's + /// old empty-key precondition, now the shared rail's. + @Test func `keyed provider without a key refuses the paste path`() async { + let resolved = await ProviderCredential.resolve( + provider: .anthropic, + envKey: "", + endpoint: ModelProvider.anthropic.defaultEndpoint, + portalAuthPath: "/nonexistent/auth.json", + ) + guard case let .refused(message) = resolved else { + Issue.record("expected a refusal, got \(resolved)") + return + } + #expect(message == "no API key set — paste the key first") + } + + /// The keyless fallback: nous on the official endpoint (trailing slash + /// tolerated) borrows the session's agent_key. + @Test func `keyless provider borrows the portal session key on the official endpoint`() async throws { + let authPath = try makeAuthFile(key: "ak-shared-123") + for endpoint in [ + ModelProvider.nous.defaultEndpoint, + ModelProvider.nous.defaultEndpoint + "/", + ] { + let resolved = await ProviderCredential.resolve( + provider: .nous, + envKey: "", + endpoint: endpoint, + portalAuthPath: authPath, + ) + #expect(resolved == .key("ak-shared-123")) + } + } + + /// Finish-audit #175, on the shared rail: the implicit session + /// credential never rides a user-set URL — a custom endpoint with an + /// empty key refuses even though the login exists. + @Test func `the session key never rides a custom endpoint`() async throws { + let authPath = try makeAuthFile(key: "ak-shared-123") + let resolved = await ProviderCredential.resolve( + provider: .nous, + envKey: "", + endpoint: "http://proxy.example/v1", + portalAuthPath: authPath, + ) + guard case let .refused(message) = resolved else { + Issue.record("expected the custom-endpoint refusal, got \(resolved)") + return + } + #expect(message.contains("paste an API key")) + } + + /// Keyless with neither key nor login names the portal login path, + /// not a bare "no key". + @Test func `keyless without key or login names the portal path`() async { + let resolved = await ProviderCredential.resolve( + provider: .nous, + envKey: "", + endpoint: ModelProvider.nous.defaultEndpoint, + portalAuthPath: "/nonexistent/auth.json", + ) + guard case let .refused(message) = resolved else { + Issue.record("expected a refusal, got \(resolved)") + return + } + #expect(message.contains("hermes auth add nous")) + } +} diff --git a/MuseionTests/ScriptedEngine.swift b/MuseionTests/ScriptedEngine.swift index 480edb7..c36d962 100644 --- a/MuseionTests/ScriptedEngine.swift +++ b/MuseionTests/ScriptedEngine.swift @@ -157,6 +157,14 @@ final class ScriptedEngine: EngineTransport, @unchecked Sendable { queue.sync { heldLoad != nil } } + /// True while a hangOnPrompt prompt is parked — the #179 repoint pin + /// polls for the PARK (runningPass flips before the one-shot engine + /// even spawns; ending the hold in that window false-fails under load, + /// the #30/#147 flake family). + var hasHeldPrompt: Bool { + queue.sync { heldPromptID != nil } + } + // MARK: EngineTransport /// The fake always spawns cleanly — there is no process. diff --git a/docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md b/docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md new file mode 100644 index 0000000..162ce13 --- /dev/null +++ b/docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md @@ -0,0 +1,66 @@ +# Provider descriptor + Pass Readiness — provider facts as data, one credential resolution + +> **Date:** 2026-11-10 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/181 + +## Goal + +Issue #181 (from the 2026-11-09 architecture review, settings cluster): per-provider facts become **data on the provider enum** instead of five switches across Settings, the probe, and the pane; **one credential-resolution function** (provider key, else the shared Portal session key for keyless providers) serves Test Connection and pass readiness; **pass readiness leaves the session model** into its own module; the probe's **dialect selector keys off the descriptor** (SSE decoders stay separate functions); rider: **runPass and blindRead share one guard helper**. Red line (ADR-0014): provider metadata only — no app-side model-settings store. Blocked by #178 (closed — verified before work started). + +## What Was Done + +- `ModelProvider` is now the provider-descriptor table: existing facts (label, effort ladder, flagship, default endpoint, env var) joined by `dialect` (`Dialect` enum: chat/models paths + the SSE decoder selector), `authMode` (`AuthMode`: Bearer vs Anthropic's `x-api-key` + pinned version), `keyless` (nous rides the Portal login), and `trimmedEndpoint(_:)` — the ONE trailing-slash normalization shared by the probe's URL builders and the credential gate. +- `ProviderCredential.resolve` (SettingsModel.swift) — the ONE credential rail: pasted key wins; keyless providers fall back to the Portal session key **only on the official default endpoint**; refusals name the paste-a-key path or `hermes auth add nous`. Settings' `testConnection` and pass readiness both call it (the twice-implemented #175 fallback is now one function). +- `Museion/PassReadiness.swift` (new) — the readiness module: reads each pass surface's provider + `.env` key through the `SettingsWriting` seam, resolves credentials through `ProviderCredential`, answers `[PassKind: PassReadiness]`. `MentorSessionModel.refreshPassReadiness` is a thin delegate; the model reads no keys and no auth files. +- `ProviderProbe` — `chatURL`/`modelsURL`/`applyAuth`/`decodeChat` select by `provider.dialect` / `provider.authMode`; the per-dialect request bodies and stream decoders stay separate functions. +- `PostsModelPasses.guardOpenPieceRun` — the ONE guard rail behind `runPass` and `blindRead` (nothing running, mentor not mid-turn, engine ready, open saved piece); returns `(id, session)`; refusal strings byte-identical to the old per-runner messages except the busy message now names the actual blocker. +- `ProviderCredentialTests` (new, 5 pins) — the shared credential suite; `ScriptedEngine.hasHeldPrompt` + a poll in the #179 repoint pin de-flake the spawn-window race; PassRunTests' open-piece pin tightened to the exact interpolated message. +- DOX pass: `Museion/AGENTS.md` (Settings bullet rewritten as the descriptor table + credential rail + PassReadiness file; PostsModel runPass chain + MentorSessionModel readiness bullets updated), `MuseionTests/AGENTS.md` (suite map + the hasHeldPrompt note). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Readiness gained the official-endpoint gate (behavior delta) | The unified rail carries the #175 exfiltration posture: a nous pass profile on a user-set `base_url` with no pasted key now reads `.missingKey` (was `.ready` — the old session-model fallback had NO endpoint gate). Both finish-audit reviewers rate this the correct tightening; the remedy (paste a key) is consistent. | +| missingKey guard moved AFTER the shared open-piece rail | The rail owns the common grammar; the kind-specific readiness check stays caller-side. "No piece open + no key" now shows "Open a saved post" (was the key message). The load-bearing invariant — key guard before anything touches disk — holds; no test pinned the old order. Flagged to the maintainer. | +| z.ai branches stay provider-keyed | Key-type UI toggle, endpoint families, thinking knobs, and the 1113 error decode are zai-specific config, not provider metadata; the ticket blesses "genuinely different code, not switch clothing". | +| `refreshPassReadiness` stays as a thin delegate | Museion/AGENTS.md pins the model as the pane's observable; the module computes, the model stores. | +| `PassKind`-keyed refresh return, surfaces baked in | One caller, constant `[.pass1, .pass2]` — the parameter was a dead degree of freedom (finish-audit ponytail trim). | +| De-flaked the #179 repoint pin instead of re-running | `runningPass` flips before the one-shot engine parks its prompt; `endHeldPrompt()` fired into that window false-fails under parallel-suite load — the #30/#147 green-by-luck family. Fix the test's timing assumption, not the schedule. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Full-suite run 1: `home repoint mid-pass refuses the advance` failed (`endHeldPrompt()` → false) | The pin polled `runningPass`, which flips BEFORE the one-shot engine spawns and parks its prompt — the poll passed, the park hadn't happened; parallel-suite load widened the window | Added `ScriptedEngine.hasHeldPrompt`; the pin now polls for the PARK, then requires the release (`#require` still fails loudly on a genuine timeout) | +| `-only-testing:MuseionTests/` filters silently matched subsets (12 of 71 expected tests) | Several suites are free functions / differently-named structs — the known #31 trap; verified against per-file `@Test` counts | Ran the whole MuseionTests suite and verified by the xcresult EXECUTED count (668), never the SUCCEEDED banner | +| A patch intended as `provider.keyless` mangled a newline in SettingsPagesView instead | old_string/new_string differed only by trailing newline | Re-read the region, restored the newline, applied the real change | +| detect-changes listed serif-writing files this session never touched | Index-staleness relative to a pre-#180 index state; `git status` showed them unmodified | Trusted `git status` as the commit's file list; analyze rebuilt the index | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/SettingsModel.swift` | Descriptor additions (dialect, authMode, keyless, trimmedEndpoint), `ProviderCredential`, `testConnection` through the rail | +| `Museion/PassReadiness.swift` | NEW — the readiness module over the descriptor + credential rail | +| `Museion/MentorSessionModel.swift` | Nested `PassReadiness` + refresh body removed; thin delegate remains (−~65 lines) | +| `Museion/ProviderProbe.swift` | URL/auth/SSE selectors key off the descriptor | +| `Museion/PostsModelPasses.swift` | `guardOpenPieceRun` shared rail; both runners rewritten onto it | +| `Museion/SettingsPagesView.swift` | Keyless branch keys off `provider.keyless` | +| `MuseionTests/ProviderCredentialTests.swift` | NEW — the shared credential suite (5 pins) | +| `MuseionTests/ScriptedEngine.swift` | `hasHeldPrompt` park observable | +| `MuseionTests/PostsModelTests.swift` | Repoint pin polls the park first | +| `MuseionTests/PassRunTests.swift` | Open-piece pin tightened to the exact message | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass (+ gitnexus stats bump) | + +## Open Items & Next Steps + +- [x] All six acceptance criteria met; full suite green +- [ ] Deferred (audit): cross-repo coupling — `defaultEndpoint` assumes hermes' unset-`base_url` default matches the app's constant (comment names it; revisit only if the portal URL moves) +- [ ] Deferred (audit): `auth.json` read once per surface (twice when both passes ride nous) — local JSON, off-main, pane-entry only; cache when it ever shows +- [ ] #182 ProfileLayout + config-set rail is the next ticket in the architecture batch + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 970ccc0..7b0f155 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-10 | issue | [20261110-issue181-provider-descriptor-pass-readiness_log.md](20261110-issue181-provider-descriptor-pass-readiness_log.md) | Provider facts one table on the enum; one credential rail serves probe + readiness; readiness module; shared run guard (#181) | | 2026-11-10 | issue | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | One PostFrontmatter codec: lenient read + three byte-identical write postures, named eligibility predicates both gates consume | | 2026-11-09 | issue | [20261109-issue179-postsmodel-write-rail_log.md](20261109-issue179-postsmodel-write-rail_log.md) | One `performWrite` rail pairs every library write with one rescan and owns the strip; model owns the Home (#179) | | 2026-11-09 | issue | [20261109-issue178-extract-engine-host-transport-seam_log.md](20261109-issue178-extract-engine-host-transport-seam_log.md) | Engine lifecycle → EngineHost behind the EngineTransport seam; scripted in-process tests, one real smoke per surface |