diff --git a/AGENTS.md b/AGENTS.md index 68dd168..3f3290e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (5099 symbols, 19010 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** (5172 symbols, 19414 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). @@ -185,18 +185,16 @@ This project is indexed by GitNexus as **museion** (5099 symbols, 19010 relation Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent: - | Date | Log | |------|-----| -| 2026-10-27 | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](docs/devlog/20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | -| 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](docs/devlog/20261027-issue135-profiles-s2-settings-page-ui_log.md) | -| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | -| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md) | -| 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | -| 2026-10-22 | [20261022-issue29-research-library-light_log.md](docs/devlog/20261022-issue29-research-library-light_log.md) | -| 2026-10-22 | [20261022-issue28-session-lifecycle-ui_log.md](docs/devlog/20261022-issue28-session-lifecycle-ui_log.md) | -| 2026-10-21 | [20261021-issue27-dismiss-decay-learnings_log.md](docs/devlog/20261021-issue27-dismiss-decay-learnings_log.md) | -| 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) | -| 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) | - +| 2026-10-28 | issue | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) | Pass engines on-demand per profile, transient transcripts, chat restart deferred mid-turn, missing-key Run Pass — 2 race fixes | +| 2026-10-27 | issue | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | Profiles S3: settings write path (config set + .env), Test Connection probe, three dogfood rounds, three-reviewer audit | +| 2026-10-27 | issue | [20261027-issue135-profiles-s2-settings-page-ui_log.md](20261027-issue135-profiles-s2-settings-page-ui_log.md) | #135 Profiles S2: variant C Settings sidebar+detail over the SettingsWriting seam; NSComboBox stale-stringValue dogfood fix; 432 tests | +| 2026-10-27 | issue | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | #134 Profiles S1: ×3 surface registry + provisioner, master-symlink skills with byte-match migration, three-profile backup; 412 tests | +| 2026-10-22 | issue | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | #31 S5.1: Swift-native first-draft stats stamped in place at pass invocation; two frontmatter-erasure bugs fixed; finish-audit fanout — 396 tests | +| 2026-10-22 | issue | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | #30 lands: session-born Posts stamp origin: ai, brainstorm flavor, shared composer, and the real-engine resume wire fix. | +| 2026-10-22 | issue | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) | #29 research rail: submit_research_notes candidates in-session, ask-before keep into research/, resume replay pin, audit fixes — targeted suites green | +| 2026-10-22 | issue | [20261022-issue28-session-lifecycle-ui_log.md](20261022-issue28-session-lifecycle-ui_log.md) | #28 Session lifecycle: multi-session model + names-only roster, pane, pass auto-create, finish-audit with 7 fixes — 359 tests green | +| 2026-10-21 | issue | [20261021-issue27-dismiss-decay-learnings_log.md](20261021-issue27-dismiss-decay-learnings_log.md) | #27 dismiss & decay Learnings: per-type pass clock, frontmatter decay state, consult filtering, two review waves with 5 fixes | +| 2026-10-21 | issue | [20261021-issue26-promote-consult-learnings_log.md](20261021-issue26-promote-consult-learnings_log.md) | #26 promote/consult Learnings: teaching-shape files, on-disk-truth promote, symlink guard, Learnings pane — 329 tests green | diff --git a/CHANGELOG.md b/CHANGELOG.md index 85bd88f..3deb538 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **mentor:** Profiles S4 — per-surface engine lifecycle + model-switch UX (#137) — passes run on their OWN one-shot engines (`hermes acp -p museion-passN` spawned per pass run, torn down at the verdict — a model switch costs nothing, the next spawn reads fresh config) streaming into transient unrostered transcripts (#129: one Sessions surface over the chat engine); the Chat engine stays resident and a Chat model change in Settings restarts it in place, deferred to turn end while a reply streams; Run Pass names the missing provider key and disables with an Open Settings link until the key lands (pane re-entry re-checks). Finish-audit (3 reviewers) fixed a post-await activation steal that could flip the surface mid-pass and lose the Cancel (one `claimActive` gate), plus a PRE-EXISTING `rescan` bug where a stale scan snapshot "vanished" a just-opened piece and killed its session with unflushed edits. Suite 477 (issue #137) + - **settings:** Profiles S3 — the real write path + Test Connection (#136) — every Settings change now persists: model/effort writes ride the engine's own CLI (`hermes -p config set/unset` model.provider/default/reasoning_effort/base_url, wire-verified) and provider keys upsert `VAR=value` into ALL THREE profiles' `.env` (0600, foreign lines preserved, line-broken values refused at the sink — an env-file injection guard); hydration reads model blocks and keys back at pane open, so a restart neither blanks the UI nor refuses Test Connection, and a custom z.ai base_url survives instead of being clobbered to a family default. Per-target writes coalesce AND chain past the debounce guard — the last edit is always the last write to land. Test Connection is a two-step probe (`GET /models` then a minimal streaming chat) with honest decode per the factsheet: z.ai 1113 → wrong key type, 401s → auth failed with request id, finish=length → starved, empty 200 → request failed. Live-probed wire corrections: `Content-Type: application/json` on every request (URLSession defaults to form-urlencoded — z.ai answers 200 with an error envelope), OpenAI speaks the Responses API (`/responses`, `input` + `max_output_tokens`, flagship `gpt-6.1-sol`), probe token cap 512 (64 starved reasoning models into "no content"). Suite 468; three-reviewer finish-audit fixed a write-ordering race, an `.env` lost-update race, a mid-hydrate stomp, and cut ~30 lines of dead flexibility (issue #136) - **settings:** Profiles S2 — Settings page as sidebar + detail (#130 prototype variant C verdict) — destinations Content (the unchanged Home control) · Pass 1 · Pass 2 · Chat (annotated "· Sessions") · Provider Keys. Each surface page edits its model block over an in-memory model: provider menu, model combobox sourcing Hermes' own registry cache with first-class free text (the seed `claude-sonnet-5-5` reads as *custom (not in registry)* — the default state), per-provider reasoning-effort menu led by "unset · provider default", variant B's current-model headline, and Restore Defaults back to the #132 seed; the Provider Keys page carries endpoint, the z.ai key-type toggle swapping the endpoint family (`/api/paas/v4` ↔ `/api/coding/paas/v4`, custom endpoints survive), and masked keys with reveal. Persistence is S3's — every change routes through an injectable `SettingsWriting` seam whose contract (debounce, secrets never via argv, redacted error text) is frozen now; write failures surface in an orange strip. Dropdown picks commit through `comboBoxSelectionDidChange` reading the selection index — the notification fires before `stringValue` updates (log-observed dogfood fix). Suite 432 (issue #135) diff --git a/Museion/ACPEngineClient.swift b/Museion/ACPEngineClient.swift index 9f496d3..5c79dfa 100644 --- a/Museion/ACPEngineClient.swift +++ b/Museion/ACPEngineClient.swift @@ -109,9 +109,11 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { /// stderr lines (engine logs) — surfaced for the restart prompt's details. var onStderrLine: (@Sendable (String) -> Void)? - init(binaryPath: String) { + /// #137 (S4, ADR-0014): one Hermes profile per LLM surface — the chat + /// engine keeps the default `museion`; pass engines spawn `-p museion-passN`. + init(binaryPath: String, profile: String = "museion") { process.executableURL = URL(fileURLWithPath: binaryPath) - process.arguments = ["acp", "-p", "museion"] + process.arguments = ["acp", "-p", profile] process.standardInput = stdinPipe process.standardOutput = stdoutPipe process.standardError = stderrPipe diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 9bb2e6c..86012c0 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -27,14 +27,14 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. - `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). - `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent). -- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#28: `mentor.beginPassSession(kind:pieceTitle:)` — every pass auto-creates its Session (wire session/new, rostered "Pass N · \", activated; the `runningPass` flag goes live only AFTER these awaits — setting it earlier left a window where the #124 Cancel pin could observe the flag with `isStreaming` still false and the cancel refused, the turn hung)** → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · ")` (the label renders, the wire stub never lands; the prompt lands in the pass's OWN session) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). +- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). - `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here. - `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions. - `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam). - `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/<id>` 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. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), 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. -- 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 <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` 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. +- 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 <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` 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). - 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. `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 `<!--S:N-->` 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 <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, 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 `<pre>` (#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`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error). @@ -71,10 +71,11 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## ACP bridge (S2.2, #14 map) -- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored. -- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): engine state machine (idle/starting/ready/crashed; `isStreaming` Bool; **#28: `.ready` carries NO sessionId — session ids live in the roster**). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`; **#28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)**), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks). **#28: the handshake is initialize ONLY — sessions are created separately (`newSession`/`beginPassSession`/`ensureDefaultSession`), the bridge is session-agnostic.** `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child. - **#28 (S2.3) session lifecycle:** the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId; `rows`/`streamingText`/`streamingThought` are same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged). `SessionEntry` (nonisolated, Codable: `sessionId`/`name`/`pieceTitle`/`createdAt`) + `SessionRoster` (nonisolated; JSON array at `~/Library/Application Support/Museion/sessions.json`, `rosterDirectory` injectable — `init(binaryPath:rosterDirectory:)`; an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). **The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand.** API: `newSession(name:pieceTitle:)` (wire session/new, rostered newest-first, activated), `resumeSession(_)` (wire session/load — the adapter replays full history as `session/update` BEFORE responding; user turns arrive as `user_message_chunk` and RENDER on replay, live-turn echoes stay ignored; **#30 dogfood: the REAL 0.21.5 load response carries NO top-level `sessionId` — the id rides `_meta.hermes.sessionProvenance.acpSessionId`, so extraction accepts both shapes and empty-everywhere alone means the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session; the top-level-only read made every real-engine resume fail as "unknown"**), `forkActiveSession()` (wire session/fork → "<name> (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginPassSession(kind:pieceTitle:)` ("Pass N · \<title\>", rostered + activated — the pass auto-create rail), `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. -- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (running version + orange drift note — **#28: the version shows `activeEntry`'s id alongside, `.ready` no longer carries it**; trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `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/<file>` / `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). +- `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 → "<name> (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginBrainstormSession(pieceTitle:)` (#30: the brainstorm flavor — a "Brainstorm" rostered session whose first turn is `brainstormPrompt`, the normal prompt rail, no new machinery; pinned: roster head + labeled opener + raw prompt absent + reply streams into ITS transcript), `draftCandidateText()` / `draftCandidateText(in:)` (#30: the New-Post-from-Session candidate — the LAST "Mentor: " text row, prefix stripped; user/thought/card/research/raw rows never prefill, blank bodies skipped, and the refusal/connection-shaped rows sharing the display prefix are excluded — ponytail-marked until SessionRow carries speaker identity), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. **#29 (S8.1–S8.3) research candidates:** `ResearchCandidate` (nonisolated: piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote` — `appendToolCall` routes on PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses via `ResearchCandidate.batch` (one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted). `setResearchDisposition(rowID:_:)` flips the ACTIVE session's row in place (unknown id = no-op). `isWritingRow` keeps `.researchNote` visible in the writing voice. + **#137 (S4, ADR-0014) per-surface engine lifecycle:** passes run on their OWN one-shot engines — `runPass(kind:stub:pieceTitle:)` spawns `ACPEngineClient(binaryPath:, profile: ProfileSurface(passKind:))` (museion-passN), streams the verdict into a TRANSIENT unrostered transcript under `passTranscriptKey` ("pass", the active entry lives only for the run — #129: passes are never rostered; `handleNotification` maps the pass wire sid onto the key), and tears the engine down at the verdict (`teardownPassEngine`; onCrash deliberately nil — a pass-engine crash lands the honest failure row, never the crash card; KNOWN EDGE, accepted v1: a chat-engine crash mid-pass flips the pane while the pass completes underneath). The turn pipeline is ONE `turnCore(client:wireSid:key:prompt:label:)` shared by sendPrompt and the pass run (label row, session/prompt, stopReason mapping, buffer flush); `sendPrompt` refuses the pass surface with a visible row (read-only transcript). Restart posture: `restart()` (crash button) and `requestRestart()` (model-change, Settings fires it) share `respawn()` — teardown, fresh spawn, resume the PRE-restart active rostered session (not blindly the newest); `requestRestart` defers to turn end while `isStreaming` (`pendingRestart`, fired from both turn-end defers — a reply is never cut mid-stream) and ignores .idle/.starting (a future spawn reads fresh config). `stopStreaming` routes `session/cancel` to the PASS engine while a pass runs. Internal test observables: `passEngineChildPid`, `isPassEngineRunning`. **Run Pass readiness (#137 acceptance 3, slice B):** `PassReadiness` (ready | missingKey(providerLabel) | unknown) per kind, stored in the class body (`passReadiness`; `passReadinessWriter` = injectable read seam, nil → ad-hoc `HermesSettingsWriter` over the gate's binary, no binaryPath → stays empty); `refreshPassReadiness()` reads both pass profiles' providers in ONE task group, then each DISTINCT provider's key — an unreadable surface maps `.unknown` (never block on our own read failure). `PostsModel.runPass` guards `.missingKey` BEFORE the open-piece guard: `lastError` names the provider and nothing touches disk, not even the pre-pass snapshot. +- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (running version + orange drift note — **#28: the version shows `activeEntry`'s id alongside, `.ready` no longer carries it**; trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing <provider> key —` line under the state row carries a borderless accent **Open Settings** button (`onOpenSettings`, threaded MentorPaneView→PostsPaneView→WorkspaceView's `selection = .settings`, ArchivePaneView closure precedent), the disabled Run's help names the reason, and `.unknown` never disables (the spawn's honest failure owns that path). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). The header's session chip hides while the transient pass transcript (`passTranscriptKey`) owns the active surface, and the pane's `.task` runs `refreshPassReadiness()` before the hosted-test guard — pane re-entry re-fires it, so a key added in Settings re-enables Run Pass. `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + 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/<file>` / `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 ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss). - Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child. diff --git a/Museion/MentorPaneView.swift b/Museion/MentorPaneView.swift index 8ca7a75..7c838aa 100644 --- a/Museion/MentorPaneView.swift +++ b/Museion/MentorPaneView.swift @@ -21,6 +21,9 @@ struct MentorPaneView: View { var posts: PostsModel? /// #24 (S3.1): the Home passes run against. var home: URL? + /// #137 (S4): opens Settings — the missing-key line's way out (nil = + /// previews; PostsPaneView threads WorkspaceView's pane hop). + var onOpenSettings: (() -> Void)? /// #24 (S3.1): the segmented surface — Pass 1 | Pass 2 | Chat. Pass /// modes carry the pass bar; Chat is the freeform surface alone. private enum Mode: Hashable { case pass1, pass2, chat } @@ -30,11 +33,18 @@ struct MentorPaneView: View { /// either way (debug history intact; the toggle flips instantly). @AppStorage("mentorDebugRows") private var debugRows = false - init(model: MentorSessionModel, binaryPath: String?, posts: PostsModel? = nil, home: URL? = nil) { + init( + model: MentorSessionModel, + binaryPath: String?, + posts: PostsModel? = nil, + home: URL? = nil, + onOpenSettings: (() -> Void)? = nil, + ) { _model = State(initialValue: model) self.binaryPath = binaryPath self.posts = posts self.home = home + self.onOpenSettings = onOpenSettings } var body: some View { @@ -48,7 +58,7 @@ struct MentorPaneView: View { case .ready: modePicker if let kind = passKind { - PassBarView(kind: kind, posts: posts, home: home, model: model) + PassBarView(kind: kind, posts: posts, home: home, model: model, onOpenSettings: onOpenSettings) Divider() } if let posts, !posts.openPieceCards.isEmpty { @@ -85,6 +95,10 @@ struct MentorPaneView: View { if let binaryPath { model.binaryPath = binaryPath } + // #137: the Run Pass posture over the pass profiles' keys — + // a no-op without a binaryPath; pane re-entry re-fires this + // task, so a key added in Settings re-enables Run Pass. + await model.refreshPassReadiness() // Hosted unit tests run this app as their runner — never spawn a // real engine child there (it outlives the test session and kills // the runner). @@ -113,7 +127,9 @@ struct MentorPaneView: View { .help(note) } Spacer() - if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId { + // #137: the transient pass transcript carries no session id — the + // chip stays hidden while a pass run owns the active surface. + if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId, sessionId != MentorSessionModel.passTranscriptKey { Text("session \(sessionId.prefix(8))") .font(.caption2) .foregroundStyle(.tertiary) @@ -210,6 +226,8 @@ private struct PassBarView: View { let posts: PostsModel? let home: URL? let model: MentorSessionModel + /// #137 (S4): the missing-key line's way out — WorkspaceView's pane hop. + let onOpenSettings: (() -> Void)? var body: some View { VStack(alignment: .leading, spacing: 8) { @@ -224,11 +242,34 @@ private struct PassBarView: View { Spacer() actions } + // #137: the pass profile's provider has no key — name it and + // offer the way out. A readable-but-keyed profile shows nothing. + if let label = missingKeyLabel { + HStack(spacing: 4) { + Text("Missing \(label) key —") + Button("Open Settings") { + onOpenSettings?() + } + .buttonStyle(.borderless) + .foregroundStyle(DesignTokens.accent) + } + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + } } .padding(.horizontal, 12) .padding(.bottom, 10) } + /// #137: nil unless the pass profile's provider is readable AND unkeyed + /// (.unknown never blocks — the spawn's honest failure owns that path). + private var missingKeyLabel: String? { + if case let .missingKey(label) = model.readiness(for: kind) { + return label + } + return nil + } + /// What the pass does + the predictable cost — or the honest ask when /// no piece is open. private var description: String { @@ -248,7 +289,8 @@ private struct PassBarView: View { } /// Cancel while a pass runs; Run otherwise — disabled with no open - /// piece or while the engine can't take the turn. + /// piece, while the engine can't take the turn, or (#137) while the + /// pass profile's provider has no key (the help names it). @ViewBuilder private var actions: some View { if posts?.runningPass != nil { @@ -256,15 +298,24 @@ private struct PassBarView: View { posts?.cancelPass(mentor: model) } .buttonStyle(.bordered) + } else if let label = missingKeyLabel { + runPassButton + .disabled(true) + .help("\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys.") } else { - Button("Run \(kind.rawValue)") { - guard let posts, let home else { return } - Task { await posts.runPass(kind, home: home, mentor: model) } - } - .buttonStyle(.borderedProminent) - .disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming) + runPassButton + .disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming) } } + + /// The Run button core — shared by the ready and missing-key branches. + private var runPassButton: some View { + Button("Run \(kind.rawValue)") { + guard let posts, let home else { return } + Task { await posts.runPass(kind, home: home, mentor: model) } + } + .buttonStyle(.borderedProminent) + } } #Preview { diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index 7227ae9..785b6e0 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -8,8 +8,17 @@ // (session/new, session/load, session/fork, /compress on the wire), one // transcript per session, and the same-named ACTIVE surface (rows, buffers, // sendPrompt, stop) so the pane and every existing test read unchanged. +// #137 (S4): per-surface engines — passes run on their own one-shot +// engine and stream into a transient unrostered transcript; the chat +// engine gains the model-change restart posture (requestRestart). // +// swiftlint:disable file_length +// One model, one lifecycle story: the class body (state + session rail) and +// the same-file turn-core/engine-lifecycle extension read together; the pass +// engine's stored state can't live in another file (private, MainActor). +// Extraction ticket follows PostsModel's precedent if the file keeps growing. + import Foundation import Observation import os @@ -204,6 +213,20 @@ final class MentorSessionModel { private var client: ACPEngineClient? private var lastPrompt: String? + /// #137 (S4): the TRANSIENT pass engine — spawned per pass run on its + /// own profile, torn down at the verdict, never rostered (#129: passes + /// are one-shot; only the chat engine's sessions are rostered). + private var passClient: ACPEngineClient? + private var passWireId: String? + private var passCancelRequested = false + /// #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 + /// 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)? /// The gate's winning binary path (no re-probe — map decision). Set by the /// app when the gate passes; tests inject directly. @@ -241,8 +264,9 @@ final class MentorSessionModel { client?.childProcessIdentifier } - /// App-quit teardown (#14): close the engine child cleanly. Idempotent. + /// App-quit teardown (#14): close the engine children cleanly. Idempotent. func shutdown() { + teardownPassEngine() shutdownClientDirectly() client = nil clientRef = nil @@ -250,9 +274,11 @@ final class MentorSessionModel { } /// nonisolated deinit + MainActor shutdown share this: client.close() is - /// thread-safe (its own serial queue) and idempotent. + /// thread-safe (its own serial queue) and idempotent. The pass child + /// rides the same rail (#137) — deinit must close it too. private nonisolated func shutdownClientDirectly() { clientRef?.close() + passClientRef?.close() } /// ponytail: a deinit can't touch MainActor state — the client reference is @@ -260,6 +286,9 @@ final class MentorSessionModel { /// wherever `client` is assigned. private nonisolated(unsafe) var clientRef: ACPEngineClient? + /// The pass engine's deinit mirror (clientRef pattern, #137). + private nonisolated(unsafe) var passClientRef: ACPEngineClient? + /// Lazy spawn on first session open. Idempotent per lifecycle. Ensures /// ONE session exists: the default freeform 'Mentor' session on first /// open, otherwise the newest rostered entry activated with a FRESH @@ -277,17 +306,7 @@ final class MentorSessionModel { /// remembers the last prompt so the writer can resend it. func restart() async { guard case .crashed = phase else { return } - client?.close() - client = nil - clientRef = nil - for sid in transcripts.keys { - transcripts[sid]?.streamingText = "" - transcripts[sid]?.streamingThought = "" - } - phase = .starting - await startEngine() - guard case .starting = phase else { return } - await ensureDefaultSession() + await respawn() } private func startEngine() async { @@ -373,6 +392,13 @@ final class MentorSessionModel { /// against unloaded state; a first open creates the default freeform /// 'Mentor' session. private func ensureDefaultSession() async { + // #137 audit fix: a restart completing while a pass runs (crash → + // Restart mid-pass) — the engine is up, mark ready and leave the + // pass surface alone; the newest entry activates on the next open. + guard !isStreaming else { + phase = .ready + return + } if let newest = roster.first { activate(newest) // The resume REPLAYS, unconditionally (finish-audit): the deleted @@ -398,15 +424,6 @@ final class MentorSessionModel { return await createSession(name: name, pieceTitle: pieceTitle) } - /// The pass's own session (#28): wire session/new + roster - /// 'Pass N · <title>' + activate, so the pass prompt streams into ITS - /// transcript. Nil when the engine isn't ready or refuses. - @discardableResult - func beginPassSession(kind: PassKind, pieceTitle: String) async -> SessionEntry? { - guard phase.isReady, client != nil else { return nil } - return await createSession(name: "\(kind.rawValue) · \(pieceTitle)", pieceTitle: pieceTitle) - } - /// #30 (S2.7): the brainstorm flavor — a plain freeform session whose /// first turn is the brainstorm prompt (PRD S2.8: no new machinery). /// Nil when the session couldn't be created; the opener rides the @@ -424,7 +441,8 @@ final class MentorSessionModel { + "and angles for what I want to write — keep replies short and generative, " + "and don't draft prose unless I ask." - /// The shared creation rail behind newSession/beginPassSession. + /// The shared creation rail behind newSession (#137: beginPassSession + /// died with per-surface engines — passes never mint sessions). private func createSession(name: String, pieceTitle: String?) async -> SessionEntry? { // Finish-audit backstop: fork guards !isStreaming; the views disable // these controls mid-turn. A programmatic caller must not switch the @@ -454,10 +472,14 @@ final class MentorSessionModel { return nil } let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date()) + // #137 audit fix: the session/new await above is a suspension — + // a pass may have started under it. Re-check ownership before + // rostering/activating (the entry guard at the top can't see + // this window); claimActive refuses with this function's voice. + guard claimActive(entry, refusedNote: "Session refused — the mentor is mid-turn.") else { + return nil + } roster.insert(entry, at: 0) - transcripts[sid] = SessionTranscript() - activeEntry = entry - phase = .ready saveRoster() return entry } catch { @@ -532,8 +554,13 @@ final class MentorSessionModel { } // Activate WITHOUT resetting the transcript — activate() is for // fresh-transcript activations; the replay already filled this one. - activeEntry = entry - phase = .ready + // #137 audit fix: the session/load await can span a whole pass — + // a resume completing mid-turn must not steal the pass surface + // (a lost Cancel reopens the #124 hole); the replayed rows stay + // in the entry's store for its next click. + guard claimActive(entry, freshTranscript: false, refusedNote: "Resume refused — the mentor is mid-turn.") else { + return false + } return true } catch { replayingSessionId = nil @@ -571,10 +598,12 @@ final class MentorSessionModel { pieceTitle: source.pieceTitle, createdAt: Date(), ) + // #137 audit fix: same post-await ownership re-check as + // createSession/resumeSession — the fork await is a suspension. + guard claimActive(entry, refusedNote: "Fork refused — the mentor is mid-turn.") else { + return nil + } roster.insert(entry, at: 0) - transcripts[sid] = SessionTranscript() - activeEntry = entry - phase = .ready saveRoster() return entry } catch { @@ -604,9 +633,104 @@ final class MentorSessionModel { phase = .ready } + /// #137 audit fix: the ONE activation gate every post-await writer routes + /// through — a session/new/load/fork completing while ANY turn streams + /// (a pass holds the surface for its whole run) must not steal the active + /// entry: Cancel would misroute to the wrong engine (#124 class) and the + /// pane would flip mid-run. Refuses with the caller's row, activates + /// (fresh or replay-filled transcript) otherwise. + private func claimActive(_ entry: SessionEntry, freshTranscript: Bool = true, refusedNote: String) -> Bool { + guard !isStreaming else { + appendRow(.text(refusedNote), to: activeEntry?.sessionId) + return false + } + if freshTranscript { + transcripts[entry.sessionId] = SessionTranscript() + } + activeEntry = entry + phase = .ready + return true + } + private func saveRoster() { SessionRoster.save(roster, directory: rosterDirectory) } +} + +// MARK: Turn core + per-surface engine lifecycle (#137, S4) + +/// Same-file extension — type_body_length posture (MentorPaneView precedent); +/// the turn pipeline and the #137 engine lifecycle read as one unit. +extension MentorSessionModel { + /// #137: the transient pass transcript's key. A pass never mints a + /// roster entry (#129: passes run on their own one-shot engines) — the + /// pass entry lives under this key only for the run; the view layer + /// hides the session chip on it (next slice). + nonisolated static let passTranscriptKey = "pass" + + /// The pass engine's pid — internal test observable (teardown pins). + var passEngineChildPid: pid_t? { + passClient?.childProcessIdentifier + } + + /// True while a pass engine is resident (spawn → verdict). + var isPassEngineRunning: Bool { + passClient != nil + } + + /// #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). + + 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). + 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)) { + keys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? "" + } + 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) + } + } + } /// Send a prompt and stream the reply into the ACTIVE session's /// transcript. Appends the user row first — a non-nil `label` renders @@ -632,30 +756,60 @@ final class MentorSessionModel { guard !prompt.isEmpty, phase.isReady, !isStreaming, let sid = activeEntry?.sessionId else { return .failed } + // #137: the transient pass transcript is surface-only — the pass + // engine is gone after teardown, so the composer must refuse with + // the words visible, never silently drop the text. + guard sid != Self.passTranscriptKey else { + appendRow(.text("Pick or start a session to chat — the pass transcript is read-only."), to: sid) + return .failed + } + guard let client else { return .failed } + isStreaming = true + defer { + isStreaming = false + // #137: a model-change restart requested mid-turn fires now. + firePendingRestartIfRequested() + } + return await turnCore( + client: client, + wireSid: sid, + key: sid, + prompt: prompt, + label: label ?? "You: \(prompt)", + ) + } + + /// The ONE turn pipeline behind sendPrompt and the pass run (#137): the + /// label row, session/prompt, stopReason mapping, and the streaming- + /// buffer flush — one implementation, two engines. + private func turnCore( + client: ACPEngineClient, + wireSid: String, + key: String, + prompt: String, + label: String, + ) async -> TurnOutcome { lastPrompt = prompt - appendRow(.text(label ?? "You: \(prompt)"), to: sid) + appendRow(.text(label), to: key) isStreaming = true defer { // Flush the thinking first (it preceded the message), collapsed. - if let pending = transcripts[sid], !pending.streamingThought.isEmpty { - appendRow(.thought(pending.streamingThought), to: sid) - transcripts[sid]?.streamingThought = "" + if let pending = transcripts[key], !pending.streamingThought.isEmpty { + appendRow(.thought(pending.streamingThought), to: key) + transcripts[key]?.streamingThought = "" } // Flush any streamed-but-unfinished agent text into a row. - if let pending = transcripts[sid], !pending.streamingText.isEmpty { - appendRow(.text("Mentor: \(pending.streamingText)"), to: sid) - transcripts[sid]?.streamingText = "" + if let pending = transcripts[key], !pending.streamingText.isEmpty { + appendRow(.text("Mentor: \(pending.streamingText)"), to: key) + transcripts[key]?.streamingText = "" } isStreaming = false } - // Parity with the phase guard above: never lean on two invariants - // (.ready ⇒ client) where one guard suffices. - guard let client else { return .failed } do { let result = try await client.request( "session/prompt", params: .object([ - "sessionId": .string(sid), + "sessionId": .string(wireSid), "prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]), ]), timeout: Self.promptTimeout, @@ -666,7 +820,7 @@ final class MentorSessionModel { // must not advance on a maybe (review: empty-stopReason bug). guard !stopReason.isEmpty else { return .failed } if stopReason == "refusal" { - appendRow(.text("Mentor: (refused the prompt)"), to: sid) + appendRow(.text("Mentor: (refused the prompt)"), to: key) } if stopReason == "cancelled" { return .cancelled @@ -678,20 +832,171 @@ final class MentorSessionModel { if case .crashed = phase { // Crash card already owns the failure surface. } else { - appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: sid) + appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: key) } return .failed } } + /// #137 (S4, ADR-0014): run one pass on its OWN one-shot engine — + /// spawn `hermes acp -p museion-passN`, stream the verdict into the + /// transient pass transcript, tear the engine down at the verdict. + /// The pass entry is never rostered (#129); the chat engine keeps + /// running untouched. + @discardableResult + func runPass(kind: PassKind, stub: String, pieceTitle: String) async -> TurnOutcome { + guard phase.isReady, !isStreaming, passClient == nil, let binaryPath else { return .failed } + let label = "\(kind.rawValue) · \(pieceTitle)" + // The transient surface: a fresh transcript under the pass key and a + // pass entry that lives only for this run — never rostered, never + // saved (#129: passes are one-shot, the chat engine owns sessions). + transcripts[Self.passTranscriptKey] = SessionTranscript() + activeEntry = SessionEntry( + sessionId: Self.passTranscriptKey, name: label, pieceTitle: pieceTitle, createdAt: Date(), + ) + isStreaming = true + defer { + isStreaming = false + teardownPassEngine() + firePendingRestartIfRequested() + } + // #137 audit: no force-unwrap — the map is total over today's two + // kinds, but a future PassKind case must refuse, not trap. + guard let surface = ProfileSurface(passKind: kind) else { return .failed } + let pass = ACPEngineClient(binaryPath: binaryPath, profile: surface.profileName) + passClient = pass + passClientRef = pass + // KNOWN EDGE (#137, accepted v1): a CHAT-engine crash mid-pass flips + // the pane to the crash card while the pass keeps streaming — the + // pass turn still completes and advances state. Symmetrically, a + // pass-engine crash must NOT flip the pane: onCrash stays nil here — + // the failed pending request lands the honest row below instead. + do { + // Same routing as the chat client (DispatchQueue.main.async keeps + // wire order — see startEngine). + try pass.start { [weak self] method, params in + DispatchQueue.main.async { + self?.handleNotification(method: method, params: params) + } + } + // Slim initialize — engineVersion/versionNote display the CHAT + // engine and must not be overwritten by the pass engine's answer. + _ = try await pass.request("initialize", params: .object([ + "protocolVersion": .number(1), + "clientCapabilities": .object([:]), + "clientInfo": .object([ + "name": .string("Museion"), + "title": .string("Museion"), + "version": .string("0.1"), + ]), + ])) + let result = try await pass.request("session/new", params: .object([ + "cwd": .string(cwdProvider()), + "mcpServers": .array([]), + ])) + guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else { + appendRow(.text("Pass failed — the engine refused a session."), to: Self.passTranscriptKey) + return .failed + } + passWireId = sid + } catch { + appendRow(.text("Pass failed — \(error.localizedDescription)"), to: Self.passTranscriptKey) + return .failed + } + // Cancel clicked while the engine was spawning: stop before the + // prompt — the run ends cancelled, nothing streams. + if passCancelRequested { + appendRow(.text("\(kind.rawValue) cancelled."), to: Self.passTranscriptKey) + return .cancelled + } + return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, prompt: stub, label: label) + } + + /// Kill the pass engine and clear its rail — at the verdict (the defer + /// above) and at shutdown. Idempotent. + private func teardownPassEngine() { + passClient?.close() + passClient = nil + passClientRef = nil + passWireId = nil + passCancelRequested = false + } + /// Stop button while a turn streams (map decision: cancel wired to /// session/cancel, a notification — no response expected). The engine - /// ends the turn (PromptResponse) as its acknowledgement. + /// ends the turn (PromptResponse) as its acknowledgement. #137: while a + /// pass runs, the PASS engine owns the live turn — Cancel must reach it. func stopStreaming() { - guard isStreaming, let sid = activeEntry?.sessionId else { return } + guard isStreaming else { return } + // #137 fix: key the branch on the TRANSIENT ENTRY, not passWireId — + // the wire id is nil until session/new lands, so a Cancel clicked in + // the spawn window fell through to the chat engine and was LOST (the + // pass then held until promptTimeout). The pass entry owns the active + // surface for the run's WHOLE span, and sendPrompt refuses chat turns + // under it — no chat stream can race this branch. + if activeEntry?.sessionId == Self.passTranscriptKey { + passCancelRequested = true + if let passSid = passWireId { + passClient?.notify("session/cancel", params: .object(["sessionId": .string(passSid)])) + } + return + } + guard let sid = activeEntry?.sessionId else { return } client?.notify("session/cancel", params: .object(["sessionId": .string(sid)])) } + /// #137 (S4): the model-change restart posture — Settings fires this + /// when the Chat model changes (the next slice wires the UI). Re-spawns + /// the resident chat engine in place when idle; while a turn streams + /// (either engine), the restart defers to turn end so a reply is never + /// cut mid-stream. .idle/.starting are ignored — a future spawn reads + /// fresh config anyway. + func requestRestart() { + switch phase { + case .ready, .crashed: + break + case .idle, .starting: + return + } + if isStreaming { + pendingRestart = true + } else { + Task { await respawn() } + } + } + + /// The restart body behind crash-restart and requestRestart (#137): + /// teardown, fresh spawn, then resume the PRE-restart active session + /// when it is rostered — the writer stays where they were, not jumped + /// to the newest entry (strictly better UX; the single-session crash + /// tests keep passing because active == newest there). + private func respawn() async { + client?.close() + client = nil + clientRef = nil + for sid in transcripts.keys { + transcripts[sid]?.streamingText = "" + transcripts[sid]?.streamingThought = "" + } + phase = .starting + await startEngine() + guard case .starting = phase else { return } // startEngine crashed instead + if let active = activeEntry, roster.contains(active) { + phase = .ready + _ = await resumeSession(active) + } else { + await ensureDefaultSession() + } + } + + /// A deferred restart fires at turn end — from BOTH turn-end defers + /// (chat sendPrompt and the pass run), whichever engine streamed (#137). + private func firePendingRestartIfRequested() { + guard pendingRestart else { return } + pendingRestart = false + Task { await respawn() } + } + /// Base version of a version string — the part before `+` build metadata /// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`. nonisolated static func baseVersion(of version: String) -> String { @@ -724,14 +1029,19 @@ extension MentorSessionModel { /// Route by the session id FROM THE PARAMS (#28) — a replay for a /// background session lands in ITS transcript, never the active one's. + /// #137: the pass engine's wire sid maps onto the transient pass key — + /// everything downstream addresses transcripts by that key (passWireId + /// is Optional; nil never equals a real sid). private func handleNotification(method: String, params: JSONValue?) { guard method == "session/update", let params, let sid = params.objectValue?["sessionId"]?.stringValue, - transcripts[sid] != nil, - let update = params.objectValue?["update"]?.objectValue else { return } + let update = params.objectValue?["update"]?.objectValue + else { return } + let key = sid == passWireId ? Self.passTranscriptKey : sid + guard transcripts[key] != nil else { return } let kind = update["sessionUpdate"]?.stringValue ?? "unknown" - let replaying = sid == replayingSessionId + let replaying = key == replayingSessionId switch kind { case "agent_message_chunk": let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" @@ -739,16 +1049,16 @@ extension MentorSessionModel { // ponytail: one row per replayed chunk — a chunked engine message // renders as several rows; wire order stays faithful. Coalesce // only if a real adapter chunks replayed turns. - appendRow(.text("Mentor: \(text)"), to: sid) + appendRow(.text("Mentor: \(text)"), to: key) } else { - transcripts[sid]?.streamingText += text + transcripts[key]?.streamingText += text } case "agent_thought_chunk": let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" if replaying { - appendRow(.thought(text), to: sid) + appendRow(.thought(text), to: key) } else { - transcripts[sid]?.streamingThought += text + transcripts[key]?.streamingThought += text } case "user_message_chunk": // Live: the engine echoes the user message; the label row already @@ -756,15 +1066,15 @@ extension MentorSessionModel { // owns the turn, so it renders (#28: user turns included). if replaying { let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" - appendRow(.text("You: \(text)"), to: sid) + appendRow(.text("You: \(text)"), to: key) } case "tool_call": - appendToolCall(update, to: sid) + appendToolCall(update, to: key) default: // Every other update type: collapsible raw-JSON row (map decision). let object = params.objectValue?.mapValues { $0.any } ?? [:] let json = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data() - appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid) + appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: key) } } diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 1bbf73a..eec2b82 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -194,7 +194,19 @@ final class PostsModel { }.value guard !Task.isCancelled else { return } posts = scanned - if let id = selectedPostID, !posts.contains(where: { $0.id == id }) { + if let id = selectedPostID, !posts.contains(where: { $0.id == id }), + // Stale-scan guard (#137 suite find): the snapshot can PREDATE the + // current selection — bind's initial rescan (detached scan over the + // empty tree) can land its continuation after a select its scan never + // saw, "vanishing" a piece that exists. Disk is the truth for + // vanished; a stale snapshot must not kill a live session (teardown + // cancels the debounce — unflushed edits would die with it). + // #137 audit (finish): a scan that outlived a Home repoint speaks + // for the OLD tree — never let it kill a session selected under + // the NEW home (the id is missing from the old snapshot by + // construction); the next rescan under the new home owns it. + watchedHome == home, PostStore.folder(of: id, home: home) == nil + { selectedPostID = nil // the post vanished (deleted in Finder or here) if let open = session, open.postID == id { open.teardown(flushFirst: false) // post is gone; cancel the debounce @@ -818,6 +830,13 @@ extension PostsModel { lastError = "The mentor engine isn't ready — wait for it or restart it." 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). + 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. @@ -843,33 +862,16 @@ extension PostsModel { // Draft, post type) is read from disk. A failed capture must never // fail the pass (decay-clock posture), so the Bool is ignored. PostStore.captureFirstDraftStats(id: id, body: session.text, home: home) - // #28 (S2.3): every pass auto-creates its own session — rostered - // 'Pass N · <title>' and activated, so the pass streams into ITS - // transcript. The existing ready-guard above stays the refusal pin. - let passSession = await mentor.beginPassSession(kind: kind, pieceTitle: title(of: id)) - guard passSession != nil else { - lastError = "The mentor engine refused a session for the pass." - return - } - // Finish-audit: the beginPassSession await above is these guards' - // first suspension — a second Run Pass landing inside it re-passed - // every guard (both flags still unset) and minted a second pass - // session. Re-check ownership here, before the flag goes live; the - // sub-ms window where BOTH awaits are still in flight self-contains - // via sendPrompt's isStreaming refusal (one orphan roster entry, - // never a double stream — ponytail ceiling). - guard runningPass == nil else { - lastError = "A pass is already running." - return - } - // runningPass goes live only AFTER the session awaits are done: from - // here to sendPrompt's isStreaming there is no suspension, so anything - // observing runningPass (the pass bar, the #124 Cancel pin) can rely - // on Stop being able to cancel the live turn. + // #137 (S4): runningPass goes live BEFORE the mentor awaits — + // flush/snapshot/capture above are synchronous, so nothing can slip + // between the guards and the flag: the #124 Cancel-visibility + // invariant now holds for the WHOLE run, pass-engine spawn included. runningPass = kind defer { runningPass = nil } let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch) - let outcome = await mentor.sendPrompt(stub, label: "\(kind.rawValue) · \(title(of: id))") + // #137: the pass runs on its OWN one-shot engine and streams into the + // transient pass transcript — never rostered (#129, ADR-0014). + let outcome = await mentor.runPass(kind: kind, stub: stub, pieceTitle: title(of: id)) guard case let .ended(stopReason) = outcome, stopReason != "refusal" else { return // cancelled / refused / failed — the transcript tells the story } diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 3467533..85cfc98 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -25,6 +25,9 @@ struct PostsPaneView: View { /// Width budget after the rail — drives column collapse (export media queries: /// library hides ≤1100, mentor hides ≤920). var availableWidth: CGFloat + /// #137 (S4): the mentor pane's missing-key Settings link (default nil + /// keeps previews compiling). + var onOpenSettings: (() -> Void)? @Environment(AppGateState.self) private var gate private var showsLibrary: Bool { @@ -147,8 +150,14 @@ struct PostsPaneView: View { } private var mentorColumn: some View { - MentorPaneView(model: mentor, binaryPath: mentorBinaryPath, posts: model, home: home) - .frame(width: DesignTokens.mentorWidth) + MentorPaneView( + model: mentor, + binaryPath: mentorBinaryPath, + posts: model, + home: home, + onOpenSettings: onOpenSettings, + ) + .frame(width: DesignTokens.mentorWidth) } } diff --git a/Museion/SettingsModel.swift b/Museion/SettingsModel.swift index 4f52b43..23c16e7 100644 --- a/Museion/SettingsModel.swift +++ b/Museion/SettingsModel.swift @@ -15,6 +15,11 @@ // Test Connection probe per provider. // +// swiftlint:disable file_length +// One Settings model, one write story: state, hydration, coalescing, and +// the #137 restart hook read as one unit; a page-per-file split follows if +// the file keeps growing. + import Foundation import Observation @@ -147,6 +152,12 @@ final class SettingsModel { private(set) var testStates: [ModelProvider: TestState] = [:] private let writer: any SettingsWriting + /// #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). + /// Never on failure (lastWriteError path), never for pass surfaces + /// (their engines are one-shot), never for key writes. + var onChatSurfaceWrite: (() -> Void)? /// Rapid edits per target coalesce: a newer write cancels the older /// task during its debounce window (the key field fires per keystroke — /// a partial prefix of a secret must never reach `.env`). Tests pass 0. @@ -366,6 +377,9 @@ final class SettingsModel { do { try await writer.writeSurface(surface, config: config, zaiEndpoint: zaiEndpoint) lastWriteError = nil + if surface == .chat { + onChatSurfaceWrite?() + } } catch { lastWriteError = error.localizedDescription } diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift index 0a392d0..2f1e07d 100644 --- a/Museion/SettingsPaneView.swift +++ b/Museion/SettingsPaneView.swift @@ -27,10 +27,14 @@ struct SettingsPaneView: View { /// profiles at pane open. @State private var model: SettingsModel - init(home: Binding<URL>, binaryPath: String?) { + init(home: Binding<URL>, binaryPath: String?, onChatSurfaceWrite: (() -> Void)? = nil) { _home = home self.binaryPath = binaryPath - _model = State(initialValue: SettingsModel(writer: HermesSettingsWriter(hermesBinary: binaryPath))) + let model = SettingsModel(writer: HermesSettingsWriter(hermesBinary: binaryPath)) + // #137: a committed Chat model write reaches the resident engine + // (WorkspaceView wires requestRestart). + model.onChatSurfaceWrite = onChatSurfaceWrite + _model = State(initialValue: model) } var body: some View { diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index 199c3a3..a68f0f1 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -194,6 +194,9 @@ struct WorkspaceView: View { mentorBinaryPath: gate.gateModel.currentBinaryPath, model: gate.posts, availableWidth: geo.size.width - DesignTokens.railWidth, + // #137: the pass bar's missing-key way out (ArchivePaneView + // closure precedent). + onOpenSettings: { selection = .settings }, ) case .sessions: // #28: the Sessions pane — roster + active transcript over the @@ -215,7 +218,14 @@ struct WorkspaceView: View { selection = .posts } case .settings: - SettingsPaneView(home: $gate.museionHome, binaryPath: gate.gateModel.currentBinaryPath) + // #137 (S4): a committed Chat model change restarts the resident + // chat engine in place (slice A's engine-side API; deferred to + // turn end while streaming). + SettingsPaneView( + home: $gate.museionHome, + binaryPath: gate.gateModel.currentBinaryPath, + onChatSurfaceWrite: { gate.mentor.requestRestart() }, + ) } } diff --git a/MuseionTests/ACPClientTests.swift b/MuseionTests/ACPClientTests.swift index b1d4941..aa74ce1 100644 --- a/MuseionTests/ACPClientTests.swift +++ b/MuseionTests/ACPClientTests.swift @@ -47,6 +47,8 @@ import Testing /// The mode travels in a file next to the fake (self-locating — race-free /// under parallel suites, same convention as ProfileProvisionerTests). /// The fix-card payload travels base64-encoded so shell quoting can't break. +/// Every spawn appends its argv line to `<name>-spawn-log` beside the fake +/// (#137) — the "which engine (profile) ran" observable. /// Internal (not private) so later test files can reuse the fake (#24). /// One contiguous zsh program — splitting the script string would break the /// wire-line inspectability the script's own comment pins. @@ -61,6 +63,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu #!/bin/zsh mode="full" [[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode") + print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran card=$(print -- '\(fixCardB64)' | base64 -d) research=$(print -- '\(researchB64)' | base64 -d) researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d) diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 90dd143..f01a6a5 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -18,7 +18,7 @@ Owned by the root AGENTS.md contract. - Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked. - `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing. -- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike. +- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike. - `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests. - `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. - `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`. @@ -26,8 +26,9 @@ Owned by the root AGENTS.md contract. - `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses. - `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve). - `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered. -- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#28:** one roster pin — a completed pass grows the roster with "Pass 1 · \<title\>" active (the auto-created session). **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). -- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass auto-creates its session (rostered "Pass 1 · \<title\>" newest-first, active, pass streams into ITS transcript), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key). +- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). +- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \<title\>"), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key). +- `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home). - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. - `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars. - `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit. @@ -39,7 +40,7 @@ Owned by the root AGENTS.md contract. - `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders. - ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` 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. -- `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. +- `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. ## Verification diff --git a/MuseionTests/EngineLifecycleTests.swift b/MuseionTests/EngineLifecycleTests.swift new file mode 100644 index 0000000..89a2615 --- /dev/null +++ b/MuseionTests/EngineLifecycleTests.swift @@ -0,0 +1,367 @@ +// +// EngineLifecycleTests.swift +// MuseionTests +// +// #137 (Profiles S4): per-surface engine lifecycle — passes run on their +// own ONE-SHOT engines (spawned per run on the pass profile, torn down at +// the verdict, never rostered per #129) and the Chat model-change restart +// posture (restart in place when idle, defer to turn end while streaming). +// Real client + fake ACP path; the fake's spawn log pins WHICH engine ran. +// + +import Foundation +@testable import Museion +import Testing + +/// makePassRig's shape plus the fake's directory — the spawn log beside +/// the fake is the "which engine (profile) spawned" observable (#137). +@MainActor +private struct EngineRig { + let model: PostsModel + let home: URL + let mentor: MentorSessionModel + let fakeDir: String +} + +@MainActor +private func makeEngineRig(mode: String = "full") throws -> EngineRig { + let (model, home) = try makeModelHome() + let dir = acpTempDir("engine-lifecycle") + let fake = makeFakeACP(at: dir, mode: mode) + return EngineRig(model: model, home: home, mentor: MentorSessionModel(binaryPath: fake), fakeDir: dir) +} + +/// Bounded poll until a child is reaped (kill(pid, 0) fails) — the house +/// 250×20 ms pattern, 100 rounds for a close() that reaps synchronously. +@MainActor +private func pollReaped(_ pid: pid_t) async throws -> Bool { + for _ in 0 ..< 100 where kill(pid, 0) == 0 { + try await Task.sleep(nanoseconds: 20_000_000) + } + return kill(pid, 0) != 0 +} + +// Scenario: A pass run lives on its own engine +// From user story #137 acceptance 1 +// Given a saved piece is open and the chat engine is resident +// When the writer runs Pass 1 +// Then Museion spawns `hermes acp -p museion-pass1`, streams the verdict +// into the pane's transcript, tears that engine down at the verdict +// (nothing pass-shaped stays resident), rosters nothing, and the chat +// engine keeps running untouched. + +@Test @MainActor func `a pass run lives on its own engine and rosters nothing`() async throws { + let rig = try makeEngineRig() + defer { rig.mentor.shutdown() } // #124: at rig creation — the children die with the test + await rig.mentor.openSession() + let chatPid = try #require(rig.mentor.childProcessIdentifier) + let rosterBefore = rig.mentor.roster.count + let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home) + rig.model.select(post.id, home: rig.home) + for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + + // In a Task — the pass child's pid is only observable while it runs. + let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) } + var passPid: pid_t? + var polls = 0 + while passPid == nil, polls < 250 { + passPid = rig.mentor.passEngineChildPid + polls += 1 + if passPid == nil { + try await Task.sleep(nanoseconds: 20_000_000) + } + } + _ = await run.value + + // The run completed as today: snapshot landed, Pass-1 Done stamped. + let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)") + let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8) + #expect(snapshot.contains("Verdict me.")) + let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8) + #expect(onDisk.contains("pass_state: Pass-1 Done")) + // The pass engine spawned under its own profile; the chat engine under museion. + let lines = try String( + contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"), + encoding: .utf8, + ).split(separator: "\n").map(String.init) + #expect(lines.contains("acp -p museion-pass1")) + #expect(lines.contains("acp -p museion")) + // Nothing pass-shaped stays resident… + #expect(rig.mentor.roster.count == rosterBefore) + #expect(!rig.mentor.isPassEngineRunning) + if let passPid { + #expect(try await pollReaped(passPid)) + } else { + Issue.record("pass engine pid never observed while the run was in flight") + } + // …and the chat engine is untouched. + #expect(kill(chatPid, 0) == 0) + #expect(rig.mentor.phase.isReady) + // The label row and the streamed critique rendered on the active surface. + #expect(textRows(of: rig.mentor).contains("Pass 1 · \(post.title)")) + #expect(!textRows(of: rig.mentor).contains { $0.contains("Critique the piece") }) + var streamed = false + for _ in 0 ..< 250 { + streamed = textRows(of: rig.mentor).contains { $0.contains("Hello mentor.") } + if streamed { + break + } + try await Task.sleep(nanoseconds: 20_000_000) + } + #expect(streamed) +} + +/// A1 cancel: the pass bar's Cancel reaches the PASS engine — the held turn +/// ends cancelled, the pass child is reaped, the roster never grew, and the +/// pre-pass snapshot still landed (pre-pass is unconditional). +@Test @MainActor func `cancelling a live pass cancels the turn and reaps the pass engine`() async throws { + let rig = try makeEngineRig(mode: "hangOnPrompt") + defer { rig.mentor.shutdown() } + await rig.mentor.openSession() + let rosterBefore = rig.mentor.roster.count + let post = try PostStore.writeNew(body: "# Held Pass\n\nCancel me.", home: rig.home) + rig.model.select(post.id, home: rig.home) + + let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) } + var passPid: pid_t? + var polls = 0 + while passPid == nil, polls < 250 { + passPid = rig.mentor.passEngineChildPid + polls += 1 + if passPid == nil { + try await Task.sleep(nanoseconds: 20_000_000) + } + } + let heldPid = try #require(passPid, "pass engine never spawned") + #expect(rig.mentor.isPassEngineRunning) + + rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail + for _ in 0 ..< 250 where rig.model.runningPass != nil { + try await Task.sleep(nanoseconds: 20_000_000) + } + #expect(rig.model.runningPass == nil) + _ = await run.value + + let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)") + let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8) + #expect(snapshot.contains("Cancel me.")) + let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8) + #expect(onDisk.contains("pass_state: First Draft")) + #expect(!rig.mentor.isPassEngineRunning) + #expect(try await pollReaped(heldPid)) + #expect(rig.mentor.roster.count == rosterBefore) +} + +// Scenario: A Chat model change restarts the resident engine, but never mid-reply +// From user story #137 acceptance 2 +// Given the resident chat engine is mid-turn (streaming) +// When a chat model change is requested (Settings fires it; this slice +// exposes the engine-side API) +// Then the restart waits for the turn to end, then re-spawns the engine in +// place and replays the active rostered session — while idle, it restarts +// immediately. + +/// A2 idle: requestRestart re-spawns in place — old child reaped, new child +/// alive, phase back to .ready, and the PRE-restart active rostered session +/// is resumed with its transcript replayed from the engine. +@Test @MainActor func `idle requestRestart respawns in place and replays the active rostered session`() async throws { + let rig = try makeEngineRig(mode: "loadReplay") + defer { rig.mentor.shutdown() } + await rig.mentor.openSession() + let active = try #require(rig.mentor.activeEntry) + _ = await rig.mentor.sendPrompt("hello mentor") // history in the active session + let oldPid = try #require(rig.mentor.childProcessIdentifier) + + rig.mentor.requestRestart() + + var newPid: pid_t? + var polls = 0 + while newPid == nil, polls < 250 { + if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != oldPid { + newPid = pid + } else { + polls += 1 + try await Task.sleep(nanoseconds: 20_000_000) + } + } + let respawned = try #require(newPid, "chat engine never re-spawned") + #expect(try await pollReaped(oldPid)) + #expect(kill(respawned, 0) == 0) + // The writer stays where they were: same rostered session, replayed. + #expect(rig.mentor.activeEntry == active) + var replayed = false + for _ in 0 ..< 250 { + replayed = !rig.mentor.transcriptRows(of: active).isEmpty + if replayed { + break + } + try await Task.sleep(nanoseconds: 20_000_000) + } + #expect(replayed) +} + +/// A2 deferred ordering pin: requested mid-turn, the restart holds (same +/// child, still streaming) until the turn ends — the pid swap happens only +/// AFTER the turn. +@Test @MainActor func `requestRestart mid-turn defers the respawn until the turn ends`() async throws { + let rig = try makeEngineRig(mode: "hangOnPrompt") + defer { rig.mentor.shutdown() } + await rig.mentor.openSession() + let chatPid = try #require(rig.mentor.childProcessIdentifier) + + let turn = Task { await rig.mentor.sendPrompt("hold this") } + for _ in 0 ..< 250 where !rig.mentor.isStreaming { + try await Task.sleep(nanoseconds: 20_000_000) + } + #expect(rig.mentor.isStreaming) + + rig.mentor.requestRestart() // Settings fires — mid-turn + try await Task.sleep(for: .milliseconds(300)) + // Still streaming, same child: the restart deferred, never mid-reply. + #expect(rig.mentor.isStreaming) + #expect(rig.mentor.childProcessIdentifier == chatPid) + #expect(kill(chatPid, 0) == 0) + + rig.mentor.stopStreaming() // ends the held turn — the restart fires now + _ = await turn.value + #expect(!rig.mentor.isStreaming) + + var newPid: pid_t? + var polls = 0 + while newPid == nil, polls < 250 { + if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != chatPid { + newPid = pid + } else { + polls += 1 + try await Task.sleep(nanoseconds: 20_000_000) + } + } + #expect(newPid != nil, "the deferred pid swap never happened after turn end") + #expect(try await pollReaped(chatPid)) +} + +// Scenario: Run Pass names the missing key instead of failing silently +// From user story #137 acceptance 3 +// Given Pass 1's provider has no key in the profiles' .env +// When the writer opens the mentor pane +// Then Run Pass is disabled with the reason named (provider) and a Settings +// link; once the key is provided via Settings, Run Pass re-enables (pane +// re-entry refreshes). + +/// 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), +/// and a surface we can't read reads .unknown (never blocks on our own +/// failure — the spawn's honest failure row owns that path). +@Test @MainActor func `pass readiness names the missing provider key and re-enables on rekey`() async { + let mentor = MentorSessionModel() + let writer = RecordingWriter() + writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5", effort: nil), nil) + writer.cannedKeys[.anthropic] = "sk-live" + writer.cannedReads[.pass2] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), nil) + mentor.passReadinessWriter = writer + await mentor.refreshPassReadiness() + #expect(mentor.readiness(for: .pass1) == .ready) + #expect(mentor.readiness(for: .pass2) == .missingKey(providerLabel: "z.ai")) + // The Settings path: the key lands, pane re-entry re-fires the + // refresh — Run Pass re-enables. + writer.cannedKeys[.zai] = "sk-z" + await mentor.refreshPassReadiness() + #expect(mentor.readiness(for: .pass2) == .ready) + // Unreadable surfaces read .unknown — a read failure of OURS never + // blocks the run. + mentor.passReadinessWriter = RecordingWriter() + await mentor.refreshPassReadiness() + #expect(mentor.readiness(for: .pass1) == .unknown) + #expect(mentor.readiness(for: .pass2) == .unknown) +} + +/// B1 guard pin: with readiness .missingKey the runPass guard names the +/// provider in lastError — and fires BEFORE the open-piece guard's +/// snapshot, so nothing lands on disk. +@Test @MainActor func `run pass names the missing provider key and writes nothing`() async throws { + let rig = try makeEngineRig() + defer { rig.mentor.shutdown() } + await rig.mentor.openSession() + let writer = RecordingWriter() + writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), nil) + rig.mentor.passReadinessWriter = writer + await rig.mentor.refreshPassReadiness() + let post = try PostStore.writeNew(body: "# No Key\n\nPass me.", home: rig.home) + rig.model.select(post.id, home: rig.home) + for _ in 0 ..< 250 where rig.model.session?.postID != post.id { + try await Task.sleep(nanoseconds: 20_000_000) + } + // The piece must be OPEN — otherwise the open-piece guard would pass + // this pin vacuously. + try #require(rig.model.session?.postID == post.id) + + await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) + + #expect(rig.model.lastError == "Pass 1 needs a z.ai API key — add it in Settings → Provider Keys.") + let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)") + #expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("passes/pass-1.md").path)) + #expect(rig.model.runningPass == nil) +} + +/// #137 audit (finish): a session/load that STARTED before a pass and +/// COMPLETES mid-pass must not steal the pass surface — the post-await +/// claimActive guard refuses, Cancel keeps routing to the pass engine. +/// loadReplayHold parks the load until `load-go` lands beside the fake +/// (SessionLifecycleTests' in-flight seam), which makes the interleaving +/// deterministic instead of lucky. +@Test @MainActor func `a resume completing mid-pass does not steal the pass surface`() async throws { + let rig = try makeEngineRig(mode: "loadReplayHold") + defer { rig.mentor.shutdown() } + await rig.mentor.openSession() // default Mentor session (sess-1) + _ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active + let target = try #require(rig.mentor.roster.last) // sess-1, NOT active + let post = try PostStore.writeNew(body: "# Held Load\n\nResume races a pass.", home: rig.home) + rig.model.select(post.id, home: rig.home) + for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + + // Park a resume of sess-1. The fake announces the park with a + // `hold-load` stderr line (the chat engine's stderrTail surfaces it). + let resume = Task { await rig.mentor.resumeSession(target) } + for _ in 0 ..< 250 where !rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + try #require(rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") })) + + // Deterministic window: flip the mode file to hangOnPrompt BEFORE the + // pass engine spawns (each child reads the mode at startup) — the pass + // prompt then HOLDS, so isStreaming is guaranteed when the parked load + // completes, and the #124 Cancel rail frees it afterwards. + try "hangOnPrompt".write( + toFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-mode"), + atomically: true, + encoding: .utf8, + ) + let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) } + for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning { + try await Task.sleep(nanoseconds: 20_000_000) + } + try #require(rig.mentor.isPassEngineRunning) + + // Free the parked load — its completion lands while the pass holds + // (nothing blocks the load; the held pass makes the direct await safe). + try Data().write(to: URL(fileURLWithPath: (rig.fakeDir as NSString).appendingPathComponent("load-go"))) + // The resume refused post-await while the pass still held the surface… + #expect(await resume.value == false) + #expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey) + + // …and Cancel still routes to the pass engine (#124 rail) — the held + // turn ends cancelled, the pass never advances. + rig.model.cancelPass(mentor: rig.mentor) + for _ in 0 ..< 250 where rig.model.runningPass != nil { + try await Task.sleep(nanoseconds: 20_000_000) + } + _ = await run.value + #expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey) + #expect(textRows(of: rig.mentor).contains("Resume refused — the mentor is mid-turn.")) + #expect(rig.mentor.roster.contains(target)) +} diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index 5955f68..bdf46c3 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -24,8 +24,10 @@ func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessio return (model, home, mentor) } +/// Internal (shared-helper convention): EngineLifecycleTests reads the same +/// transcript projection over its rigs. @MainActor -private func textRows(of model: MentorSessionModel) -> [String] { +func textRows(of model: MentorSessionModel) -> [String] { model.rows.compactMap { if case let .text(text) = $0.content { text @@ -239,27 +241,6 @@ private func textRows(of model: MentorSessionModel) -> [String] { #expect(onDisk.contains("pass_state: Pass-2 Done")) } -/// #28 (S2.3): every pass auto-creates its session — the roster grows by -/// 'Pass N · <title>' and that entry is the active transcript's owner. -@Test @MainActor func `running a pass grows the roster with its pass session active`() async throws { - let (model, home, mentor) = try makePassRig() - defer { mentor.shutdown() } - await mentor.openSession() - let before = mentor.roster.count - let post = try PostStore.writeNew(body: "# Rostered Pass\n\nOne session per pass.", home: home) - model.select(post.id, home: home) - for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { - try await Task.sleep(nanoseconds: 20_000_000) - } - - await model.runPass(.pass1, home: home, mentor: mentor) - - #expect(mentor.roster.count == before + 1) - #expect(mentor.roster.first?.name == "Pass 1 · \(post.title)") - #expect(mentor.activeEntry == mentor.roster.first) - #expect(model.lastError == nil) -} - // MARK: First-draft stats capture (#31, S5.1) @Test @MainActor func `pass on a writer first draft piece captures stats and still completes`() async throws { diff --git a/MuseionTests/SessionLifecycleTests.swift b/MuseionTests/SessionLifecycleTests.swift index c452a92..450207c 100644 --- a/MuseionTests/SessionLifecycleTests.swift +++ b/MuseionTests/SessionLifecycleTests.swift @@ -16,14 +16,15 @@ import Testing @Suite("SessionLifecycleTests") struct SessionLifecycleTests { - /// #28 AC2: the pass's session is rostered newest-first, active, and the - /// pass prompt streams into ITS transcript — the default freeform - /// session stays untouched while Pass State advances exactly as before. - @Test @MainActor func `pass auto-creates its rostered session`() async throws { + /// #137 (per #129): a pass streams into a TRANSIENT, unrostered + /// transcript — visible through the active surface while it runs, the + /// entry named by convention, never rostered, never persisted. + @Test @MainActor func `a pass streams into a transient unrostered transcript`() async throws { let (model, home, mentor) = try makePassRig() defer { mentor.shutdown() } await mentor.openSession() let defaultSession = try #require(mentor.activeEntry) + let rosterBefore = mentor.roster.count let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home) model.select(post.id, home: home) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { @@ -32,25 +33,24 @@ struct SessionLifecycleTests { await model.runPass(.pass1, home: home, mentor: mentor) - // Rostered newest-first, named by convention, and active. - #expect(mentor.roster.first?.name == "Pass 1 · \(post.title)") - #expect(mentor.activeEntry == mentor.roster.first) - // The prompt streamed into ITS transcript; the wire stub never lands. + // The roster never grew — the pass entry is transient. + #expect(mentor.roster.count == rosterBefore) + // The transient pass entry owns the active surface while it lives. let entry = try #require(mentor.activeEntry) - #expect(texts(in: mentor.transcriptRows(of: entry)).contains("Pass 1 · \(post.title)")) - // The streamed verdict lands via a client notification Task that can - // settle just after runPass returns under load — bounded settle. + #expect(entry.name == "Pass 1 · \(post.title)") + #expect(entry.sessionId == MentorSessionModel.passTranscriptKey) + // The prompt streamed through the ACTIVE surface; the wire stub never lands. + #expect(texts(in: mentor.rows).contains("Pass 1 · \(post.title)")) + #expect(!texts(in: mentor.rows).contains { $0.contains("Critique the piece") }) var streamed = false for _ in 0 ..< 250 { - streamed = texts(in: mentor.transcriptRows(of: entry)).contains(where: { $0.contains("Hello mentor.") }) + streamed = texts(in: mentor.rows).contains { $0.contains("Hello mentor.") } if streamed { break } try await Task.sleep(nanoseconds: 20_000_000) } - let rows = mentor.transcriptRows(of: entry) #expect(streamed) - #expect(!texts(in: rows).contains { $0.contains("Critique the piece") }) // The pre-existing freeform session's transcript is untouched. #expect(mentor.transcriptRows(of: defaultSession).isEmpty) // Pass State advanced on the completed turn, exactly as before. @@ -455,11 +455,15 @@ struct SessionLifecycleTests { return false }) } +} - // Scenario: draft candidate — from #30 (S2.7). Given a session - // transcript, when the sheet prefills, then the last mentor text row is - // the draft candidate; thought/card/research/raw rows never prefill. - @Test @MainActor func `draft candidate is the last mentor text row`() { +// Scenario: draft candidate — from #30 (S2.7). Given a session +// transcript, when the sheet prefills, then the last mentor text row is +// the draft candidate; thought/card/research/raw rows never prefill. +// File-scope extension — type_body_length posture; same suite, same file. +@MainActor +extension SessionLifecycleTests { + @Test func `draft candidate is the last mentor text row`() { let rows: [SessionRow] = [ SessionRow(content: .text("You: help me draft this")), SessionRow(content: .thought("thinking hard about angles")), @@ -477,7 +481,7 @@ struct SessionLifecycleTests { #expect(MentorSessionModel.draftCandidateText(in: rows) == "second and latest reply") } - @Test @MainActor func `no mentor text yields no draft candidate`() { + @Test func `no mentor text yields no draft candidate`() { // Empty transcript, user-only, and non-text lanes never prefill. #expect(MentorSessionModel.draftCandidateText(in: []) == nil) #expect(MentorSessionModel.draftCandidateText(in: [ diff --git a/MuseionTests/SettingsModelWritePathTests.swift b/MuseionTests/SettingsModelWritePathTests.swift index c6637c5..089b6c3 100644 --- a/MuseionTests/SettingsModelWritePathTests.swift +++ b/MuseionTests/SettingsModelWritePathTests.swift @@ -148,4 +148,42 @@ struct SettingsModelWritePathTests { #expect(model.probeModel(for: .anthropic) == ProfileSurface.defaultModelID) #expect(model.probeModel(for: .zai) == ModelProvider.zai.switchDefaultModel) } + + // Scenario: Saving a Chat model change reaches the resident engine + // From user story #137 acceptance 2 + // Given the Settings pane is open + // When a Chat surface model write succeeds (provider/model/effort/reset) + // Then onChatSurfaceWrite fires after the write lands — pass-surface + // writes and key writes never fire it, and failed writes don't either. + + @Test @MainActor func `a successful chat surface write fires onChatSurfaceWrite`() async { + let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0) + var fired = 0 + model.onChatSurfaceWrite = { fired += 1 } + model.setModel("claude-sonnet-5", for: .chat) + await model.awaitPendingWrites() + #expect(fired == 1) + } + + @Test @MainActor func `pass surface writes and key writes never fire onChatSurfaceWrite`() async { + let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0) + var fired = 0 + model.onChatSurfaceWrite = { fired += 1 } + model.setEffort(.max, for: .pass1) + model.setAPIKey("sk-a", for: .anthropic) + await model.awaitPendingWrites() + #expect(fired == 0) + } + + @Test @MainActor func `a failed chat write never fires onChatSurfaceWrite`() async { + let writer = RecordingWriter() + writer.failSurfaceWrites = true + let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0) + var fired = 0 + model.onChatSurfaceWrite = { fired += 1 } + model.setModel("claude-sonnet-5", for: .chat) + await model.awaitPendingWrites() + #expect(fired == 0) + #expect(model.lastWriteError != nil) + } } diff --git a/docs/devlog/20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md b/docs/devlog/20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md new file mode 100644 index 0000000..654ad9e --- /dev/null +++ b/docs/devlog/20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md @@ -0,0 +1,74 @@ +# #137 Profiles S4 — Per-surface engine lifecycle + model-switch UX + +> **Date:** 2026-10-28 +> **Type:** issue +> **Reference:** git.babylondreams.de/AlexKucera/Museion#137 (part of #125, closed map) + +## Goal + +Land #137: pass engines become on-demand (`hermes acp -p museion-passN` spawned per pass run, torn down at the verdict — a model switch costs nothing), the Chat engine stays resident and auto-restarts in place on a Chat model change (deferred while a turn streams, #129), and Run Pass gains an honest missing-key disabled state naming the provider with a Settings link (#132). All four acceptance criteria against the fake ACP server, including deferred-restart ordering. + +## What Was Done + +- `ACPEngineClient` takes `profile:` (default `museion`) — argv `["acp", "-p", profile]`; every existing call site compiles unchanged. +- `MentorSessionModel` grows the pass-engine lifecycle: `runPass(kind:stub:pieceTitle:)` spawns the pass profile's own engine, streams into a TRANSIENT unrostered transcript (`passTranscriptKey = "pass"`, per #129 "passes transient"), tears down at the verdict (nothing pass-shaped stays resident; `passClientRef` mirror closes the child from deinit). `beginPassSession` deleted — passes never mint sessions. +- The turn pipeline extracted to one `turnCore` (label row, session/prompt, stopReason mapping, streaming-buffer flush) shared by `sendPrompt` and the pass run; `stopStreaming` routes the cancel on the transient entry so the pass engine owns its whole span. +- Chat restart posture: `requestRestart()` re-spawns in place when idle (resuming the PRE-restart active rostered session), defers via `pendingRestart` to turn end while streaming — fired from both turn-end defers, whichever engine streamed. +- Missing-key posture: `PassReadiness` (ready / missingKey(providerLabel) / unknown) + `refreshPassReadiness()` (task-group `readSurface` over both pass profiles, then per-distinct-provider `readProviderKey`; `.unknown` never blocks), injected via `passReadinessWriter`. `PostsModel.runPass` refuses with the provider named BEFORE anything touches disk; PassBar renders "Missing <provider> key —" + an Open Settings link threaded WorkspaceView → PostsPaneView → MentorPaneView (`selection = .settings`, the ArchivePaneView closure precedent); pane re-entry re-fires the refresh = the re-enable path. +- Settings wiring: `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write only (never pass surfaces, keys, or failures); WorkspaceView wires it to `gate.mentor.requestRestart()`. +- Finish-audit fanout (3 reviewers) applied: the Medium (post-await `activeEntry` steal) fixed with one `claimActive` gate across createSession/resumeSession/forkActiveSession + an `ensureDefaultSession` early-out (`phase = .ready`, surface untouched) for restart-mid-pass; rescan's vanish-kill gated on `watchedHome == home`; the app target's only force-unwrap replaced with a guard; −59 lines of test duplication cut; stale `beginPassSession` docs contracts cleaned. +- Tests: `EngineLifecycleTests.swift` (new) — own-engine end-to-end (spawn log names `acp -p museion-pass1`, roster unchanged, pass child reaped, chat child alive), held-pass cancel, idle restart-in-place, deferred-restart ordering (pid unchanged while held, swaps only after turn end), readiness pins, missing-key guard pin, and the audit's resume-steal pin. Two stale #28 roster pins flipped to the transient posture; +3 SettingsModel hook pins. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Passes transient, never rostered | #129's settled framing: one Sessions pane surface over the chat engine, passes one-shot; a rostered pass session would be unresumable by the chat engine ("engine does not know" refusals) | +| `runningPass` set BEFORE the mentor awaits | flush/snapshot/capture are synchronous — no suspension between guards and flag; the #124 Cancel-visibility invariant holds for the whole run incl. the engine spawn | +| Cancel routing keyed on the transient active entry, not `passWireId` | the wire id is nil until session/new — a Cancel in the spawn window fell through to the chat engine and was LOST (found by the suite, fixed once at the shared sink) | +| One `claimActive` gate for all post-await activations | session/new/load/fork completions can land mid-pass (a load can span minutes); each stealing `activeEntry` re-opens the lost-cancel hole — one guard at the shared seam beats three local patches | +| `restart in place` resumes the pre-restart active entry | strictly better than blindly newest; single-session crash tests unaffected (active == newest there) | +| `.unknown` readiness never blocks | our own read failure must not disable Run Pass — the spawn's honest failure row owns that path | +| Deferred: double-restart coalescing | two chat writes <1 s apart cause a transient crash-card flash that self-heals; coalescing risks absorbing a config write the in-flight respawn already read — a worse trade than the cosmetic flash | +| Implementation split into two delegated slices (model layer, then UX/wiring) | shared Xcode build serializes verification anyway; B built on A's landed API | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| New cancel pin "hung" 60 min; #124 pin failed at its 5 s poll | `stopStreaming` branched on `passWireId != nil` — nil until session/new, so spawn-window cancels fell through to the chat engine and vanished; the pass held to the 1800 s `promptTimeout` (duration ≈ 2× the timeout constant names the unanswered await) | branch on `activeEntry == passTranscriptKey` (true for the run's whole span) + `passCancelRequested` flag caught after session/new | +| Two #31 stats pins failed with "Open a saved post to run a pass" under full-suite load | PRE-EXISTING: `rescan`'s "post vanished" kill trusted a scan snapshot that can PREDATE the selection — bind's initial rescan (detached scan over the empty tree) landed after a later `select` and killed the live session (teardown cancels the debounce — unflushed edits die with it) | disk-truth re-check (`PostStore.folder(of:) == nil`) before the kill; audit added `watchedHome == home` for the repoint variant | +| Subagent A interrupted mid-verification, its runs burned the budget | full-suite re-runs (30–45 min each) instead of targeted filters | parent verified via diff review + the working backtick free-function filter form `-only-testing:'MuseionTests/`<name>`()'` (solo — stacked flags match a random subset) | +| First steal-pin draft raced (load completion vs pass window) | pass duration and load completion are same-magnitude timings | deterministic: `loadReplayHold` parks the load; flip the fake's MODE FILE to `hangOnPrompt` before the pass engine spawns (each child reads it at startup) — the pass holds indefinitely, `load-go` completes the load mid-hold, the #124 rail frees it | +| Flip-verify run appeared to fail in 0.000 s after ~20 min "running" | the flip made the steal real: the resume stole the surface, Cancel misrouted to the chat engine, the held pass waited out the timeout; the recorded duration is a reporting artifact | xcresult carried the true failures (`resume.value == true`, `activeEntry → "sess-1"`) — flip discriminated on exactly the reviewed observables | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/ACPEngineClient.swift` | `profile:` parameter on init (default museion) | +| `Museion/MentorSessionModel.swift` | pass-engine lifecycle, turnCore, restart posture, PassReadiness, claimActive gate | +| `Museion/PostsModel.swift` | runPass routes to the pass engine + missing-key guard; rescan vanish-kill disk/home guards | +| `Museion/MentorPaneView.swift` | missing-key Run Pass state + Open Settings link; session chip hidden on the pass transcript | +| `Museion/PostsPaneView.swift` / `Museion/WorkspaceView.swift` | `onOpenSettings` threading + `onChatSurfaceWrite → requestRestart` wiring | +| `Museion/SettingsModel.swift` / `SettingsPaneView.swift` | `onChatSurfaceWrite` hook (chat-success only) + init threading | +| `MuseionTests/EngineLifecycleTests.swift` | NEW — 7 lifecycle/readiness/steal pins (scenario headers) | +| `MuseionTests/PassRunTests.swift` | runPass rework pins; #28 roster pin flipped then deduplicated; `textRows` internal | +| `MuseionTests/SessionLifecycleTests.swift` | pass pin flipped to the transient unrostered transcript | +| `MuseionTests/SettingsModelWritePathTests.swift` | +3 hook pins | +| `MuseionTests/ACPClientTests.swift` | fake appends every spawn's argv to `<name>-spawn-log` | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX contracts for both slices + audit fixes (root = gitnexus stats bump) | + +## Open Items & Next Steps + +- [ ] Dogfood: pass on a real piece per profile, Chat model change mid-reply, key-less Run Pass → Settings → back +- [ ] Deferred (noted in DOX): double-restart crash-card flash (revisit if observed in dogfooding); readiness CLI spawn churn per pane entry (`.task`-cancellation thread is the upgrade path) +- [ ] No deterministic pin for the rescan stale-scan/home guards (interleaving needs an injection seam) — probabilistically covered by the stats/e2e pins + +## Verification + +Full suite `xcodebuild … -only-testing:MuseionTests test`: **477 executed, 477 passed, 0 failures** (xcresult counts, post-audit tree; count arithmetic: 472 baseline + 6 new − 1 deduplicated). Flip-verified: `claimActive` guard removed → the steal pin fails on `resume.value == true` + `activeEntry → "sess-1"` (and the misrouted-cancel hang); restored → passes in 0.78 s. `swiftformat` clean; `swiftlint` at/below HEAD baseline on every touched file. `gitnexus detect-changes` shows the intended symbol set (hub fan-out labels are centrality, not scope); index re-analyzed. Final pre-commit gate re-run green — see commit. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 602b7f7..538785f 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 <!-- write-log: full-index --> | Date | Type | File | Summary | |------|------|------|---------| +| 2026-10-28 | issue | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) | Pass engines on-demand per profile, transient transcripts, chat restart deferred mid-turn, missing-key Run Pass — 2 race fixes | | 2026-10-27 | issue | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | Profiles S3: settings write path (config set + .env), Test Connection probe, three dogfood rounds, three-reviewer audit | | 2026-10-27 | issue | [20261027-issue135-profiles-s2-settings-page-ui_log.md](20261027-issue135-profiles-s2-settings-page-ui_log.md) | #135 Profiles S2: variant C Settings sidebar+detail over the SettingsWriting seam; NSComboBox stale-stringValue dogfood fix; 432 tests | | 2026-10-27 | issue | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | #134 Profiles S1: ×3 surface registry + provisioner, master-symlink skills with byte-match migration, three-profile backup; 412 tests |