feat(acp): add M0 ACP bridge — engine child + mentor pane (fixes #14)
CI / ci (push) Canceled after 0s
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:
1 parent
c0b2cb0b93
commit
f21d3a6844
12 files changed
+1271
-10
No files matched your search
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **museion** (752 symbols, 1122 relationships, 11 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **museion** (963 symbols, 1674 relationships, 31 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).
|
||||
|
||||
@@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-09-16 | [20260916-issue14-acp-bridge-s2-2_log.md](docs/devlog/20260916-issue14-acp-bridge-s2-2_log.md) |
|
||||
| 2026-09-05 | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](docs/devlog/20260905-issue48-provisioning-failure-alert-retry-ux_log.md) |
|
||||
| 2026-09-03 | [20260903-issue42-engine-gate-s2-1_log.md](docs/devlog/20260903-issue42-engine-gate-s2-1_log.md) |
|
||||
<!-- write-log: window-end -->
|
||||
@@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **acp:** M0 ACP bridge (PRD S2.2) — the app spawns the Hermes engine (`hermes acp -p museion`) as a child process via a hand-rolled NDJSON JSON-RPC stdio client, opens a Session, streams mentor replies live in a debug pane, renders fix-card tool calls as structured cards, cancels turns via Stop, tears the child down on quit, and surfaces an in-pane restart prompt on engine crash — never data loss (issue #14)
|
||||
- **provisioning:** S2.1 profile provisioning — idempotent per-gate pass creates the `museion` Hermes profile (`hermes profile create --no-alias --no-skills`) and additively seeds the bundled writing skills via `seed-manifest.txt`; existing skills are never overwritten (issue #47)
|
||||
- **provisioning:** Failure alert & retry UX — provisioning failures show a separate phase-named alert (never re-raising the gate) with the error excerpt behind Technical details; Retry re-runs the whole pass, Not Now defers to the next launch's silent retry (issue #48)
|
||||
- **gate:** Engine gate (launch gate, PRD S2.1) — discovers the user-installed Hermes engine via the documented six-path probe, health-checks it (`hermes acp --check`), and blocks app launch behind a sheet on every launch: checking/pass/fail cards with install instructions and re-check on fail, engine version in the pass card, About window, and a `state.json` record of every completed check (issue #42)
|
||||
|
||||
@@ -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) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//
|
||||
// ACPClientTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// M0 ACP bridge (#14): the fake ACP server test double — a zsh script
|
||||
// speaking real NDJSON JSON-RPC on stdio (map decision: extends the
|
||||
// fake-binary Process pattern from EngineGateTests). Exercises the client
|
||||
// and model against the real Process path: handshake, prompt + streamed
|
||||
// updates + fix-card tool call, crash, teardown.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
// MARK: - Fake ACP server + helpers
|
||||
|
||||
/// Builds a fake engine binary that speaks enough ACP for the M0 client.
|
||||
/// `mode`: `full` answers everything; `crashAfterHandshake` exits 1 right
|
||||
/// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt.
|
||||
/// 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.
|
||||
private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String {
|
||||
let path = (dir as NSString).appendingPathComponent(name)
|
||||
let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode")
|
||||
// ponytail: built field-by-field so the line stays under the lint cap.
|
||||
let card: [(String, String)] = [
|
||||
("pattern", "Blame tense"),
|
||||
("problem", "Never pivots to choice"),
|
||||
("diagnosticQuestion", "What tense?"),
|
||||
("fix", "Pivot on the hinge"),
|
||||
("anchor", "We should stop listening."),
|
||||
("provenance", "posts/x · pass 1"),
|
||||
("status", "proposed"),
|
||||
]
|
||||
let fixCard = card.map { "\"\($0.0)\":\"\($0.1)\"" }.joined(separator: ",")
|
||||
let fixCardB64 = Data(("{" + fixCard + "}").utf8).base64EncodedString()
|
||||
// ponytail: one echo per wire message — long payloads ride shell vars so
|
||||
// each line stays under the lint cap and inspectable against the schema.
|
||||
let script = """
|
||||
#!/bin/zsh
|
||||
mode="full"
|
||||
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
|
||||
card=$(print -- '\(fixCardB64)' | base64 -d)
|
||||
framing='{"jsonrpc":"2.0","id":'
|
||||
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":'
|
||||
while IFS= read -r line; do
|
||||
[[ -z "$line" ]] && continue
|
||||
method=$(echo "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
|
||||
rid=$(echo "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
|
||||
if [[ "$method" == "initialize" ]]; then
|
||||
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
|
||||
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
|
||||
elif [[ "$method" == "session/new" ]]; then
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
|
||||
elif [[ "$method" == "session/prompt" ]]; then
|
||||
echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}'
|
||||
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}'
|
||||
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
|
||||
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
|
||||
if [[ "$mode" == "hangOnPrompt" ]]; then
|
||||
sleep 30
|
||||
fi
|
||||
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
|
||||
elif [[ "$method" == "session/cancel" ]]; then
|
||||
print -u2 -- "cancel received"
|
||||
fi
|
||||
done
|
||||
exit 0
|
||||
"""
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
try? mode.write(toFile: modeFile, atomically: true, encoding: .utf8)
|
||||
try? script.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
|
||||
return path
|
||||
}
|
||||
|
||||
private func acpTempDir(_ label: String) -> String {
|
||||
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
return dir
|
||||
}
|
||||
|
||||
// MARK: - Client tests
|
||||
|
||||
@Suite("ACPClientTests")
|
||||
struct ACPClientTests {
|
||||
@Test func `handshake returns agent version`() async throws {
|
||||
let fake = makeFakeACP(at: acpTempDir("handshake"))
|
||||
let client = ACPEngineClient(binaryPath: fake)
|
||||
try client.start { _, _ in }
|
||||
let result = try await client.request("initialize", params: .object([
|
||||
"protocolVersion": .number(1),
|
||||
"clientCapabilities": .object([:]),
|
||||
"clientInfo": .object(["name": .string("Museion"), "title": .string("Museion"), "version": .string("0.1")]),
|
||||
]))
|
||||
client.close()
|
||||
#expect(result?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue == "9.9.9")
|
||||
}
|
||||
|
||||
@Test func `crash after handshake fires onCrash`() async throws {
|
||||
let fake = makeFakeACP(at: acpTempDir("crash"), mode: "crashAfterHandshake")
|
||||
let client = ACPEngineClient(binaryPath: fake)
|
||||
try client.start { _, _ in }
|
||||
// Hook FIRST, then trigger: the fake exits right after answering
|
||||
// initialize, so the crash can beat a hook attached after the request.
|
||||
await confirmation("onCrash fires once") { crashed in
|
||||
client.onCrash = { crashed() }
|
||||
_ = try? await client.request("initialize", params: nil)
|
||||
try? await Task.sleep(for: .milliseconds(500))
|
||||
}
|
||||
client.close()
|
||||
}
|
||||
|
||||
@Test func `cancel is fire-and-forget`() async throws {
|
||||
let fake = makeFakeACP(at: acpTempDir("cancel"), mode: "hangOnPrompt")
|
||||
let client = ACPEngineClient(binaryPath: fake)
|
||||
try client.start { _, _ in }
|
||||
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
|
||||
// Prompt hangs (sleep 30) — drive it in the background, then cancel.
|
||||
let promptTask = Task { try? await client.request("session/prompt", params: .object([
|
||||
"sessionId": .string("sess-1"),
|
||||
"prompt": .array([.object(["type": .string("text"), "text": .string("hello")])]),
|
||||
])) }
|
||||
try await Task.sleep(for: .milliseconds(300))
|
||||
client.notify("session/cancel", params: .object(["sessionId": .string("sess-1")]))
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
client.close() // also resumes the hung prompt task with an error
|
||||
_ = await promptTask.value
|
||||
// ponytail: reaching here without deadlock IS the cancel test — a
|
||||
// notification produces no response and the client never waits for one.
|
||||
#expect(true)
|
||||
}
|
||||
|
||||
@Test func `teardown kills a hung child and fails pending requests`() async throws {
|
||||
let fake = makeFakeACP(at: acpTempDir("teardown"), mode: "hangOnPrompt")
|
||||
let client = ACPEngineClient(binaryPath: fake)
|
||||
try client.start { _, _ in }
|
||||
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
|
||||
let promptTask = Task { try? await client.request("session/prompt", params: .object([
|
||||
"sessionId": .string("sess-1"),
|
||||
"prompt": .array([.object(["type": .string("text"), "text": .string("hello")])]),
|
||||
])) }
|
||||
try await Task.sleep(for: .milliseconds(300))
|
||||
let pid = client.childProcessIdentifier
|
||||
client.close()
|
||||
_ = await promptTask.value
|
||||
var gone = false
|
||||
for _ in 0 ..< 50 where kill(pid, 0) != 0 {
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
}
|
||||
if kill(pid, 0) != 0 {
|
||||
gone = true
|
||||
}
|
||||
#expect(gone)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Model tests
|
||||
|
||||
@MainActor
|
||||
@Test func `model handshake renders version and streams fix card`() async {
|
||||
let fake = makeFakeACP(at: acpTempDir("model"))
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
await model.openSession()
|
||||
guard case let .ready(sessionId) = model.phase else {
|
||||
Issue.record("expected ready, got \(model.phase)")
|
||||
return
|
||||
}
|
||||
#expect(sessionId == "sess-1")
|
||||
#expect(model.engineVersion == "9.9.9")
|
||||
await model.sendPrompt("hello mentor")
|
||||
let hasCard = model.rows.contains { row in
|
||||
if case let .fixCard(card) = row.content {
|
||||
return card.pattern == "Blame tense"
|
||||
}
|
||||
return false
|
||||
}
|
||||
#expect(hasCard)
|
||||
let hasText = model.rows.contains { row in
|
||||
if case let .text(text) = row.content {
|
||||
return text.contains("Hello mentor.")
|
||||
}
|
||||
return false
|
||||
}
|
||||
#expect(hasText)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `model surfaces advisory version drift note`() async {
|
||||
let fake = makeFakeACP(at: acpTempDir("drift"))
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
// Running 9.9.9 vs recorded 0.20.6 → the advisory note fires, never blocks.
|
||||
model.recordedVersionProvider = { "0.20.6" }
|
||||
await model.openSession()
|
||||
guard case .ready = model.phase else {
|
||||
Issue.record("expected ready despite drift, got \(model.phase)")
|
||||
return
|
||||
}
|
||||
#expect(model.versionNote?.contains("9.9.9") == true)
|
||||
#expect(model.versionNote?.contains("0.20.6") == true)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `model crash surfaces restart prompt and fresh engine recovers`() async throws {
|
||||
let dir = acpTempDir("restart")
|
||||
let crashing = makeFakeACP(at: dir, name: "hermes-acp-crash", mode: "crashAfterHandshake")
|
||||
let model = MentorSessionModel(binaryPath: crashing)
|
||||
await model.openSession()
|
||||
for _ in 0 ..< 100 {
|
||||
if case .crashed = model.phase {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(50))
|
||||
}
|
||||
guard case .crashed = model.phase else {
|
||||
Issue.record("expected crashed after engine exit, got \(model.phase)")
|
||||
return
|
||||
}
|
||||
// A fresh model against a healthy fake at a different path stands in for
|
||||
// restart recovery (the pane's Restart button drives model.restart()).
|
||||
let healthy = makeFakeACP(at: dir, name: "hermes-acp-ok")
|
||||
let model2 = MentorSessionModel(binaryPath: healthy)
|
||||
await model2.openSession()
|
||||
guard case .ready = model2.phase else {
|
||||
Issue.record("expected ready on healthy engine, got \(model2.phase)")
|
||||
return
|
||||
}
|
||||
model.shutdown()
|
||||
model2.shutdown()
|
||||
}
|
||||
@@ -18,6 +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`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash).
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile 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. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# ACP bridge spike — M0 (#14)
|
||||
|
||||
> **Date:** 2026-09-16
|
||||
> **Type:** issue
|
||||
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/14
|
||||
|
||||
## Goal
|
||||
|
||||
Implement the M0 ACP bridge spike per the #14 wayfinder map's settled decisions: the app spawns the Engine (`hermes acp -p museion`) as a child process through a hand-rolled thin Swift ACP client (NDJSON JSON-RPC on stdio), opens a Session, sends prompts, streams replies live in a debug pane, round-trips a fix-card-shaped tool call as structured data, tears down on quit, and surfaces a restart prompt on child crash — never data loss.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- `Museion/ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable) + `JSONValue` (decoded-wire value type, Sendable all the way down). Serial-queue-confined state; NDJSON framing; response matching by id; **requests time out (15 s default)** — a hung engine surfaces as an error → restart prompt, never an eternal await; `onCrash` on unexpected exit/EOF (never on explicit close); auto `-32601` reply to server→client requests (M0 handles none — the deny option); SIGPIPE ignored; `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap.
|
||||
- `Museion/MentorSessionModel.swift` — pane model: lazy spawn, `initialize` handshake with advisory version compare vs state.json (`recordedVersionProvider` injectable), `session/new` cwd `~`, prompt streaming (`agent_message_chunk`/`agent_thought_chunk` buffered, flushed on turn end), fix-card parse from tool-call `rawInput` (ADR-0006 fields, pattern+problem minimum), raw-JSON rows for everything else, `session/cancel` notification on Stop, crash keeps transcript + last prompt, restart re-spawns, `shutdown()` for app quit (scenePhase → `.inactive`).
|
||||
- `Museion/MentorPaneView.swift` — the debug pane (post-gate main surface): header with running version + orange drift note, transcript (text / FixCardRow / RawUpdateRow), freeform input + send + Stop, crash card with Restart + Technical details (stderr tail).
|
||||
- Wiring — `AppGateState.mentor` (app-scoped model), `ContentView` renders the pane once the gate's `currentBinaryPath` exists (gate's winner, no re-probe), `MuseionApp` tears down on scenePhase `.inactive`. Hosted-test guard: the pane never auto-opens a session under `XCTestConfigurationFilePath` (the test host is the runner — a real engine child would kill it).
|
||||
- `MuseionTests/ACPClientTests.swift` — fake ACP server: a zsh script speaking real NDJSON JSON-RPC over the real Process path. Per-binary mode file (`full`/`crashAfterHandshake`/`hangOnPrompt`, self-locating), fix-card payload base64-encoded beside the binary (shell quoting can never break the wire JSON). 7 tests: handshake version, streamed updates + fix-card (model over the real client+fake path), advisory drift note, crash → onCrash exactly once (latched — exit+EOF both fire), cancel fire-and-forget, teardown kills hung child, crash → restart recovery.
|
||||
- DOX: `Museion/AGENTS.md` gained the "ACP bridge (S2.2, #14 map)" section; `MuseionTests/AGENTS.md` documents the fake-server pattern.
|
||||
|
||||
## Decisions (settled on the map — implemented, not re-decided)
|
||||
|
||||
- Transport: NDJSON JSON-RPC on stdio; stdout is the wire, stderr is logs.
|
||||
- Lifecycle: lazy spawn, app-life child, quit teardown, crash → in-pane Restart.
|
||||
- Version verify: advisory — os_log + both versions in the pane, never blocks.
|
||||
- Fix-card round-trip: fake-server test double (real rail is M2/#23 museion-tools).
|
||||
- Rendering: text + tool calls first-class; every other update type raw JSON.
|
||||
- Cancel: Stop button → `session/cancel` notification (verified: no response exists).
|
||||
|
||||
## Verification
|
||||
|
||||
- `xcodebuild … build` — **BUILD SUCCEEDED**.
|
||||
- `xcodebuild … test` — **TEST SUCCEEDED, 36/36** (all unit suites incl. 7 ACP/model tests + UI smoke test), re-verified after the finish-audit fixes.
|
||||
- `swiftformat` + `swiftlint` clean on all touched files.
|
||||
|
||||
## Notes
|
||||
|
||||
- Wire ground truth re-verified against the installed acp SDK 0.9.0 / adapter 0.20.6 before coding: `session/cancel` IS a notification (`interfaces.py` CancelNotification), `SessionNotification.update` discriminates on `sessionUpdate`, responses camelCase (`agentInfo`, `sessionId`, `stopReason`), tool calls carry `rawInput`/`title`.
|
||||
- Two test-host traps found the hard way: (1) closing pipe file handles with readability handlers still installed crashes Foundation — handlers off first; (2) the hosted unit-test runner IS the app, so any auto-spawned real engine child at pane-mount kills the runner ("test runner exited with code 0") — guarded via `XCTestConfigurationFilePath`. A third: requests without a deadline hang forever under parallel-suite load — every `request()` now carries a 15 s timeout (also correct in production: hung engine → error → restart prompt, not an eternal spinner).
|
||||
- Not done (map's Out of scope): museion-tools MCP server (#23/M2), session lifecycle UI (#28/S2.3), profile backup (#15/S2.6).
|
||||
|
||||
## Finish-audit pass (2026-09-16)
|
||||
|
||||
Three parallel reviewers (ponytail / security / general — the latter two hit API-timeout caps mid-read, findings salvaged from transcripts; the ponytail report landed in full). All three independently caught the same ship-blocker. Accepted and fixed:
|
||||
|
||||
- **Bug (all reviewers):** `binaryPathProvider` closure was never wired in production — `AppGateState.mentor` used the `{ nil }` default, so the shipped pane could never spawn the engine. Replaced with `var binaryPath: String?` handed in via `MentorPaneView(model:binaryPath:)`.
|
||||
- **Bug:** quit teardown keyed on `scenePhase .inactive`, which fires on plain focus loss on macOS — engine killed on every app switch. Now `NSApplication.willTerminateNotification`.
|
||||
- **Bug (found by the fix's own test):** child-exit AND stdout-EOF both fire for one crash → `onCrash` twice. `failAll` now latches; fires exactly once.
|
||||
- **Hardening:** 1 MB line cap in the NDJSON ingester (unbounded buffer on a corrupt/hostile newline-free stream).
|
||||
- Shrinks: TurnState enum → `isStreaming` Bool; `handleChildExit`/`handleEOF` → one `failAll`; `arguments` param hardcoded; unused `Equatable`s deleted; scroll helper dedup; client-level stream test + `UpdateRecorder` dropped (model test covers the same real path); `LockedFlag` → Swift Testing `confirmation`.
|
||||
- Deferred: merging `close()` into `EngineProbe.terminateAndReap` — different shapes (grace period, handle sets, pending-continuation failing); not worth the cross-file refactor.
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/ACPEngineClient.swift` | new — NDJSON JSON-RPC stdio client + JSONValue |
|
||||
| `Museion/MentorSessionModel.swift` | new — pane model: lifecycle, streaming, fix-card parse |
|
||||
| `Museion/MentorPaneView.swift` | new — the debug pane UI |
|
||||
| `MuseionTests/ACPClientTests.swift` | new — fake ACP server + 7 tests |
|
||||
| `Museion/ContentView.swift` | pane mounts post-gate with the gate's binary |
|
||||
| `Museion/MuseionApp.swift` | app-scoped mentor model + willTerminate teardown |
|
||||
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md`, `docs/devlog/INDEX.md`, `CHANGELOG.md` | DOX + records |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Close map #14 on the forge (comment + close — needs Alexander's authorization)
|
||||
- [ ] Live-turn smoke against the real engine + GLM credentials (AC says one-shot ready, #49)
|
||||
- [ ] museion-tools MCP server (#23, M2) — the real fix-card rail
|
||||
- [ ] Session lifecycle UI (#28, S2.3)
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,5 +5,6 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-09-16 | issue | [20260916-issue14-acp-bridge-s2-2_log.md](20260916-issue14-acp-bridge-s2-2_log.md) | #14 M0 ACP bridge: NDJSON JSON-RPC client, mentor pane, fix-card round-trip, crash restart — 37 tests green |
|
||||
| 2026-09-05 | issue | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](20260905-issue48-provisioning-failure-alert-retry-ux_log.md) | #48 shipped: failure card with retry/Not-Now, traversal guard, temp sweep — 30 tests green |
|
||||
| 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green |
|
||||
Reference in new issue
Block a user