feat(acp): add M0 ACP bridge — engine child + mentor pane (fixes #14)
CI / ci (push) Canceled after 0s

Spawn hermes acp -p museion over NDJSON JSON-RPC stdio via a
hand-rolled thin client (no Swift SDK exists). The mentor debug
pane streams replies, renders fix-card tool calls as structured
cards (ADR-0006), cancels via session/cancel, tears down on quit
(willTerminate), and surfaces a restart prompt on engine crash —
never data loss. Version verify against state.json is advisory.

Fake ACP server test double (zsh speaking real NDJSON) covers
handshake, streaming + fix-card, drift, crash latch, cancel,
teardown. 36/36 tests green; finish-audit fixes included (wired
binaryPath, focus-loss teardown bug, double onCrash latch).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
AlexKuceraandClaude committed 2026-09-16 18:57:41 +02:00
1 parent c0b2cb0b93
commit f21d3a6844
12 files changed
+1271 -10

No files matched your search

+331
View File
@@ -0,0 +1,331 @@
//
// 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).
//
import Foundation
/// A decoded JSON value — Sendable all the way down, so wire payloads cross
/// isolation boundaries as values, not `Any` boxes.
nonisolated enum JSONValue: Sendable, Equatable {
case object([String: JSONValue])
case array([JSONValue])
case string(String)
case number(Double)
case bool(Bool)
case null
}
nonisolated extension JSONValue {
/// JSONSerialization bridge (decode side).
init(_ any: Any) {
switch any {
case let object as [String: Any]:
self = .object(object.mapValues { JSONValue($0) })
case let array as [Any]:
self = .array(array.map { JSONValue($0) })
case let string as String:
self = .string(string)
case let number as NSNumber:
// ponytail: NSNumber(bool) also answers Int/Double — bool must be tested first.
if CFGetTypeID(number) == CFBooleanGetTypeID() {
self = .bool(number.boolValue)
} else {
self = .number(number.doubleValue)
}
default:
self = .null
}
}
/// JSONSerialization bridge (encode side).
var any: Any {
switch self {
case let .object(object): object.mapValues { $0.any }
case let .array(array): array.map(\.any)
case let .string(string): string
case let .number(number): number
case let .bool(bool): bool
case .null: NSNull()
}
}
var stringValue: String? {
if case let .string(string) = self {
return string
}
return nil
}
var objectValue: [String: JSONValue]? {
if case let .object(object) = self {
return object
}
return nil
}
}
/// Thin async ACP client: spawns the engine child, frames NDJSON on stdio,
/// matches responses to pending requests, and delivers notifications in wire
/// order. Requests are expected to be strictly sequential (initialize →
/// session/new → prompt), matching the pane's usage.
///
/// Wire facts baked in (verified against adapter 0.20.6 + the acp SDK):
/// - `session/cancel` is a JSON-RPC *notification* (interfaces.py — CancelNotification).
/// - Responses carry camelCase keys (`agentInfo`, `sessionId`, `stopReason`).
/// - Notifications discriminate updates on `update.sessionUpdate`.
final nonisolated class ACPEngineClient: @unchecked Sendable {
struct TransportError: Error, CustomStringConvertible {
let message: String
var description: String {
message
}
}
private let process = Process()
private let stdinPipe = Pipe()
private let stdoutPipe = Pipe()
private let stderrPipe = Pipe()
/// All mutable state below is confined to this serial queue.
private let queue = DispatchQueue(label: "com.babylondreams.Museion.acp-client")
private var pending: [Int: CheckedContinuation<JSONValue?, any Error>] = [:]
private var buffer = Data()
private var currentID = 0
private var closed = false
private var started = false
/// Latched on first fire — child-exit AND stdout-EOF both arrive for one
/// crash; onCrash must surface exactly once.
private var crashed = false
/// Fires when the child dies unexpectedly (crash or EOF) — never on an
/// explicit `close()`, which is the app's own teardown.
var onCrash: (@Sendable () -> Void)?
/// stderr lines (engine logs) — surfaced for the restart prompt's details.
var onStderrLine: (@Sendable (String) -> Void)?
init(binaryPath: String) {
process.executableURL = URL(fileURLWithPath: binaryPath)
process.arguments = ["acp", "-p", "museion"]
process.standardInput = stdinPipe
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
}
/// The child's pid (tests verify teardown reaped it).
var childProcessIdentifier: pid_t {
process.processIdentifier
}
/// Spawn the child. `onMessage` receives every notification (method +
/// params), in wire order.
func start(onMessage: @escaping @Sendable (_ method: String, _ params: JSONValue?) -> Void) throws {
guard !started else { return }
started = true
// A crashed engine closes the pipe; ignoring SIGPIPE turns a kill-signal
// into a plain EPIPE write error instead of taking the app down.
signal(SIGPIPE, SIG_IGN)
try process.run()
process.terminationHandler = { [weak self] _ in
self?.queue.async { self?.failAll("engine exited (code \(self?.process.terminationStatus ?? 0))") }
}
readStderr()
readStdout(onMessage: onMessage)
}
/// Send a JSON-RPC request and await its matching response result.
/// A request that gets no answer within `timeout` fails — a hung engine
/// must surface as an error (→ restart prompt), never an eternal await.
func request(_ method: String, params: JSONValue? = nil, timeout: TimeInterval = 15) async throws -> JSONValue? {
let id = queue.sync {
currentID += 1
return currentID
}
let payload: [String: Any] = [
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params?.any ?? [String: Any](),
]
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else {
throw TransportError(message: "unencodable request: \(method)")
}
return try await withCheckedThrowingContinuation { continuation in
let registered = queue.sync { () -> Bool in
guard !closed else { return false }
pending[id] = continuation
return true
}
guard registered else {
continuation.resume(throwing: TransportError(message: "engine closed before \(method)"))
return
}
queue.async { self.send(raw) }
// ponytail: deadline on the same serial queue — fires only if the
// response hasn't already resumed and removed the continuation.
queue.asyncAfter(deadline: .now() + timeout) {
if let continuation = self.pending.removeValue(forKey: id) {
continuation.resume(throwing: TransportError(message: "\(method) timed out after \(Int(timeout)) s"))
}
}
}
}
/// Send a JSON-RPC notification (no id, no response).
func notify(_ method: String, params: JSONValue? = nil) {
let payload: [String: Any] = [
"jsonrpc": "2.0",
"method": method,
"params": params?.any ?? [String: Any](),
]
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else { return }
queue.async { self.send(raw) }
}
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the child
/// never outlives the app (same pattern as EngineProbe.terminateAndReap).
func close() {
let alreadyClosed = queue.sync {
if closed {
return true
}
closed = true
for (_, continuation) in pending {
continuation.resume(throwing: TransportError(message: "engine closed"))
}
pending.removeAll()
return false
}
guard !alreadyClosed else { return }
// Handlers off BEFORE closing handles — a readability handler firing on
// a closed handle crashes Foundation.
stdoutPipe.fileHandleForReading.readabilityHandler = nil
stderrPipe.fileHandleForReading.readabilityHandler = nil
if process.isRunning {
process.terminate()
let grace = Date().addingTimeInterval(1.0)
while process.isRunning, Date() < grace {
Thread.sleep(forTimeInterval: 0.01)
}
if process.isRunning {
kill(process.processIdentifier, SIGKILL)
}
}
process.waitUntilExit()
try? stdinPipe.fileHandleForWriting.close()
try? stdoutPipe.fileHandleForReading.close()
try? stderrPipe.fileHandleForReading.close()
}
// MARK: - Private (everything below runs on `queue` unless noted)
/// Frame and write one NDJSON line. A failed write (child gone) is dropped:
/// the crash path owns the UX, not the send.
private func send(_ data: Data) {
var framed = Data(data)
framed.append(0x0A)
try? stdinPipe.fileHandleForWriting.write(contentsOf: framed)
}
/// Fail every pending request and surface the crash — the one exit path
/// for both an unexpected child exit and an stdout EOF. Latched: both
/// signals arrive for one crash, onCrash fires exactly once.
private func failAll(_ reason: String) {
guard !closed, !crashed else { return }
crashed = true
for (_, continuation) in pending {
continuation.resume(throwing: TransportError(message: reason))
}
pending.removeAll()
onCrash?()
}
private func readStderr() {
stderrPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
let data = handle.availableData
guard !data.isEmpty else {
handle.readabilityHandler = nil
return
}
let text = String(data: data, encoding: .utf8) ?? ""
for line in text.split(separator: "\n") {
self?.onStderrLine?(String(line))
}
}
}
private func readStdout(onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
stdoutPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
let data = handle.availableData
guard !data.isEmpty else {
handle.readabilityHandler = nil
self?.queue.async { self?.failAll("engine stdout closed (EOF)") }
return
}
self?.queue.async { self?.ingest(data, onMessage: onMessage) }
}
}
/// Buffer incoming bytes, split on \n, decode each line as one JSON-RPC message.
private func ingest(_ data: Data, onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
buffer.append(data)
// ponytail: 1 MB line cap — a corrupt/hostile engine streaming one
// newline-free line would otherwise grow the buffer unbounded.
if buffer.count > 1_048_576, buffer.firstIndex(of: 0x0A) == nil {
buffer.removeAll()
return
}
while let newline = buffer.firstIndex(of: 0x0A) {
let line = buffer.subdata(in: buffer.startIndex ..< newline)
buffer.removeSubrange(buffer.startIndex ... newline)
guard !line.isEmpty,
let json = try? JSONSerialization.jsonObject(with: line),
let object = json as? [String: Any] else { continue }
dispatch(object, onMessage: onMessage)
}
}
private func dispatch(_ object: [String: Any], onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
let id = object["id"] as? Int
let method = object["method"] as? String
// Server→client request (id + method): M0 has no permission/fs/terminal
// handlers — answer -32601 so the engine never waits on us (the adapter
// always offers a deny option; this is us taking it).
if let id, let method {
let reply: [String: Any] = [
"jsonrpc": "2.0",
"id": id,
"error": ["code": -32601, "message": "Museion M0 handles no server requests"],
]
if let raw = try? JSONSerialization.data(withJSONObject: reply) {
send(raw)
}
return
}
// Response to one of our requests — already on the queue; direct access.
if let id {
guard let continuation = pending.removeValue(forKey: id) else { return }
if let error = object["error"] as? [String: Any] {
let code = (error["code"] as? Int) ?? -1
// ponytail: truncated so a runaway engine can't balloon the restart prompt.
let message = String(((error["message"] as? String) ?? "unknown error").prefix(500))
continuation.resume(throwing: TransportError(message: "\(code): \(message)"))
} else {
continuation.resume(returning: object["result"].map { JSONValue($0) })
}
return
}
// Notification.
if let method {
onMessage(method, object["params"].map { JSONValue($0) })
}
}
}
+8
View File
@@ -32,6 +32,14 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills seeded; `ste-writing`/`writing-for-agents` ship but never seed.
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `<binaryDir>/profiles/<name>`), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload.
## 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.
- `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.
## Work Guidance
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001).
+18 -9
View File
@@ -34,16 +34,25 @@ struct ContentView: View {
var body: some View {
@Bindable var gate = gate
VStack(spacing: 8) {
Image(systemName: "books.vertical")
.font(.largeTitle)
Text(AppMetadata.name)
.font(.title)
.bold()
Text(AppMetadata.tagline)
.foregroundStyle(.secondary)
Group {
// #14: post-gate main surface is the mentor debug pane (M0 demo
// surface, map decision: pane placement). Gate pass hands over the
// probe's winning binary — no re-probe.
if gate.gateModel.currentBinaryPath != nil {
MentorPaneView(model: gate.mentor, binaryPath: gate.gateModel.currentBinaryPath)
} else {
VStack(spacing: 8) {
Image(systemName: "books.vertical")
.font(.largeTitle)
Text(AppMetadata.name)
.font(.title)
.bold()
Text(AppMetadata.tagline)
.foregroundStyle(.secondary)
}
.padding(32)
}
}
.padding(32)
.frame(minWidth: 480, minHeight: 320)
.sheet(isPresented: $gate.gateRaised) {
EngineGateView(
+263
View File
@@ -0,0 +1,263 @@
//
// MentorPaneView.swift
// Museion
//
// M0 ACP bridge (#14): the debug pane — the M0 demo surface. Post-gate main
// surface replacing the content placeholder (map decision: pane placement).
//
import SwiftUI
/// The mentor debug pane: transcript, freeform input, Stop while streaming,
/// restart prompt on crash. Post-gate main surface (map decision).
struct MentorPaneView: View {
@State private var draft = ""
@State private var model: MentorSessionModel
/// Set post-gate by ContentView: the probe's winning binary (no re-probe).
var binaryPath: String?
init(model: MentorSessionModel, binaryPath: String?) {
_model = State(initialValue: model)
self.binaryPath = binaryPath
}
var body: some View {
VStack(spacing: 0) {
header
Divider()
switch model.phase {
case .idle, .starting:
ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
case .ready:
transcript
Divider()
inputBar
case let .crashed(lastPrompt):
crashCard(lastPrompt: lastPrompt)
}
}
.frame(minWidth: 560, minHeight: 420)
.task {
model.binaryPath = binaryPath ?? model.binaryPath
// 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).
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
await model.openSession()
}
}
// MARK: Header
private var header: some View {
HStack(spacing: 8) {
Image(systemName: "bubble.left.and.text.bubble.right")
.foregroundStyle(.secondary)
Text("Mentor Session")
.font(.headline)
if let version = model.engineVersion {
Text(version)
.font(.caption)
.foregroundStyle(.tertiary)
}
if let note = model.versionNote {
Text(note)
.font(.caption)
.foregroundStyle(.orange)
.help(note)
}
Spacer()
if case let .ready(sessionId) = model.phase {
Text("session \(sessionId.prefix(8))")
.font(.caption2)
.foregroundStyle(.tertiary)
.textSelection(.enabled)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
}
// MARK: Transcript
private var transcript: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
ForEach(model.rows) { row in
rowView(row)
.id(row.id)
}
if !model.streamingText.isEmpty {
textRow("Mentor: \(model.streamingText)")
.id("streaming")
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
}
.onChange(of: model.rows.count) { scrollToBottom(proxy) }
.onChange(of: model.streamingText) { scrollToBottom(proxy) }
}
}
private func scrollToBottom(_ proxy: ScrollViewProxy) {
if let last = model.rows.last?.id {
proxy.scrollTo(last, anchor: .bottom)
} else {
proxy.scrollTo("streaming", anchor: .bottom)
}
}
@ViewBuilder
private func rowView(_ row: SessionRow) -> some View {
switch row.content {
case let .text(text):
textRow(text)
case let .fixCard(card):
FixCardRow(card: card)
case let .raw(kind, json):
RawUpdateRow(kind: kind, json: json)
}
}
private func textRow(_ text: String) -> some View {
Text(text)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
// MARK: Input
private var inputBar: some View {
HStack(spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain)
.lineLimit(1 ... 4)
.onSubmit { send() }
Button {
send()
} label: {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
if model.isStreaming {
Button {
model.stopStreaming()
} label: {
Text("Stop")
}
.controlSize(.regular)
}
}
.padding(12)
.disabled(model.phase.isReady == false)
}
private func send() {
let text = draft
draft = ""
Task { await model.sendPrompt(text) }
}
// MARK: Crash → restart prompt (map decision: EOF/crash surfaces an
// in-pane Restart prompt, never data loss)
private func crashCard(lastPrompt: String?) -> some View {
VStack(spacing: 14) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30))
.foregroundStyle(.orange)
Text("The mentor engine stopped")
.font(.title3)
Text("Nothing is lost — the transcript stays, and the engine can be restarted.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
if let lastPrompt, !lastPrompt.isEmpty {
Text("Last prompt: \(lastPrompt)")
.font(.caption)
.foregroundStyle(.tertiary)
.lineLimit(2)
}
Button("Restart") {
Task { await model.restart() }
}
.buttonStyle(.borderedProminent)
if !model.stderrTail.isEmpty {
DisclosureGroup("Technical details") {
Text(model.stderrTail.joined(separator: "\n"))
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: Rows
private struct FixCardRow: View {
let card: FixCard
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Label(card.pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
.font(.callout.weight(.semibold))
if !card.anchor.isEmpty {
Text("“\(card.anchor)”")
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(.secondary)
}
if !card.problem.isEmpty {
Text(card.problem).font(.callout)
}
if !card.diagnosticQuestion.isEmpty {
Text("Diagnostic: \(card.diagnosticQuestion)")
.font(.callout)
.foregroundStyle(.secondary)
}
if !card.fix.isEmpty {
Text("Fix: \(card.fix)").font(.callout)
}
Text(card.provenance + " · " + card.status)
.font(.caption2)
.foregroundStyle(.tertiary)
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8))
}
}
private struct RawUpdateRow: View {
let kind: String
let json: String
var body: some View {
DisclosureGroup {
Text(json)
.font(.system(size: 10, design: .monospaced))
.textSelection(.enabled)
} label: {
Text(kind)
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
#Preview {
MentorPaneView(model: MentorSessionModel(), binaryPath: nil)
}
+330
View File
@@ -0,0 +1,330 @@
//
// MentorSessionModel.swift
// Museion
//
// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle,
// one session, prompt streaming, fix-card render, crash → restart prompt.
//
import Foundation
import Observation
import os
/// One rendered row in the pane transcript. Text + tool calls first-class,
/// the rest raw (map decision: rendering fidelity).
struct SessionRow: Identifiable {
enum Content {
case text(String)
case fixCard(FixCard)
case raw(kind: String, json: String)
}
let id = UUID()
var content: Content
}
/// A Fix Card as defined by CONTEXT.md — pattern, problem, diagnostic
/// question, fix, anchor, provenance, status — riding a typed tool call
/// (ADR-0006), parsed from `rawInput` as data, never prose.
struct FixCard {
var pattern: String
var problem: String
var diagnosticQuestion: String
var fix: String
var anchor: String
var provenance: String
var status: String
}
/// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the
/// pane opens its first session and stays alive for the app's life (map
/// decision: child lifecycle).
@MainActor
@Observable
final class MentorSessionModel {
enum Phase: Equatable {
case idle
case starting
case ready(sessionId: String)
case crashed(lastPrompt: String?)
var isReady: Bool {
if case .ready = self {
return true
}
return false
}
}
private(set) var phase: Phase = .idle
/// True while a turn streams — the Stop button's target.
private(set) var isStreaming = false
private(set) var rows: [SessionRow] = []
/// Streaming buffer for the in-flight agent message; flushed to a row on completion.
private(set) var streamingText = ""
/// Advisory engine-version verdict (map decision: advisory, never blocks).
private(set) var versionNote: String?
/// The running engine's version, from the initialize handshake (always visible).
private(set) var engineVersion: String?
/// Last stderr lines from the engine — the restart prompt's technical details.
private(set) var stderrTail: [String] = []
private var client: ACPEngineClient?
private var sessionId: String?
private var lastPrompt: String?
/// The gate's winning binary path (no re-probe — map decision). Set by the
/// app when the gate passes; tests inject directly.
var binaryPath: String?
/// Session cwd is ~ — neutral for a resident mentor with no Piece context (map decision).
var cwdProvider: () -> String = { NSHomeDirectory() }
/// The gate's recorded engine version (state.json) — injectable for tests.
var recordedVersionProvider: () -> String? = { EngineProbe.readStateRecord()?.engineVersion }
init(binaryPath: String? = nil) {
self.binaryPath = binaryPath
}
deinit {
// nonisolated deinit (Swift 6): close() is nonisolated-safe on the client.
shutdownClientDirectly()
}
/// App-quit teardown (#14): close the engine child cleanly. Idempotent.
func shutdown() {
shutdownClientDirectly()
client = nil
clientRef = nil
phase = .idle
}
/// nonisolated deinit + MainActor shutdown share this: client.close() is
/// thread-safe (its own serial queue) and idempotent.
private nonisolated func shutdownClientDirectly() {
clientRef?.close()
}
/// ponytail: a deinit can't touch MainActor state — the client reference is
/// held in this unsafe mirror solely so deinit can close it. Assigned
/// wherever `client` is assigned.
private nonisolated(unsafe) var clientRef: ACPEngineClient?
/// Lazy spawn on first session open. Idempotent per lifecycle.
func openSession() async {
guard phase == .idle else { return }
phase = .starting
await startEngine()
}
/// Restart after a crash — keeps the transcript (never data loss) and
/// 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
sessionId = nil
streamingText = ""
phase = .starting
await startEngine()
}
private func startEngine() async {
guard let binaryPath else {
phase = .crashed(lastPrompt: nil)
stderrTail = ["no engine binary path available"]
return
}
let client = ACPEngineClient(binaryPath: binaryPath)
self.client = client
clientRef = client
client.onCrash = { [weak self] in
Task { @MainActor in
self?.handleCrash()
}
}
client.onStderrLine = { [weak self] line in
Task { @MainActor in
self?.appendStderr(line)
}
}
do {
try client.start { [weak self] method, params in
Task { @MainActor in
self?.handleNotification(method: method, params: params)
}
}
} catch {
phase = .crashed(lastPrompt: lastPrompt)
stderrTail = ["spawn failed: \(error.localizedDescription)"]
return
}
do {
try await handshake(client)
} catch {
phase = .crashed(lastPrompt: lastPrompt)
stderrTail = ["handshake failed: \(error.localizedDescription)"]
}
}
/// initialize + session/new (map decisions: advisory version verify; cwd ~).
private func handshake(_ client: ACPEngineClient) async throws {
let params: JSONValue = .object([
"protocolVersion": .number(1),
"clientCapabilities": .object([:]),
"clientInfo": .object([
"name": .string("Museion"),
"title": .string("Museion"),
"version": .string("0.1"),
]),
])
let result = try await client.request("initialize", params: params)
let version = result?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue
engineVersion = version
// Advisory version verify against state.json's recorded version
// (map decision: one os_log line + both versions in the pane; never blocks).
var note: String?
if let version {
let recorded = recordedVersionProvider()
if let recorded, recorded != 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)")
}
}
versionNote = note
// New session — cwd ~ (map decision).
let newResult = try await client.request(
"session/new",
params: .object(["cwd": .string(cwdProvider())]),
)
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
}
sessionId = sid
phase = .ready(sessionId: sid)
}
/// Send a prompt and stream the reply. Appends the user row first; the
/// stop_reason response ends the turn (refusal maps to a plain note —
/// wire-verified edge semantics).
func sendPrompt(_ text: String) async {
let prompt = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return }
lastPrompt = prompt
rows.append(SessionRow(content: .text("You: \(prompt)")))
isStreaming = true
defer {
// Flush any streamed-but-unfinished agent text into a row.
if !streamingText.isEmpty {
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
streamingText = ""
}
isStreaming = false
}
do {
let result = try await client!.request("session/prompt", params: .object([
"sessionId": .string(sid),
"prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]),
]))
let stopReason = result?.objectValue?["stopReason"]?.stringValue ?? ""
if stopReason == "refusal" {
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
}
} catch {
// Transport failure mid-turn: the crash path owns the UX; keep the
// partial transcript (never data loss).
guard case .crashed = phase else {
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
return
}
}
}
/// 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.
func stopStreaming() {
guard isStreaming, let sid = sessionId else { return }
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
}
private func handleCrash() {
guard case .ready = phase else {
// A crash during startup also lands in the restart prompt.
if case .starting = phase {
phase = .crashed(lastPrompt: lastPrompt)
}
return
}
phase = .crashed(lastPrompt: lastPrompt)
}
private func appendStderr(_ line: String) {
stderrTail.append(line)
if stderrTail.count > 20 {
stderrTail.removeFirst(stderrTail.count - 20)
}
}
// MARK: - Notification decoding
private func handleNotification(method: String, params: JSONValue?) {
guard method == "session/update",
let params,
let sessionId = params.objectValue?["sessionId"]?.stringValue,
sessionId == self.sessionId else { return }
guard let update = params.objectValue?["update"]?.objectValue else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
switch kind {
case "agent_message_chunk", "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingText += text
case "user_message_chunk":
// The engine echoes the user message; we already rendered it.
break
case "tool_call":
appendToolCall(update)
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()
rows.append(SessionRow(content: .raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? "")))
}
}
/// Tool-call decoding — the fix-card rail (ADR-0006): a tool call whose
/// `rawInput` decodes to fix-card fields renders as a card; any other tool
/// call renders as a raw row.
private func appendToolCall(_ update: [String: JSONValue]) {
let title = update["title"]?.stringValue ?? "tool call"
let rawInput = update["rawInput"]
if let card = FixCard(rawInput: rawInput) {
rows.append(SessionRow(content: .fixCard(card)))
return
}
let json = (try? JSONSerialization.data(withJSONObject: rawInput?.any ?? [:], options: [.sortedKeys])) ?? Data()
rows.append(SessionRow(content: .raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? "")))
}
}
/// Fix Card parsing from a tool call's rawInput — the fields per CONTEXT.md.
private extension FixCard {
init?(rawInput: JSONValue?) {
guard let object = rawInput?.objectValue else { return nil }
// A fix-card-shaped payload carries at least pattern + problem.
guard let patternValue = object["pattern"]?.stringValue,
let problemValue = object["problem"]?.stringValue else { return nil }
pattern = patternValue
problem = problemValue
diagnosticQuestion = object["diagnosticQuestion"]?.stringValue ?? ""
fix = object["fix"]?.stringValue ?? ""
anchor = object["anchor"]?.stringValue ?? ""
provenance = object["provenance"]?.stringValue ?? "engine"
status = object["status"]?.stringValue ?? "proposed"
}
}
+9
View File
@@ -18,6 +18,8 @@ final class AppGateState {
var gateDismissed = false
let gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
/// #14: the app-scoped mentor bridge — the pane renders it; quit tears it down.
let mentor = MentorSessionModel()
}
@main
@@ -28,6 +30,13 @@ struct MuseionApp: App {
WindowGroup {
ContentView()
.environment(gate)
// #14: app quit tears down the engine child cleanly (map
// decision: child lifecycle). willTerminate is the real quit
// signal on macOS — scenePhase .inactive also fires on plain
// focus loss, which would kill the engine on every app switch.
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in
gate.mentor.shutdown()
}
}
Window("About \(AppMetadata.name)", id: "about") {
AboutEngineView()