# #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 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/``()'` (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 `-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*