CI / ci (push) Canceled after 0s
Wires #161's goal engine and #160's contract into the app: armed from a corner dot or View ▸ Start Cold Turkey…, enforced by the macOS app-kiosk (7-option presentation combo + fullscreen, restored on completion), readout with hairline + near-goal terracotta, and a completion note fading back into focus. While held: focus exit, reading, new buffers, ⌘W/⌃⌘F/⌘N refused (key-code-matched monitor — character matching is layout/Caps-blind; no .closeItem placement exists), ⌘Q asks once per #163's ruling. Typing continuity holds by construction — lock ⇒ focus freezes the branch under the editor and chrome mounts as overlays only. Arm values type directly (1…1000 words / 1…60 min, defaults 250/5). Nothing persists. Wayfinder map #158 Build S2; suite 620, flip-verified pins.
700 lines
32 KiB
Swift
700 lines
32 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.
|
|
// #124: hangOnPrompt now acknowledges session/cancel (stopReason
|
|
// "cancelled") — a sleep-oblivious hold can't pin the Cancel rail.
|
|
//
|
|
|
|
// swiftlint:disable file_length
|
|
// One file: the shared fake harness (makeFakeACP/acpTempDir — other test
|
|
// files build rigs on it) + the client/model suites that pin its contract.
|
|
|
|
import Foundation
|
|
@testable import Museion
|
|
import SwiftUI
|
|
import Testing
|
|
|
|
// MARK: - Fake ACP server + helpers
|
|
|
|
// swiftlint:disable function_body_length
|
|
/// 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` streams, then HOLDS the turn
|
|
/// open reading — session/cancel answers the hanging prompt with stopReason
|
|
/// "cancelled" (the real engine's contract, #124), stdin EOF without a
|
|
/// cancel (teardown) answers end_turn, and during the hold ONLY
|
|
/// session/cancel is answered — any other request waits until teardown;
|
|
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled"
|
|
/// with no cancel needed; `refuseOnPrompt` answers stopReason "refusal" (no
|
|
/// chunks); `loadReplay` (#28) adds the lifecycle wire: session/new/load/fork
|
|
/// all require `mcpServers` (-32602 without, the #44 invariant), session ids
|
|
/// are minted uniquely (sess-1, sess-2, …), session/load replays
|
|
/// user+thought+message chunks PLUS one submit_research_notes tool call
|
|
/// (#29 — candidates re-materialize on resume) for ANY minted sess-* id
|
|
/// then answers its id
|
|
/// (a relaunch default-open resumes the newest rostered entry, #28 review
|
|
/// fix; any other id answers with NO sessionId = unknown), and session/fork
|
|
/// of sess-1 returns a fresh F-<n> (any other source id returns ""). load/fork
|
|
/// log "load <id>" / "fork <id>" to stderr so tests can pin the wire call.
|
|
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
|
|
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
|
|
/// the finish-audit interleaving pin's in-flight observable.
|
|
/// 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.
|
|
/// Every spawn appends its argv line to `<name>-spawn-log` beside the fake
|
|
/// (#137) — the "which engine (profile) ran" observable.
|
|
/// Internal (not private) so later test files can reuse the fake (#24).
|
|
/// One contiguous zsh program — splitting the script string would break the
|
|
/// wire-line inspectability the script's own comment pins.
|
|
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")
|
|
let fixCardB64 = fixCardPayloadB64()
|
|
let researchB64 = researchPayloadB64()
|
|
// 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")
|
|
print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran
|
|
card=$(print -- '\(fixCardB64)' | base64 -d)
|
|
research=$(print -- '\(researchB64)' | base64 -d)
|
|
researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d)
|
|
framing='{"jsonrpc":"2.0","id":'
|
|
sessn=0
|
|
forkn=0
|
|
mcpcheck='import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")'
|
|
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \\n escapes of multi-line prompts
|
|
[[ -z "$line" ]] && continue
|
|
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
|
|
rid=$(print -r -- "$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
|
|
if [[ "$mode" == "loadReplay" ]]; then # #44 invariant: mcpServers required
|
|
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
|
if [[ "$ok" == "0" ]]; then
|
|
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
|
continue
|
|
fi
|
|
fi
|
|
sessn=$((sessn+1)) # #28: unique id per new — multi-session rosters need distinct ids
|
|
echo $framing"$rid",'"result":{"sessionId":"sess-'"$sessn"'"}}'
|
|
elif [[ "$method" == "session/prompt" ]]; then
|
|
print -r -- "$line" >> "${0:h}/\(name)-prompt-log" # every prompt's wire line — tests pin what the engine was asked (#122)
|
|
psid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
|
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$psid"'","update":'
|
|
if [[ "$mode" == "refuseOnPrompt" ]]; then
|
|
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
|
|
continue
|
|
fi
|
|
echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}'
|
|
echo $notify'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"weighing the structure"},"messageId":"t1"}}}'
|
|
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}'
|
|
if [[ "$mode" == "cancelOnPrompt" ]]; then
|
|
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
|
|
continue
|
|
fi
|
|
if [[ "$mode" == "noStopReason" ]]; then
|
|
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
|
|
continue
|
|
fi
|
|
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
|
|
if [[ "$mode" == "strayResearchOnPrompt" ]]; then
|
|
# #29 audit pin: a research payload carrying stray fix-card keys at
|
|
# the top level must route by shape (notes array), not vanish into
|
|
# a card row.
|
|
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_research_notes","rawInput":'"$researchstray"'}}}'
|
|
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
|
|
continue
|
|
fi
|
|
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
|
|
if [[ "$mode" == "hangOnPrompt" ]]; then
|
|
# #124: the cancel-acknowledging hold — the real engine answers its
|
|
# hanging prompt with stopReason "cancelled" the moment session/cancel
|
|
# arrives; a sleep-oblivious fake can't pin the Cancel rail. EOF with
|
|
# no cancel (teardown closed stdin) ends the turn so the child exits.
|
|
while IFS= read -r held; do
|
|
[[ -z "$held" ]] && continue
|
|
hm=$(print -r -- "$held" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
|
|
if [[ "$hm" == "session/cancel" ]]; then
|
|
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
|
|
continue 2
|
|
fi
|
|
done
|
|
fi
|
|
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
|
|
elif [[ "$method" == "session/load" ]]; then
|
|
if [[ "$mode" != loadReplay* ]]; then continue; fi
|
|
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
|
if [[ "$ok" == "0" ]]; then
|
|
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
|
continue
|
|
fi
|
|
lsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
|
print -u2 -- "load $lsid" # the wire call, visible in model.stderrTail
|
|
if [[ "$mode" == "loadReplayHold" ]]; then
|
|
# Finish-audit pin support: park the replay until `load-go` lands
|
|
# beside the fake; the pre-hold stderr line above is the observable
|
|
# that the load (and the model's replay slot) is in flight.
|
|
print -u2 -- "hold-load"
|
|
while [[ ! -f "${0:h}/load-go" ]]; do sleep 0.05; done
|
|
fi
|
|
# Any MINTED id replays: a relaunch default-open resumes the newest
|
|
# rostered session (review fix), so load answers every id session/new
|
|
# ever issued, not one planted id.
|
|
rnot='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$lsid"'","update":'
|
|
if [[ "$lsid" == sess-* ]]; then
|
|
# Full history replay, wire order, BEFORE the load response — the
|
|
# real adapter's contract (#28). The load RESPONSE carries NO
|
|
# top-level sessionId (0.21.5 live-verified, #30 dogfood): the id
|
|
# rides _meta.hermes.sessionProvenance.acpSessionId — resuming a
|
|
# minted id must ACCEPT this shape; an empty result stays the
|
|
# unknown-refusal.
|
|
echo $rnot'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"earlier ask"}}}}'
|
|
echo $rnot'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"old thinking"}}}}'
|
|
echo $rnot'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier verdict"}}}}'
|
|
echo $rnot'{"sessionUpdate":"tool_call","toolCallId":"tc2","title":"submit_research_notes","rawInput":'"$research"'}}}'
|
|
if [[ "$mode" == "loadReplayLegacy" ]]; then
|
|
# #30 audit knob: the OLDER contract - top-level sessionId, no
|
|
# provenance. resumeSession must accept BOTH shapes.
|
|
echo $framing"$rid\",'\"result\":{\"sessionId\":\"'"$lsid"'\"}}'
|
|
continue
|
|
fi
|
|
echo $framing"$rid\",'\"result\":{\"modes\":[],\"_meta\":{\"hermes\":{\"sessionProvenance\":{\"acpSessionId\":\"'\"$lsid\"'\"}}}}}'
|
|
else
|
|
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
|
|
fi
|
|
elif [[ "$method" == "session/fork" ]]; then
|
|
if [[ "$mode" != "loadReplay" ]]; then continue; fi
|
|
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
|
if [[ "$ok" == "0" ]]; then
|
|
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
|
continue
|
|
fi
|
|
fsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
|
print -u2 -- "fork $fsid"
|
|
if [[ "$fsid" == "sess-1" ]]; then
|
|
forkn=$((forkn+1))
|
|
echo $framing"$rid",'"result":{"sessionId":"F-'"$forkn"'"}}'
|
|
else
|
|
echo $framing"$rid",'"result":{"sessionId":""}}' # empty = fork refused
|
|
fi
|
|
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
|
|
}
|
|
|
|
// swiftlint:enable function_body_length
|
|
|
|
/// The fix-card payload for the fake's tool call, base64-encoded so shell
|
|
/// quoting can never break the wire JSON. The REAL submit_fix_cards
|
|
/// argument shape (snake_case, anchor as object) — pins the nested parse;
|
|
/// the flat #14-era shape was a regression the parser never matched the
|
|
/// live rail (review).
|
|
private func fixCardPayloadB64() -> String {
|
|
let card = #"{"pattern":"Blame tense","problem":"Never pivots to choice","# +
|
|
#""diagnostic_question":"What tense?","fix":"Pivot on the hinge","# +
|
|
#""anchor":{"quote":"We should stop listening.","occurrence":1}}"#
|
|
let json = #"{"piece_path":"/tmp/piece","cards":["# + card + #"]}"#
|
|
return Data(json.utf8).base64EncodedString()
|
|
}
|
|
|
|
/// The research-notes payload for the fake's replayed tool call (#29) —
|
|
/// base64 like the fix card so shell quoting can never break the wire JSON.
|
|
/// Two notes: one complete, one with quote/note absent (the "" defaults).
|
|
private func researchPayloadB64() -> String {
|
|
let json = #"{"piece_path":"/tmp/piece","notes":["# +
|
|
#"{"title":"Hinge Study","url":"https://example.org/hinge","quote":"We should stop listening.","note":"Counts the pivot tense."},"# +
|
|
#"{"title":"Second Source","url":"https://example.org/second"}]}"#
|
|
return Data(json.utf8).base64EncodedString()
|
|
}
|
|
|
|
/// The #29 routing pin's payload: a research batch that ALSO carries stray
|
|
/// fix-card keys at the top level (LLM tool calls pick up stray keys). The
|
|
/// notes-array shape must win over the pattern/problem match.
|
|
private func strayResearchPayloadB64() -> String {
|
|
let json = #"{"pattern":"stray","problem":"stray","piece_path":"/tmp/piece","notes":["# +
|
|
#"{"title":"Hinge Study","url":"https://example.org/hinge"}]}"#
|
|
return Data(json.utf8).base64EncodedString()
|
|
}
|
|
|
|
func acpTempDir(_ label: String) -> String {
|
|
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
|
|
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
|
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")
|
|
struct ACPClientTests {
|
|
@Test func `handshake returns agent version`() async throws {
|
|
let fake = makeFakeACP(at: acpTempDir("handshake"))
|
|
let client = ACPEngineClient(binaryPath: fake)
|
|
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
|
|
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")]),
|
|
]))
|
|
#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)
|
|
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
|
|
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))
|
|
}
|
|
}
|
|
|
|
@Test func `cancel is fire-and-forget`() async throws {
|
|
let fake = makeFakeACP(at: acpTempDir("cancel"), mode: "hangOnPrompt")
|
|
let client = ACPEngineClient(binaryPath: fake)
|
|
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
|
|
try client.start { _, _ in }
|
|
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
|
|
// The prompt holds — 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() // bound only — the fake answers the prompt on cancel
|
|
_ = 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)
|
|
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
|
|
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: - Turn outcome seam (#24 S3.1: sendPrompt → TurnOutcome)
|
|
|
|
// The suite hosts these model tests (not free functions like the model
|
|
// tests below) so the suite-name test filter runs them.
|
|
|
|
@MainActor
|
|
@Test func `sendPrompt returns ended end_turn and streams text`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("outcome-ended"))
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
let outcome = await model.sendPrompt("hello mentor")
|
|
#expect(outcome == .ended(stopReason: "end_turn"))
|
|
let streamed = model.rows.contains { row in
|
|
if case let .text(text) = row.content {
|
|
return text.contains("Hello mentor.")
|
|
}
|
|
return false
|
|
}
|
|
#expect(streamed)
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `labeled prompt renders the label not the wire stub`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("outcome-label"))
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
// The pass orchestrator sends a long wire stub; only the label may land.
|
|
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
|
|
var texts: [String] = []
|
|
for row in model.rows {
|
|
if case let .text(text) = row.content {
|
|
texts.append(text)
|
|
}
|
|
}
|
|
#expect(texts.contains("Pass 1 · My Post"))
|
|
#expect(!texts.contains { $0.contains("STUB-WIRE-PROMPT") })
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
let outcome = await model.sendPrompt("hello mentor")
|
|
#expect(outcome == .cancelled)
|
|
}
|
|
|
|
/// Review pin: a prompt response without stopReason is NOT a completed
|
|
/// turn — .failed, so a pass never advances on a maybe.
|
|
@MainActor
|
|
@Test func `missing stopReason maps to failed`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("outcome-nostop"), mode: "noStopReason")
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
let outcome = await model.sendPrompt("hello mentor")
|
|
#expect(outcome == .failed)
|
|
}
|
|
|
|
/// #23 dogfood regression pin: session/prompt's response arrives when the
|
|
/// TURN ends — minutes into a pass. The client's 15 s request default
|
|
/// abandoned live turns ("connection lost" while the engine kept working,
|
|
/// Stop vanished with isStreaming). sendPrompt must wait pass-length.
|
|
@Test func `prompt deadline is pass length not the request default`() {
|
|
#expect(MentorSessionModel.promptTimeout >= 600)
|
|
}
|
|
|
|
/// #23 dogfood: the writing-session filter — prose + card events stay,
|
|
/// raw session/tool rows and thinking are debug-only.
|
|
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
|
|
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
|
|
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .fixCard(
|
|
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
|
|
))))
|
|
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .thought("thinking…"))))
|
|
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
|
|
}
|
|
|
|
/// #155 (map #153): the editorial-voice classifier — the model's speaker
|
|
/// prefixes map onto the contract's three voices (agent prose / user
|
|
/// capsule / system status box); everything else is the system's mono
|
|
/// voice (refusals, pass kick-off labels, reveals).
|
|
@Test func `speaker classifier maps prefixes onto the contract voices`() {
|
|
#expect(SessionTranscriptView.speaker(of: "Mentor: The opening earns its place.") == .agent)
|
|
#expect(SessionTranscriptView.speaker(of: "Mentor: (refused the prompt)") == .agent)
|
|
#expect(SessionTranscriptView.speaker(of: "You: What would you cut first?") == .user)
|
|
#expect(SessionTranscriptView.speaker(of: "Pass 1 · The piece") == .system)
|
|
#expect(SessionTranscriptView.speaker(of: "Session refused — the mentor is mid-turn.") == .system)
|
|
#expect(SessionTranscriptView.speaker(of: "A = Pass 1 start snapshot · B = current document") == .system)
|
|
}
|
|
|
|
/// #155 audit (security): the link-open gate — interpreted markdown
|
|
/// opens http(s) only; every other scheme (file:, mailto:, custom app
|
|
/// schemes) is discarded. Engine prose echoes imported content, so a
|
|
/// lying `[label](scheme:…)` link must never reach a handler.
|
|
@Test func `linkVerdict discards non-http schemes from interpreted markdown`() throws {
|
|
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: "https://mentor.dev/critique"))) == .open)
|
|
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: "http://mentor.dev/critique"))) == .open)
|
|
// Scheme matching is case-insensitive on the wire.
|
|
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: "HTTPS://MENTOR.DEV/x"))) == .open)
|
|
for scheme in ["file:///etc/passwd", "mailto:x@y.dev", "notesapp://open", "javascript:alert(1)"] {
|
|
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: scheme))) == .discard, "\(scheme) should be discarded")
|
|
}
|
|
}
|
|
|
|
/// #155 audit: the Return split — Caps Lock must not turn Shift+Return
|
|
/// into a send (an exact `==` did).
|
|
@Test func `returnIntent masks caps lock and splits plain vs shift return`() {
|
|
#expect(SessionTranscriptView.returnIntent(for: []) == .send)
|
|
#expect(SessionTranscriptView.returnIntent(for: .shift) == .lineBreak)
|
|
#expect(SessionTranscriptView.returnIntent(for: [.shift, .capsLock]) == .lineBreak)
|
|
#expect(SessionTranscriptView.returnIntent(for: .capsLock) == .send)
|
|
#expect(SessionTranscriptView.returnIntent(for: .option) == .passthrough)
|
|
#expect(SessionTranscriptView.returnIntent(for: [.command]) == .passthrough)
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `refusal maps to ended refusal and still renders the refusal row`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("outcome-refusal"), mode: "refuseOnPrompt")
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
let outcome = await model.sendPrompt("hello mentor")
|
|
#expect(outcome == .ended(stopReason: "refusal"))
|
|
let refused = model.rows.contains { row in
|
|
if case let .text(text) = row.content {
|
|
return text.contains("(refused the prompt)")
|
|
}
|
|
return false
|
|
}
|
|
#expect(refused)
|
|
}
|
|
|
|
/// #29 audit pin: a research payload with stray fix-card keys routes by
|
|
/// SHAPE (the notes array) — it renders candidates, never a card row.
|
|
/// Title-based routing would also work on the fake but titles are
|
|
/// display text; the payload is the contract.
|
|
@MainActor
|
|
@Test func `research payload with stray card keys renders candidates not a card`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("stray-research"), mode: "strayResearchOnPrompt")
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
let outcome = await model.sendPrompt("research this")
|
|
guard case .ended = outcome else {
|
|
Issue.record("turn did not end: \(outcome)")
|
|
return
|
|
}
|
|
var hasCandidates = false
|
|
var hasCard = false
|
|
for _ in 0 ..< 250 {
|
|
hasCandidates = model.rows.contains {
|
|
if case .researchNote = $0.content {
|
|
return true
|
|
}; return false
|
|
}
|
|
hasCard = model.rows.contains {
|
|
if case .fixCard = $0.content {
|
|
return true
|
|
}; return false
|
|
}
|
|
if hasCandidates {
|
|
break
|
|
}
|
|
try? await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
#expect(hasCandidates, "the stray-key research batch never rendered as candidates")
|
|
#expect(!hasCard, "the research payload was swallowed by the fix-card parser")
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("thought-lane"))
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
// The fake streams a thought chunk BEFORE the message chunks — the
|
|
// live shape of a pass turn (long thinking, then the critique).
|
|
let outcome = await model.sendPrompt("hello mentor")
|
|
#expect(outcome == .ended(stopReason: "end_turn"))
|
|
let thought = model.rows.contains { row in
|
|
if case let .thought(text) = row.content {
|
|
return text == "weighing the structure"
|
|
}
|
|
return false
|
|
}
|
|
#expect(thought)
|
|
// The critique text stays clean — thinking never bleeds into it.
|
|
let critique = model.rows.contains { row in
|
|
if case let .text(text) = row.content {
|
|
return text == "Mentor: Hello mentor."
|
|
}
|
|
return false
|
|
}
|
|
#expect(critique)
|
|
#expect(!model.rows.contains { row in
|
|
if case let .text(text) = row.content {
|
|
return text.contains("weighing")
|
|
}
|
|
return false
|
|
})
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `transport failure mid-turn maps to TurnOutcome failed`() async throws {
|
|
let fake = makeFakeACP(at: acpTempDir("outcome-failed"), mode: "hangOnPrompt")
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
// Deterministic transport failure through the model: hangOnPrompt keeps
|
|
// the turn pending, then shutdown() closes the client — the in-flight
|
|
// session/prompt fails with a transport error, the same route a mid-turn
|
|
// engine error takes. crashAfterHandshake can't pin this: after the crash
|
|
// the phase is .crashed and sendPrompt's guard refuses before any request.
|
|
let promptTask = Task { await model.sendPrompt("hello mentor") }
|
|
for _ in 0 ..< 100 where !model.isStreaming {
|
|
try await Task.sleep(for: .milliseconds(50))
|
|
}
|
|
model.shutdown()
|
|
let outcome = await promptTask.value
|
|
#expect(outcome == .failed)
|
|
}
|
|
}
|
|
|
|
// MARK: - Model tests
|
|
|
|
@Test @MainActor func `model handshake renders version and streams fix card`() async throws {
|
|
let fake = makeFakeACP(at: acpTempDir("model"))
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
|
|
await model.openSession()
|
|
guard case .ready = model.phase else {
|
|
Issue.record("expected ready, got \(model.phase)")
|
|
return
|
|
}
|
|
#expect(model.activeEntry?.sessionId == "sess-1")
|
|
#expect(model.engineVersion == "9.9.9")
|
|
await model.sendPrompt("hello mentor")
|
|
// The card row lands via a client notification Task that can settle just
|
|
// after the response resumes this test under full-suite load — bounded
|
|
// settle (house poll pattern); the pin itself is unchanged.
|
|
var hasCard = false
|
|
for _ in 0 ..< 250 where !hasCard {
|
|
hasCard = model.rows.contains { row in
|
|
if case let .fixCard(card) = row.content {
|
|
return card.pattern == "Blame tense"
|
|
}
|
|
return false
|
|
}
|
|
if !hasCard {
|
|
try await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
}
|
|
#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)
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `model surfaces advisory version drift note`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("drift"))
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
// 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)
|
|
}
|
|
|
|
@MainActor
|
|
@Test func `build metadata does not fabricate version drift`() async {
|
|
let fake = makeFakeACP(at: acpTempDir("metadata-drift"))
|
|
let model = MentorSessionModel(binaryPath: fake)
|
|
defer { model.shutdown() }
|
|
// 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)
|
|
}
|
|
|
|
@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)
|
|
defer { model.shutdown() }
|
|
await model.openSession()
|
|
guard case .ready = model.phase else {
|
|
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
|
|
return
|
|
}
|
|
#expect(model.activeEntry?.sessionId == "sess-1")
|
|
}
|
|
|
|
@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)
|
|
defer { model.shutdown() }
|
|
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)
|
|
defer { model2.shutdown() }
|
|
await model2.openSession()
|
|
guard case .ready = model2.phase else {
|
|
Issue.record("expected ready on healthy engine, got \(model2.phase)")
|
|
return
|
|
}
|
|
}
|