fix(acp): repair mentor bridge for adapter 0.21.5

Two bugs after the engine update, both found via a live NDJSON
repro against the real binary:

session/new now requires mcpServers in the ACP SDK schema
(NewSessionRequest). Museion sent only cwd, the engine answered
-32602, the handshake threw, and the pane showed "the mentor
engine stopped" — a validation rejection dressed as a crash. Send
the honest empty list; Museion ships no MCP servers (#44
invariant, now pinned on the wire by a strict fake in tests).

The advisory version-drift note compared raw strings: the gate
records the derived version from `acp --version`
(0.21.5+2177.g735e426) while initialize answers the base version
(agentInfo.version -> 0.21.5), fabricating drift on every launch.
Compare base versions (strip +build metadata); real drift still
fires.

Wire facts re-verified against adapter 0.21.5; docs updated.
This commit is contained in:
AlexKucera committed 2026-10-02 11:32:49 +02:00
1 parent e5490ed290
commit de76a50cc6
6 files changed
+97 -11

No files matched your search

+5 -5
View File
@@ -2,11 +2,11 @@
// ACPEngineClient.swift
// Museion
//
// M0 ACP bridge (#14): a hand-rolled thin client speaking NDJSON JSON-RPC on
// stdio to `hermes acp -p museion` (ponytail: no Swift ACP SDK exists;
// revisit if one appears). Wire facts verified against adapter 0.20.6 —
// one JSON message per \n-terminated line, stdout is the wire, stderr is
// engine logs (never parsed for protocol state).
// M0 ACP bridge (#14): a hand-rolled thin client speaking NDJSON JSON-RPC on
// stdio to `hermes acp -p museion` (ponytail: no Swift ACP SDK exists;
// revisit if one appears). Wire facts verified against adapter 0.21.5 —
// one JSON message per \n-terminated line, stdout is the wire, stderr is
// engine logs (never parsed for protocol state).
//
import Foundation
+2 -2
View File
@@ -51,8 +51,8 @@ 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.20.6 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `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): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; one os_log line + both versions in the pane, never blocks) → `session/new` cwd `~`. `sendPrompt` streams `agent_message_chunk`/`thought` into a buffer flushed on turn end; tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields); every other update type a collapsible raw-JSON row. 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.
- `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): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), 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) → `session/new` cwd `~` + `mcpServers: []`. `sendPrompt` streams `agent_message_chunk`/`thought` into a buffer flushed on turn end; tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields); every other update type a collapsible raw-JSON row. 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.
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note), transcript (text rows, FixCardRow cards, RawUpdateRow disclosure), freeform input 1…4 lines + send + Stop while streaming, crash card (Restart, last prompt, stderr tail behind Technical details).
- 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.
+16 -3
View File
@@ -186,10 +186,13 @@ final class MentorSessionModel {
// Advisory version verify against state.json's recorded version
// (map decision: one os_log line + both versions in the pane; never blocks).
// The gate records the derived version (`acp --version` → 0.21.5+2177.g735e426);
// the handshake answers the base version (agentInfo.version → 0.21.5) — compare
// bases so build metadata never fabricates drift.
var note: String?
if let version {
let recorded = recordedVersionProvider()
if let recorded, recorded != version {
if let recorded, Self.baseVersion(of: recorded) != Self.baseVersion(of: version) {
note = "Engine \(version) differs from the recorded \(recorded)"
Logger(subsystem: "com.babylondreams.Museion", category: "acp")
.warning("engine version drift: running \(version, privacy: .public), recorded \(recorded, privacy: .public)")
@@ -197,10 +200,14 @@ final class MentorSessionModel {
}
versionNote = note
// New session — cwd ~ (map decision).
// New session — cwd ~ (map decision). Adapter ≥0.21.5 requires mcpServers
// (ACP SDK NewSessionRequest); Museion ships none, so the honest empty list.
let newResult = try await client.request(
"session/new",
params: .object(["cwd": .string(cwdProvider())]),
params: .object([
"cwd": .string(cwdProvider()),
"mcpServers": .array([]),
]),
)
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
@@ -271,6 +278,12 @@ final class MentorSessionModel {
}
}
/// 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 {
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
}
// MARK: - Notification decoding
private func handleNotification(method: String, params: JSONValue?) {