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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user