fix(acp): repair mentor bridge for adapter 0.21.5
Two bugs after the engine update, both found via a live NDJSON repro against the real binary: session/new now requires mcpServers in the ACP SDK schema (NewSessionRequest). Museion sent only cwd, the engine answered -32602, the handshake threw, and the pane showed "the mentor engine stopped" — a validation rejection dressed as a crash. Send the honest empty list; Museion ships no MCP servers (#44 invariant, now pinned on the wire by a strict fake in tests). The advisory version-drift note compared raw strings: the gate records the derived version from `acp --version` (0.21.5+2177.g735e426) while initialize answers the base version (agentInfo.version -> 0.21.5), fabricating drift on every launch. Compare base versions (strip +build metadata); real drift still fires. Wire facts re-verified against adapter 0.21.5; docs updated.
This commit is contained in:
1 parent
e5490ed290
commit
de76a50cc6
6 files changed
+97
-11
No files matched your search
@@ -19,3 +19,7 @@ All notable changes to this project will be documented in this file. The format
|
||||
- **skills:** Micro-drill prompt-pack skill — two-minute single-shelf drill offers riding the Pass finding that motivates them; declined drills vanish, drill output never touches the draft (issue #8)
|
||||
- **skills:** Craft canon distilled from the #4 shortlist — rhetoric (Heinrichs: argument and rhetoric, ten cards plus the fallacy index), reader-psychology (Williams: the reader-processing diagnosis sequence), prose-craft (Clark: fifteen generative tools across better-words, structure, humor, revision); a sample Pass demonstrates all three firing as fix cards (issue #7)
|
||||
- **skills:** Titles-and-hooks craft skill distilled from web sources per the #4 research — the title surface (takeaway over label, bounded numbers, the worn tease, mode fit, person over committee voice) and the hook's curiosity gap (open it, foot it, honor the title–hook contract), every rule data-backed; the sample Pass gains a ninth fix card demonstrating the shelf (issue #11)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **acp:** mentor pane against adapter 0.21.5 — `session/new` now sends the newly required `mcpServers` list (empty: Museion ships none); its absence was rejected as invalid params and wrongly surfaced as "the mentor engine stopped" when the engine was fine. The advisory version-drift note now compares base versions, so build metadata (`0.21.5+2177.g735e426` recorded vs `0.21.5` reported) no longer fabricates a mismatch on every launch; real drift still fires.
|
||||
@@ -2,11 +2,11 @@
|
||||
// ACPEngineClient.swift
|
||||
// Museion
|
||||
//
|
||||
// M0 ACP bridge (#14): a hand-rolled thin client speaking NDJSON JSON-RPC on
|
||||
// stdio to `hermes acp -p museion` (ponytail: no Swift ACP SDK exists;
|
||||
// revisit if one appears). Wire facts verified against adapter 0.20.6 —
|
||||
// one JSON message per \n-terminated line, stdout is the wire, stderr is
|
||||
// engine logs (never parsed for protocol state).
|
||||
// M0 ACP bridge (#14): a hand-rolled thin client speaking NDJSON JSON-RPC on
|
||||
// stdio to `hermes acp -p museion` (ponytail: no Swift ACP SDK exists;
|
||||
// revisit if one appears). Wire facts verified against adapter 0.21.5 —
|
||||
// one JSON message per \n-terminated line, stdout is the wire, stderr is
|
||||
// engine logs (never parsed for protocol state).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
+2
-2
@@ -51,8 +51,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
|
||||
## ACP bridge (S2.2, #14 map)
|
||||
|
||||
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.20.6 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
|
||||
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; one os_log line + both versions in the pane, never blocks) → `session/new` cwd `~`. `sendPrompt` streams `agent_message_chunk`/`thought` into a buffer flushed on turn end; tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields); every other update type a collapsible raw-JSON row. Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
|
||||
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
|
||||
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks) → `session/new` cwd `~` + `mcpServers: []`. `sendPrompt` streams `agent_message_chunk`/`thought` into a buffer flushed on turn end; tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields); every other update type a collapsible raw-JSON row. Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
|
||||
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note), transcript (text rows, FixCardRow cards, RawUpdateRow disclosure), freeform input 1…4 lines + send + Stop while streaming, crash card (Restart, last prompt, stderr tail behind Technical details).
|
||||
- Wiring: `AppGateState.mentor` is the app-scoped model ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss).
|
||||
- Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
|
||||
|
||||
@@ -186,10 +186,13 @@ final class MentorSessionModel {
|
||||
|
||||
// Advisory version verify against state.json's recorded version
|
||||
// (map decision: one os_log line + both versions in the pane; never blocks).
|
||||
// The gate records the derived version (`acp --version` → 0.21.5+2177.g735e426);
|
||||
// the handshake answers the base version (agentInfo.version → 0.21.5) — compare
|
||||
// bases so build metadata never fabricates drift.
|
||||
var note: String?
|
||||
if let version {
|
||||
let recorded = recordedVersionProvider()
|
||||
if let recorded, recorded != version {
|
||||
if let recorded, Self.baseVersion(of: recorded) != Self.baseVersion(of: version) {
|
||||
note = "Engine \(version) differs from the recorded \(recorded)"
|
||||
Logger(subsystem: "com.babylondreams.Museion", category: "acp")
|
||||
.warning("engine version drift: running \(version, privacy: .public), recorded \(recorded, privacy: .public)")
|
||||
@@ -197,10 +200,14 @@ final class MentorSessionModel {
|
||||
}
|
||||
versionNote = note
|
||||
|
||||
// New session — cwd ~ (map decision).
|
||||
// New session — cwd ~ (map decision). Adapter ≥0.21.5 requires mcpServers
|
||||
// (ACP SDK NewSessionRequest); Museion ships none, so the honest empty list.
|
||||
let newResult = try await client.request(
|
||||
"session/new",
|
||||
params: .object(["cwd": .string(cwdProvider())]),
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
|
||||
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
|
||||
@@ -271,6 +278,12 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Base version of a version string — the part before `+` build metadata
|
||||
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
|
||||
nonisolated static func baseVersion(of version: String) -> String {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
|
||||
// MARK: - Notification decoding
|
||||
|
||||
private func handleNotification(method: String, params: JSONValue?) {
|
||||
|
||||
@@ -82,6 +82,38 @@ private func acpTempDir(_ label: String) -> String {
|
||||
return dir
|
||||
}
|
||||
|
||||
/// A strict `session/new` guard, mirroring the ACP SDK's required mcpServers
|
||||
/// (adapter ≥0.21.5 rejects the field's absence with -32602). The lenient
|
||||
/// fake above accepts anything and can't catch this bug class.
|
||||
private func makeStrictFakeACP(at dir: String, name: String = "hermes-acp-strict") -> String {
|
||||
let path = (dir as NSString).appendingPathComponent(name)
|
||||
let script = """
|
||||
#!/bin/zsh
|
||||
framing='{"jsonrpc":"2.0","id":'
|
||||
jq=/usr/bin/python3
|
||||
while IFS= read -r line; do
|
||||
[[ -z "$line" ]] && continue
|
||||
method=$(echo "$line" | $jq -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
|
||||
rid=$(echo "$line" | $jq -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"}}}'
|
||||
elif [[ "$method" == "session/new" ]]; then
|
||||
ok=$(echo "$line" | $jq -c 'import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")')
|
||||
if [[ "$ok" == "1" ]]; then
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
|
||||
else
|
||||
echo $framing"$rid",'"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}'
|
||||
fi
|
||||
fi
|
||||
done
|
||||
exit 0
|
||||
"""
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
try? script.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
|
||||
return path
|
||||
}
|
||||
|
||||
// MARK: - Client tests
|
||||
|
||||
@Suite("ACPClientTests")
|
||||
@@ -204,6 +236,43 @@ struct ACPClientTests {
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `build metadata does not fabricate version drift`() async {
|
||||
let fake = makeFakeACP(at: acpTempDir("metadata-drift"))
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
// The gate records the derived version; the handshake answers the base —
|
||||
// same engine, strings differ only in +build metadata → no note.
|
||||
model.recordedVersionProvider = { "9.9.9+2177.g735e426" }
|
||||
await model.openSession()
|
||||
guard case .ready = model.phase else {
|
||||
Issue.record("expected ready, got \(model.phase)")
|
||||
return
|
||||
}
|
||||
#expect(model.versionNote == nil)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `real base-version drift still fires the note`() {
|
||||
#expect(MentorSessionModel.baseVersion(of: "0.21.5+2177.g735e426") == "0.21.5")
|
||||
#expect(MentorSessionModel.baseVersion(of: "0.21.5") == "0.21.5")
|
||||
#expect(MentorSessionModel.baseVersion(of: "unknown") == "unknown")
|
||||
#expect(MentorSessionModel.baseVersion(of: "0.20.6") != MentorSessionModel.baseVersion(of: "0.21.5"))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `session new against strict mcpServers schema reaches ready`() async {
|
||||
let fake = makeStrictFakeACP(at: acpTempDir("strict"))
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
await model.openSession()
|
||||
guard case let .ready(sessionId) = model.phase else {
|
||||
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
|
||||
return
|
||||
}
|
||||
#expect(sessionId == "sess-1")
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `model crash surfaces restart prompt and fresh engine recovers`() async throws {
|
||||
let dir = acpTempDir("restart")
|
||||
|
||||
@@ -18,7 +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).
|
||||
- `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). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch.
|
||||
- `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`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17) — throwaway Homes via `makeHome`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`), lazy folders / hidden dirs / symlinks / noise not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
|
||||
|
||||
Reference in new issue
Block a user