Files
museion/docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md
T
AlexKucera 627ecf515e
CI / ci (push) Canceled after 0s
refactor(session): extract the engine host
Engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown,
and the per-surface residency rules (resident chat engine; one-shot
pass engines spawned per run, torn down at the verdict, ADR-0014) —
moves out of MentorSessionModel into EngineHost behind the
EngineTransport seam. The model keeps session + turn coordination and
stays the only observable the panes see; ACPEngineClient becomes the
seam's production adapter, and a scripted in-process engine
(ScriptedEngine) becomes the second adapter — engine-behaviour tests
(streaming, crash, cancel, restart, per-surface spawn) now run without
child processes, retiring the zsh fake-server rigs from logic tests
(#30 flake family). Exactly one real-process wire smoke per LLM
surface survives (chat two-act + parameterized pass1/pass2): the
held-turn cancel contract, hung-child SIGTERM teardown, handshake,
streamed turn, crash, restart.

One-shot teardown is structural (withOneShot closes at body end, every
exit path); the one-shot slot is claimed before the first suspension so
the at-most-one invariant holds across the spawn/handshake awaits.

Suite: 652 executed / 652 passed / 0 failed (653 argument cases),
counted from the xcresult; swiftformat idempotent, swiftlint clean on
touched files.

Closes #178
2026-11-09 18:26:16 +01:00

11 KiB
Raw Blame History

Extract the engine host — per-surface lifecycle policy behind a transport seam

Date: 2026-11-09 Type: issue Reference: Closes #178 (git.babylondreams.de/AlexKucera/Museion, from the 2026-11-09 architecture review, mentor line step 2 of 3)

Goal

Move the engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown, and the per-surface residency rules (resident chat engine; on-demand one-shot pass engines per ADR-0014) — out of MentorSessionModel into an engine-host module over the ACP client through a narrow transport seam. A scripted in-process transport becomes the seam's second adapter so engine-behaviour tests (streaming, crash, cancel, restart, per-surface spawn) run without child processes; exactly one real-process end-to-end smoke per LLM Surface survives as the wire-contract guard, retiring the zsh fake-server rigs from logic tests (the documented real-process flake family, #30).

What Was Done

  • Museion/EngineHost.swift (new) — the EngineTransport seam (onMessage/onCrash/onStderrLine hooks + start() throws + request(_:params:timeout:) + notify + close()) and EngineHost (@MainActor), owner of spawn (makeTransport factory, profile → transport, reads binaryPath at spawn time), the initialize handshake (advisory BASE-version drift note, moved verbatim from the model), teardown, and per-surface residency: one resident chat engine (startChat() → ChatStart / killChat()) plus at most one one-shot engine (withOneShot(profile:_:) — spawn per run, teardown at the body's end = the verdict). Hook wiring rides DispatchQueue.main.async (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets onMessage only (KNOWN EDGE #137: a pass crash must not flip the pane). nonisolated(unsafe) mirrors close children in deinit (the old model's clientRef pattern relocated).
  • ACPEngineClient — conforms to EngineTransport; start(onMessage:) became an onMessage property + start() (always set before start; process.run() provides the happens-before). Concrete request/notify default arguments cut — the seam's protocol extension owns the default shape (finish-audit: defaults were dead with the host as sole caller).
  • MentorSessionModel — all process lifecycle deleted (−211 lines): client/passClient/clientRef/passClientRef, startEngine, handshake, teardownPassEngine, shutdownClientDirectly, the deinit body. Session + turn coordination stays: phase machine fed by host.startChat() outcomes (applyChatStart), runOneShot rides host.withOneShot with the body holding session/new + the spawn-window cancel + turnCore; respawn = killChat → clear buffers → startChat → resume PRE-restart active. The model stays the ONLY observable the panes see.
  • MuseionTests/ScriptedEngine.swift (new) — the scripted in-process adapter: mode strings mirroring the retired zsh fake (full/crashAfterHandshake/hangOnPrompt/cancelOnPrompt/refuseOnPrompt/noStopReason/strayResearchOnPrompt/loadReplay*/strictMcp), ScriptedPayloads (one home for the wire payloads — the zsh b64 helpers delegate to it), a lock-protected ScriptedBook captured STRONGLY by the factory, and the rig roots. Observables: spawned-profiles record (which engine ran), transport identity where pid pins used to live, isClosed for reaped, prompts for what the engine was asked, releaseHeldLoad() for the parked-load interleavings.
  • 8 suites migrated in-process — ACPClientTests (turn-outcome + view predicates; the zsh harness stays as the shared wire fixture), EngineLifecycleTests, PassRunTests, BlindReadTests, SessionLifecycleTests, SessionScopeTests, TranscriptRailTests, ResearchCandidateTests. All pins kept their meaning; pid/kill pins became transport-identity/isClosed pins; the load-go mode-file flip became the rig's mutable mode + releaseHeldLoad().
  • MuseionTests/EngineSmokeTests.swift (new) — the ONLY child-spawning suite: one real-process wire smoke per LLM surface. Chat (two acts over one fake: held-turn fire-and-forget cancel → .cancelled + shutdown SIGTERMs a parked child → reaped, then mode flip to loadReplay for handshake/stream/crash/restart/teardown on a fresh model) + one parameterized pass smoke over [PassKind.pass1, .pass2] (own engine under its profile, spawn-log pins, teardown reap, chat engine untouched).
  • DOX — Museion/AGENTS.md ACP-bridge section rewritten (EngineHost bullet added; model bullet re-scoped to "the only observable the panes see"); MuseionTests/AGENTS.md conventions + suite map updated (in-process seam rigs; EngineSmokeTests as the only child-spawning suite).

Decisions & Rationale

Decision Rationale
Seam = the client's own surface (hooks + request/notify/close), not a smaller one The model needed exactly that shape through turnCore; inventing a narrower protocol would duplicate the client's API. Two adapters, both exercised — the seam earns its existence
Host not @Observable; model copies engineVersion/versionNote from startChat()'s .up Keeps observation 100% on the model (acceptance: "no pane observes the host directly") without proxy-property tracking subtleties
One-shot teardown inside withOneShot (scoped-resource pattern) Guarantees "torn down at the verdict" structurally — teardown at body end on every exit path including throws — instead of trusting every future caller to remember
One-shot slot claimed BEFORE the spawn/handshake awaits (review fix) Old model set passClient before any suspension; claiming after the handshake left isOneShotRunning false and the at-most-one contract unenforced across the await. Defer registered with the claim so all four exits release
Rig factory holds the ScriptedBook STRONGLY (no [weak self]) The original rig dropped to nil mid-test when a 3-tuple shape didn't retain it — every later spawn silently fell back to "full" mode; poisoned holds. Rig lifetime must not matter
Chat smoke in two acts with a mid-test mode-file flip One smoke per surface is the ceiling; the flip (each fake child reads the mode at startup — the old interleaving-test convention) lets one fake serve both the cancel/hold contracts and the restart-resume contract
Deferred: LocalizedError on TransportError/HostError so failure rows render the message Pre-existing user-visible string behavior faithfully ported; changing row text exceeds #178's scope. Noted for #181's guard-dedupe rider

Gotchas & Fixes

Problem Root Cause Fix
Every scripted spawn answered as "full" mode mid-test; a parked 1800 s load poisoned cross-suite runs Rig factory's [weak self] went nil when the makePassRig 3-tuple dropped the rig object Lock-protected ScriptedBook captured strongly by host.makeTransport; no MainActor closure in the factory
crash after handshake fires onCrash exactly once failed with confirmation count 0 The scripted engine resumed the initialize continuation before firing onCrash; the awaiting task ended the confirmation body first Latch + fire onCrash BEFORE resuming the continuation (mirror of the wire-order rule)
Suite SIGTRAP: every test crashed at payload decode Backslash-escaped quotes inside raw string literals produced invalid JSON → preconditionFailure Fixed literals; green full run confirms
652 executed after parameterizing the pass smoke (expected 653) xcresulttool totalTestCount counts a Swift Testing parameterized @Test as ONE test; per-argument executions are nodeType: "Arguments" children Reconciled programmatically: 652 functions = 653 argument cases (.pass1/.pass2 children individually Passed). Count convention updated in MuseionTests verification practice
One-shot engine identity not observable mid-run in-process A full-mode scripted turn completes inside one 20 ms poll sleep (no child-process latency) The pin captures the pass engine from the spawn records post-run (profile, isClosed, host.oneShot == nil) — same facts, timing-free
Chat smoke restart would hang on the default fake restart() resumes via session/load, which "full" mode never answers (1800 s timeout) Mode loadReplay answers everything Act 2 drives; Act 1's holds use hangOnPrompt before the flip
function_body_length (53 > 50) introduced by the audit's smoke restructure The skill's own warning: an audit fix can add a violation Act 1 extracted to a file-local helper (heldTurnWireContracts)

Files Changed

File Change Summary
Museion/EngineHost.swift NEW — the EngineTransport seam + the engine lifecycle owner
Museion/ACPEngineClient.swift Conformance; onMessage property + start(); concrete defaults cut
Museion/MentorSessionModel.swift Lifecycle removed (−211 lines); all engine work routed through host
MuseionTests/ScriptedEngine.swift NEW — scripted in-process adapter, payloads, rig roots
MuseionTests/EngineSmokeTests.swift NEW — one real-process wire smoke per surface (chat two-act + parameterized passes)
MuseionTests/ACPClientTests.swift Migrated in-process; zsh harness retained as the wire fixture
MuseionTests/{EngineLifecycle,PassRun,BlindRead,SessionLifecycle,SessionScope,TranscriptRail,ResearchCandidate}Tests.swift Migrated to scripted rigs; pid pins → identity/isClosed pins
Museion/AGENTS.md, MuseionTests/AGENTS.md DOX: ACP-bridge section, test conventions + suite map
AGENTS.md gitnexus index stat line (auto)

Open Items & Next Steps

  • #181 (Provider descriptor + Pass Readiness, blocked-by #178) is unblocked by this merge.
  • Deferred: LocalizedError on engine error types so failure rows render the real message (pre-existing cosmetic; candidate rider on #181).
  • Deferred (taste, rejected by audit): folding hasChat/isOneShotRunning into bare != nil reads.

Verification (final tree, cited from the session's last run): build-for-testing + test-without-building — 652 executed / 652 passed / 0 failed (653 argument cases; the pass smoke's .pass1/.pass2 children individually Passed), counted via xcrun xcresulttool get test-results summary, never the SUCCEEDED banner. swiftformat idempotent; swiftlint 0 violations in touched files (model's two pre-existing warnings reduced: type_body_length 346→296). gitnexus detect-changes before the final analyze reported exactly the intended blast radius (lifecycle symbols over the RunPass/RunBlindRead/SendPrompt flows).

Log written by write-log skill