Files
museion/MuseionTests/ACPClientTests.swift
T
AlexKuceraandClaude f21d3a6844
CI / ci (push) Canceled after 0s
feat(acp): add M0 ACP bridge — engine child + mentor pane (fixes #14)
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>
2026-09-16 18:57:41 +02:00

235 lines
9.4 KiB
Swift

//
// 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()
}