feat(mentor): museion-tools MCP server (#23)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Headless --serve-mcp role in the app binary: NDJSON JSON-RPC on stdio exposing query_learnings and submit_fix_cards (ADR-0006 cards, anchor-validated; stale lands flagged, never rejected), registered into the museion profile at provisioning. Cards persist per piece under <piece>/cards/ and surface in a floating Fix Cards palette with pass-stamped provenance. Live dogfood drove the shape: session/prompt waits pass length (the 15 s request default abandoned working turns), a liveness row and a persisted Debug checkbox (off) split writing sessions from debug chatter, the verdict references findings by title only while the cards carry the detail (persona v1.3 — tools work in silence), and the #24 pass rails (pass bar, TurnOutcome seam, snapshots) ride in. Three-reviewer audit round: piece-path shape guard closes the JSON-drop and substring-oracle holes, nested submit rawInput parsing (the flat parser never matched the live rail), missing stopReason never advances a pass, 1 MB stdin cap, card scan off MainActor. 296 tests green; every behavioral fix flip-verified. Closes #23
This commit is contained in:
1 parent
c2e94fd825
commit
683ddf8426
29 files changed
+2626
-169
No files matched your search
@@ -17,25 +17,17 @@ import Testing
|
||||
|
||||
/// 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.
|
||||
/// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt;
|
||||
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled";
|
||||
/// `refuseOnPrompt` answers stopReason "refusal" (no chunks).
|
||||
/// 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 {
|
||||
/// Internal (not private) so later test files can reuse the fake (#24).
|
||||
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()
|
||||
let fixCardB64 = fixCardPayloadB64()
|
||||
// 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 = """
|
||||
@@ -45,18 +37,31 @@ private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: Stri
|
||||
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
|
||||
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=$(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")')
|
||||
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
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
|
||||
elif [[ "$method" == "session/prompt" ]]; then
|
||||
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"}}}'
|
||||
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
|
||||
if [[ "$mode" == "hangOnPrompt" ]]; then
|
||||
@@ -76,7 +81,20 @@ private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: Stri
|
||||
return path
|
||||
}
|
||||
|
||||
private func acpTempDir(_ label: String) -> String {
|
||||
/// 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()
|
||||
}
|
||||
|
||||
func acpTempDir(_ label: String) -> String {
|
||||
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
return dir
|
||||
@@ -187,6 +205,156 @@ struct ACPClientTests {
|
||||
}
|
||||
#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)
|
||||
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)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@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)
|
||||
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") })
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
|
||||
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
await model.openSession()
|
||||
let outcome = await model.sendPrompt("hello mentor")
|
||||
#expect(outcome == .cancelled)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
/// 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)
|
||||
await model.openSession()
|
||||
let outcome = await model.sendPrompt("hello mentor")
|
||||
#expect(outcome == .failed)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
/// #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(MentorPaneView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
|
||||
#expect(MentorPaneView.isWritingRow(SessionRow(content: .fixCard(
|
||||
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
|
||||
))))
|
||||
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .thought("thinking…"))))
|
||||
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
|
||||
}
|
||||
|
||||
@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)
|
||||
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)
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@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)
|
||||
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
|
||||
})
|
||||
model.shutdown()
|
||||
}
|
||||
|
||||
@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)
|
||||
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
|
||||
|
||||
@@ -18,11 +18,13 @@ 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). `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.
|
||||
- `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`, `cancelOnPrompt` — one chunk then stopReason cancelled, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). 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. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub.
|
||||
- `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. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), 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, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
|
||||
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel.
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
|
||||
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700.
|
||||
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
|
||||
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic).
|
||||
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
|
||||
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
|
||||
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//
|
||||
// MCPServerWireTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #23 (M2, slice 1): the museion-tools wire contract, in-process through
|
||||
// MCPServer.run(lines:write:) over real JSON-RPC lines — echoed
|
||||
// protocolVersion, silent notifications, typed tools/list, the full
|
||||
// submit round-trip with the card on disk, isError tool failures,
|
||||
// -32601 unknown method, -32700 garbage. Wire facts verified live
|
||||
// against the real hermes MCP client.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
/// Run lines through the server loop, parsing every reply as JSON objects.
|
||||
private func runWire(_ lines: [String]) throws -> [[String: Any]] {
|
||||
var replies: [String] = []
|
||||
MCPServer.run(lines: AnyIterator(lines.makeIterator())) { replies.append($0) }
|
||||
return try replies.compactMap {
|
||||
try JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]
|
||||
}
|
||||
}
|
||||
|
||||
/// Review pin (DoS): a line over the 1 MB frame cap answers -32600 —
|
||||
/// never reaches JSONSerialization.
|
||||
@Test func `oversized line answers line too long`() throws {
|
||||
let big = String(repeating: "a", count: 1_048_577)
|
||||
let replies = try runWire([big])
|
||||
let error = replies[0]["error"] as? [String: Any]
|
||||
#expect((error?["code"] as? Int) == -32600)
|
||||
}
|
||||
|
||||
private let initializeLine = #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#
|
||||
private let initializedLine = #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#
|
||||
private let toolsListLine = #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#
|
||||
|
||||
/// The text payload of a tools/call result.
|
||||
private func toolText(_ result: [String: Any]) throws -> String {
|
||||
let content = try #require(result["content"] as? [[String: Any]])
|
||||
return try #require(content.first?["text"] as? String)
|
||||
}
|
||||
|
||||
struct MCPServerWireTests {
|
||||
@Test func `initialize echoes client protocol version`() throws {
|
||||
let replies = try runWire([initializeLine])
|
||||
#expect(replies.count == 1)
|
||||
#expect(replies[0]["id"] as? Int == 1)
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["protocolVersion"] as? String == "2025-06-18")
|
||||
let info = try #require(result["serverInfo"] as? [String: Any])
|
||||
#expect(info["name"] as? String == "museion-tools")
|
||||
#expect(result["capabilities"] is [String: Any])
|
||||
}
|
||||
|
||||
@Test func `initialize falls back to pinned protocol version`() throws {
|
||||
let replies = try runWire([#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["protocolVersion"] as? String == "2025-11-25")
|
||||
}
|
||||
|
||||
@Test func `notifications never reply`() throws {
|
||||
#expect(try runWire([initializedLine]).isEmpty)
|
||||
}
|
||||
|
||||
@Test func `ping answers empty result`() throws {
|
||||
let replies = try runWire([#"{"jsonrpc":"2.0","id":9,"method":"ping"}"#])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result.isEmpty)
|
||||
}
|
||||
|
||||
@Test func `tools list exposes both tools with schemas`() throws {
|
||||
let replies = try runWire([toolsListLine])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
let tools = try #require(result["tools"] as? [[String: Any]])
|
||||
#expect(Set(tools.compactMap { $0["name"] as? String }) == ["query_learnings", "submit_fix_cards"])
|
||||
|
||||
let submit = try #require(tools.first { $0["name"] as? String == "submit_fix_cards" })
|
||||
let schema = try #require(submit["inputSchema"] as? [String: Any])
|
||||
let required = try #require(schema["required"] as? [String])
|
||||
#expect(required.contains("piece_path"))
|
||||
#expect(required.contains("cards"))
|
||||
let properties = try #require(schema["properties"] as? [String: Any])
|
||||
let cardsProp = try #require(properties["cards"] as? [String: Any])
|
||||
let cardItems = try #require(cardsProp["items"] as? [String: Any])
|
||||
let cardRequired = try #require(cardItems["required"] as? [String])
|
||||
#expect(cardRequired.contains("pattern"))
|
||||
#expect(cardRequired.contains("problem"))
|
||||
#expect(cardRequired.contains("anchor"))
|
||||
#expect(cardRequired.contains("lane"))
|
||||
#expect(cardRequired.contains("emitter"))
|
||||
let cardProps = try #require(cardItems["properties"] as? [String: Any])
|
||||
let anchor = try #require(cardProps["anchor"] as? [String: Any])
|
||||
let anchorProps = try #require(anchor["properties"] as? [String: Any])
|
||||
let occurrence = try #require(anchorProps["occurrence"] as? [String: Any])
|
||||
#expect(occurrence["type"] as? String == "integer")
|
||||
#expect(occurrence["default"] as? Int == 1)
|
||||
|
||||
let query = try #require(tools.first { $0["name"] as? String == "query_learnings" })
|
||||
let querySchema = try #require(query["inputSchema"] as? [String: Any])
|
||||
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
|
||||
}
|
||||
|
||||
@Test func `submit and query round trip through the wire`() throws {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("mcp-wire-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
let piece = home.appendingPathComponent("projects/posts/test-piece", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: piece, withIntermediateDirectories: true)
|
||||
try "---\ntype: post\n---\nThe repeated anchor line.\n"
|
||||
.write(to: piece.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
|
||||
try "wire learning".write(to: learnings.appendingPathComponent("l.md"), atomically: true, encoding: .utf8)
|
||||
|
||||
// swiftlint:disable line_length
|
||||
let submit = """
|
||||
{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"\(piece.path)","cards":[{"pattern":"Hedging","problem":"The hedge weakens the claim.","anchor":{"quote":"repeated anchor line"},"lane":"mechanical","emitter":"lint"}]}}}
|
||||
"""
|
||||
// swiftlint:enable line_length
|
||||
let query = """
|
||||
{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"query_learnings","arguments":{"piece_path":"\(piece.path)"}}}
|
||||
"""
|
||||
let replies = try runWire([initializeLine, initializedLine, submit, query])
|
||||
// initialize + two tool results; the notification stayed silent.
|
||||
#expect(replies.count == 3)
|
||||
|
||||
let submitResult = try #require(replies[1]["result"] as? [String: Any])
|
||||
#expect(submitResult["isError"] == nil)
|
||||
let payload = try #require(
|
||||
try JSONSerialization.jsonObject(with: Data(toolText(submitResult).utf8)) as? [String: Any],
|
||||
)
|
||||
let cards = try #require(payload["cards"] as? [[String: Any]])
|
||||
#expect(cards.first?["anchor_status"] as? String == "valid")
|
||||
let file = try #require(cards.first?["file"] as? String)
|
||||
#expect(file.hasSuffix("-hedging.json"))
|
||||
#expect(
|
||||
FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards/\(file)").path),
|
||||
)
|
||||
|
||||
let queryResult = try #require(replies[2]["result"] as? [String: Any])
|
||||
let learned = try #require(
|
||||
try JSONSerialization.jsonObject(with: Data(toolText(queryResult).utf8)) as? [String: Any],
|
||||
)
|
||||
let learningsPayload = try #require(learned["learnings"] as? [[String: Any]])
|
||||
#expect(learningsPayload.first?["markdown"] as? String == "wire learning")
|
||||
}
|
||||
|
||||
@Test func `tool failures set is error`() throws {
|
||||
let lines = [
|
||||
// Missing piece.
|
||||
// swiftlint:disable:next line_length
|
||||
#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"/nonexistent/piece","cards":[{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}]}}}"#,
|
||||
// Unknown tool name.
|
||||
#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"wat","arguments":{}}}"#,
|
||||
// Malformed arguments (piece_path missing).
|
||||
#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"query_learnings","arguments":{}}}"#,
|
||||
]
|
||||
for line in lines {
|
||||
let replies = try runWire([line])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["isError"] as? Bool == true, "expected isError for: \(line)")
|
||||
#expect(replies[0]["error"] == nil)
|
||||
let text = try toolText(result)
|
||||
#expect(!text.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `unknown method errors 32601`() throws {
|
||||
let replies = try runWire([#"{"jsonrpc":"2.0","id":6,"method":"wat/thing"}"#])
|
||||
let error = try #require(replies[0]["error"] as? [String: Any])
|
||||
#expect(error["code"] as? Int == -32601)
|
||||
#expect(replies[0]["result"] == nil)
|
||||
}
|
||||
|
||||
@Test func `garbage line errors 32700 with null id`() throws {
|
||||
let replies = try runWire(["not json at all"])
|
||||
let error = try #require(replies[0]["error"] as? [String: Any])
|
||||
#expect(error["code"] as? Int == -32700)
|
||||
#expect(replies[0]["id"] is NSNull)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//
|
||||
// MCPToolsTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #23 (M2, slice 1): the museion-tools tool layer — pure anchor
|
||||
// validation, the submit round-trip (one snake_case JSON file per card
|
||||
// under <piece>/cards/), scan ordering, and the learnings reader.
|
||||
// Temp-home convention (PostStoreTests).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
/// Throwaway Home in a temp dir (PostStoreTests convention).
|
||||
private func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("mcp-tools-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
try write(home)
|
||||
return home
|
||||
}
|
||||
|
||||
/// One piece under projects/posts/<id>/post.md; returns the piece folder.
|
||||
/// `type: nil` writes no frontmatter block at all.
|
||||
@discardableResult
|
||||
private func writePiece(
|
||||
_ home: URL,
|
||||
id: String = "test-piece",
|
||||
type: String? = "post",
|
||||
body: String = "# Title\n\nThe repeated anchor line.\nAgain the repeated anchor line.\n",
|
||||
) throws -> URL {
|
||||
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
let block = type.map { "---\ntype: \($0)\npass_state: First Draft\norigin: writer\n---\n" } ?? ""
|
||||
try (block + body).write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
return dir
|
||||
}
|
||||
|
||||
/// One wire-shaped card with test-friendly defaults. Internal — shared
|
||||
/// with PostsModelTests (review: a hand-copy drifted here).
|
||||
func card(
|
||||
pattern: String = "Hedging",
|
||||
problem: String = "The hedge weakens the claim.",
|
||||
diagnosticQuestion: String? = nil,
|
||||
quote: String = "repeated anchor line",
|
||||
occurrence: Int = 1,
|
||||
) -> FixCardStore.Input {
|
||||
FixCardStore.Input(
|
||||
pattern: pattern,
|
||||
problem: problem,
|
||||
diagnosticQuestion: diagnosticQuestion,
|
||||
fix: nil,
|
||||
anchor: .init(quote: quote, occurrence: occurrence),
|
||||
lane: .mechanical,
|
||||
emitter: .lint,
|
||||
provenance: nil,
|
||||
)
|
||||
}
|
||||
|
||||
/// A fully-stamped card for hand-written fixtures (scan tests).
|
||||
private func storedCard(pattern: String) -> FixCardStore.StoredFixCard {
|
||||
FixCardStore.StoredFixCard(
|
||||
id: UUID(),
|
||||
submittedAt: Date(timeIntervalSince1970: 0),
|
||||
pattern: pattern,
|
||||
problem: "p",
|
||||
diagnosticQuestion: "",
|
||||
fix: "",
|
||||
anchor: .init(quote: "q", occurrence: 1),
|
||||
lane: .mechanical,
|
||||
emitter: .lint,
|
||||
provenance: nil,
|
||||
status: "open",
|
||||
anchorStatus: .valid,
|
||||
)
|
||||
}
|
||||
|
||||
struct MCPToolsTests {
|
||||
@Test func `anchor validation`() {
|
||||
let text = "alpha anchor beta anchor gamma"
|
||||
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 1) == .valid)
|
||||
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 2) == .valid) // 2 of 2
|
||||
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 3) == .stale) // 3 of 2
|
||||
#expect(FixCardStore.anchorStatus(text: text, quote: "vanished", occurrence: 1) == .stale)
|
||||
#expect(FixCardStore.anchorStatus(text: text, quote: "", occurrence: 1) == .stale)
|
||||
// Non-overlapping counting: "a a" fits "a a a" only once.
|
||||
#expect(FixCardStore.anchorStatus(text: "a a a", quote: "a a", occurrence: 2) == .stale)
|
||||
}
|
||||
|
||||
@Test func `input decode defaults occurrence and rejects unknown enums`() throws {
|
||||
let minimal = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}"#
|
||||
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(minimal.utf8))
|
||||
#expect(input.anchor.occurrence == 1)
|
||||
#expect(input.diagnosticQuestion == nil)
|
||||
|
||||
let badLane = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"nope","emitter":"lint"}"#
|
||||
#expect(throws: DecodingError.self) {
|
||||
_ = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(badLane.utf8))
|
||||
}
|
||||
}
|
||||
|
||||
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
|
||||
/// wire; pre-schema cards (no pass key) decode to nil, never error.
|
||||
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
|
||||
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a","pass":2}}"#
|
||||
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(wire.utf8))
|
||||
#expect(input.provenance?.pass == 2)
|
||||
|
||||
let old = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a"}}"#
|
||||
let oldInput = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(old.utf8))
|
||||
#expect(oldInput.provenance?.pass == nil)
|
||||
}
|
||||
|
||||
@Test func `submit writes snake case card file`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
let written = try FixCardStore.submit(
|
||||
piecePath: piece.path,
|
||||
cards: [card(diagnosticQuestion: "Is the hedge load-bearing?")],
|
||||
)
|
||||
|
||||
#expect(written.count == 1)
|
||||
#expect(written[0].card.anchorStatus == .valid)
|
||||
#expect(written[0].card.status == "open")
|
||||
#expect(written[0].file.hasSuffix("-hedging.json"))
|
||||
|
||||
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
|
||||
let files = try FileManager.default.contentsOfDirectory(atPath: cardsDir.path)
|
||||
.filter { $0.hasSuffix(".json") }
|
||||
#expect(files == [written[0].file])
|
||||
|
||||
let json = try #require(
|
||||
try JSONSerialization.jsonObject(
|
||||
with: Data(contentsOf: cardsDir.appendingPathComponent(written[0].file)),
|
||||
) as? [String: Any],
|
||||
)
|
||||
#expect(json["pattern"] as? String == "Hedging")
|
||||
#expect(json["diagnostic_question"] as? String == "Is the hedge load-bearing?")
|
||||
#expect(json["anchor_status"] as? String == "valid")
|
||||
#expect(json["status"] as? String == "open")
|
||||
#expect(json["submitted_at"] is String)
|
||||
#expect(json["id"] is String)
|
||||
}
|
||||
|
||||
@Test func `submit flags stale anchors but still lands`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
// A post.md path is accepted directly, not just the piece folder.
|
||||
let written = try FixCardStore.submit(
|
||||
piecePath: piece.appendingPathComponent("post.md").path,
|
||||
cards: [card(quote: "this quote is nowhere")],
|
||||
)
|
||||
#expect(written[0].card.anchorStatus == .stale)
|
||||
#expect(
|
||||
FileManager.default.fileExists(
|
||||
atPath: piece.appendingPathComponent("cards/\(written[0].file)").path,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test func `submit throws on missing piece`() throws {
|
||||
let home = try toolsHome()
|
||||
// A lazy piece folder without post.md is not a piece.
|
||||
let noPost = home.appendingPathComponent("projects/posts/ghost", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: noPost, withIntermediateDirectories: true)
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: noPost.path, cards: [card()]) }
|
||||
#expect(throws: Error.self) {
|
||||
try FixCardStore.submit(piecePath: home.appendingPathComponent("nowhere").path, cards: [card()])
|
||||
}
|
||||
}
|
||||
|
||||
/// Security pins (review MEDIUM-1/-2): a readable foreign file must not
|
||||
/// pass as a "piece" — submit beside it = JSON-drop, anchor check =
|
||||
/// substring oracle. One resolvePostURL guard closes both.
|
||||
@Test func `submit refuses foreign files and loose post md`() throws {
|
||||
let home = try toolsHome()
|
||||
let foreign = home.appendingPathComponent("notes.md")
|
||||
try "not a piece".write(to: foreign, atomically: true, encoding: .utf8)
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: foreign.path, cards: [card()]) }
|
||||
|
||||
let loose = home.appendingPathComponent("loose", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: loose, withIntermediateDirectories: true)
|
||||
try "x".write(to: loose.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: loose.path, cards: [card()]) }
|
||||
}
|
||||
|
||||
@Test func `submit throws on malformed cards and writes nothing`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: " ")]) }
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(problem: "")]) }
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(quote: "")]) }
|
||||
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(occurrence: 0)]) }
|
||||
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards").path))
|
||||
}
|
||||
|
||||
@Test func `submit suffixes same second collisions`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card(), card()])
|
||||
#expect(written[0].file.hasSuffix("-hedging.json"))
|
||||
#expect(written[1].file.hasSuffix("-hedging-2.json"))
|
||||
#expect(written[0].file != written[1].file)
|
||||
}
|
||||
|
||||
@Test func `scan returns newest first and skips undecodable`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
let dir = piece.appendingPathComponent("cards", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try FixCardStore.encoder.encode(storedCard(pattern: "New"))
|
||||
.write(to: dir.appendingPathComponent("20260102-000000-new.json"))
|
||||
try FixCardStore.encoder.encode(storedCard(pattern: "Old"))
|
||||
.write(to: dir.appendingPathComponent("20260101-000000-old.json"))
|
||||
try "{ not json".write(to: dir.appendingPathComponent("junk.json"), atomically: true, encoding: .utf8)
|
||||
try "note".write(to: dir.appendingPathComponent("note.txt"), atomically: true, encoding: .utf8)
|
||||
|
||||
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["New", "Old"])
|
||||
// A post.md URL is tolerated (the app-side call sites hold the file URL).
|
||||
#expect(FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md")).count == 2)
|
||||
}
|
||||
|
||||
@Test func `learnings read raw markdown name sorted`() throws {
|
||||
let home = try toolsHome { home in
|
||||
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try "beta body".write(to: dir.appendingPathComponent("b.md"), atomically: true, encoding: .utf8)
|
||||
try "# Alpha\n\nraw *markdown*".write(to: dir.appendingPathComponent("a.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
let piece = try writePiece(home)
|
||||
let learned = try FixCardStore.learnings(piecePath: piece.path)
|
||||
#expect(learned.map(\.file) == ["a.md", "b.md"])
|
||||
#expect(learned[0].markdown == "# Alpha\n\nraw *markdown*")
|
||||
}
|
||||
|
||||
@Test func `learnings follow content type`() throws {
|
||||
let home = try toolsHome { home in
|
||||
let outlines = home.appendingPathComponent("learnings/outlines", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: outlines, withIntermediateDirectories: true)
|
||||
try "- outline learning".write(to: outlines.appendingPathComponent("o.md"), atomically: true, encoding: .utf8)
|
||||
let posts = home.appendingPathComponent("learnings/posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: posts, withIntermediateDirectories: true)
|
||||
try "post learning".write(to: posts.appendingPathComponent("p.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
let piece = try writePiece(home, id: "outline-piece", type: "outline")
|
||||
#expect(try FixCardStore.learnings(piecePath: piece.path).map(\.markdown) == ["- outline learning"])
|
||||
}
|
||||
|
||||
@Test func `learnings missing dir is empty and type defaults to post`() throws {
|
||||
let home = try toolsHome { home in
|
||||
let outlines = home.appendingPathComponent("learnings/outlines", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: outlines, withIntermediateDirectories: true)
|
||||
try "outline learning".write(to: outlines.appendingPathComponent("o.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
// No type key → post → looks in learnings/posts/, which doesn't exist.
|
||||
let piece = try writePiece(home, type: nil)
|
||||
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
|
||||
// A missing piece is still an error, not an empty answer.
|
||||
#expect(throws: Error.self) {
|
||||
try FixCardStore.learnings(piecePath: home.appendingPathComponent("gone").path)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//
|
||||
// PassRunTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #24 (S3.1): the pass orchestration — PostsModel.runPass over the real
|
||||
// client + fake ACP server (ACPClientTests' fake, PostsModelTests' temp-home
|
||||
// model). Pre-pass snapshot before the engine sees the text, Pass State
|
||||
// advancing only on a completed turn, order-free.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
/// Throwaway Home + model + mentor over the fake engine (makeModelHome +
|
||||
/// makeFakeACP, one rig).
|
||||
@MainActor
|
||||
// swiftlint:disable:next large_tuple
|
||||
func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessionModel) {
|
||||
let (model, home) = try makeModelHome()
|
||||
let fake = makeFakeACP(at: acpTempDir("passrun"), mode: mode)
|
||||
let mentor = MentorSessionModel(binaryPath: fake)
|
||||
return (model, home, mentor)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func textRows(of model: MentorSessionModel) -> [String] {
|
||||
model.rows.compactMap {
|
||||
if case let .text(text) = $0.content {
|
||||
text
|
||||
} else {
|
||||
nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test @MainActor func `runPass snapshots streams and advances pass state`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
await mentor.openSession()
|
||||
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
// Wait for the bind rescan to surface the piece — the pass label reads
|
||||
// the library's title for it (the PostsModelTests poll pattern).
|
||||
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
|
||||
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
|
||||
#expect(snapshot.contains("The body under pass."))
|
||||
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("pass_state: Pass-1 Done"))
|
||||
// The label renders as the user row; the wire stub never lands.
|
||||
#expect(textRows(of: mentor).contains("Pass 1 · \(post.title)"))
|
||||
#expect(!textRows(of: mentor).contains { $0.contains("Critique the piece") })
|
||||
#expect(model.runningPass == nil)
|
||||
#expect(model.lastError == nil)
|
||||
// The library regroups after the (async) rescan.
|
||||
for _ in 0 ..< 250 where model.posts.first(where: { $0.id == post.id })?.passState != .pass1Done {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(model.posts.first(where: { $0.id == post.id })?.passState == .pass1Done)
|
||||
mentor.shutdown()
|
||||
}
|
||||
|
||||
@Test @MainActor func `cancelled pass does not advance`() async throws {
|
||||
let (model, home, mentor) = try makePassRig(mode: "cancelOnPrompt")
|
||||
await mentor.openSession()
|
||||
let post = try PostStore.writeNew(body: "# Cancel Me\n\nStill first draft.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
|
||||
// Pre-pass is unconditional — the snapshot landed anyway.
|
||||
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
|
||||
#expect(snapshot.contains("Still first draft."))
|
||||
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("pass_state: First Draft"))
|
||||
#expect(model.runningPass == nil)
|
||||
mentor.shutdown()
|
||||
}
|
||||
|
||||
@Test @MainActor func `refused pass does not advance`() async throws {
|
||||
let (model, home, mentor) = try makePassRig(mode: "refuseOnPrompt")
|
||||
await mentor.openSession()
|
||||
let post = try PostStore.writeNew(body: "# Refused\n\nAlso first draft.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
let onDisk = try String(
|
||||
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
|
||||
)
|
||||
#expect(onDisk.contains("pass_state: First Draft"))
|
||||
#expect(model.runningPass == nil)
|
||||
mentor.shutdown()
|
||||
}
|
||||
|
||||
@Test @MainActor func `runPass requires an open saved post`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
await mentor.openSession()
|
||||
model.newPost() // draft staged — no folder exists
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
#expect(model.lastError?.contains("post") == true)
|
||||
// Nothing landed on disk — no passes/ anywhere under the Home.
|
||||
let paths = (FileManager.default.enumerator(atPath: home.path)?.allObjects ?? [])
|
||||
.compactMap { $0 as? String }
|
||||
#expect(!paths.contains { $0.contains("passes") })
|
||||
mentor.shutdown()
|
||||
}
|
||||
|
||||
@Test @MainActor func `dirty session flushes before the snapshot`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
await mentor.openSession()
|
||||
let post = try PostStore.writeNew(body: "# Flush First\n\nOriginal.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
model.session?.edit("# Flush First\n\nEdited on the way.") // inside the debounce window
|
||||
|
||||
await model.runPass(.pass1, home: home, mentor: mentor)
|
||||
|
||||
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
|
||||
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
|
||||
#expect(snapshot.contains("Edited on the way."))
|
||||
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
|
||||
#expect(onDisk.contains("Edited on the way."))
|
||||
mentor.shutdown()
|
||||
}
|
||||
|
||||
@Test @MainActor func `pass runs in any order from first draft`() async throws {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
await mentor.openSession()
|
||||
let post = try PostStore.writeNew(body: "# Free Order\n\nStraight to two.", home: home)
|
||||
model.select(post.id, home: home)
|
||||
|
||||
await model.runPass(.pass2, home: home, mentor: mentor)
|
||||
|
||||
let onDisk = try String(
|
||||
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
|
||||
)
|
||||
#expect(onDisk.contains("pass_state: Pass-2 Done"))
|
||||
mentor.shutdown()
|
||||
}
|
||||
@@ -557,3 +557,149 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String)
|
||||
#expect(onDisk.contains("## one"))
|
||||
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path))
|
||||
}
|
||||
|
||||
// MARK: Pass substrate (#24)
|
||||
|
||||
@Test func `snapshotPass writes the pre-pass body verbatim under passes`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Snapshot\n\nPre-pass body.", home: home)
|
||||
|
||||
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snapshot\n\nPre-pass body.", home: home)
|
||||
|
||||
let snapshot = try String(
|
||||
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
|
||||
encoding: .utf8,
|
||||
)
|
||||
#expect(snapshot == "# Snapshot\n\nPre-pass body.") // body only, no frontmatter
|
||||
}
|
||||
|
||||
@Test func `snapshotPass re-run overwrites keeping latest per pass type`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Snap\n\nBefore.", home: home)
|
||||
|
||||
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nBefore.", home: home)
|
||||
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nAfter the first pass.", home: home)
|
||||
|
||||
let snapshot = try String(
|
||||
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
|
||||
encoding: .utf8,
|
||||
)
|
||||
#expect(snapshot == "# Snap\n\nAfter the first pass.")
|
||||
}
|
||||
|
||||
@Test func `pass snapshots coexist per pass type`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Both\n\nBody.", home: home)
|
||||
let passes = home.appendingPathComponent("projects/posts/\(post.id)/passes", isDirectory: true)
|
||||
|
||||
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "before pass one", home: home)
|
||||
try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "before pass two", home: home)
|
||||
|
||||
#expect(try String(contentsOf: passes.appendingPathComponent("pass-1.md"), encoding: .utf8) == "before pass one")
|
||||
#expect(try String(contentsOf: passes.appendingPathComponent("pass-2.md"), encoding: .utf8) == "before pass two")
|
||||
}
|
||||
|
||||
@Test func `snapshotPass on vanished piece throws`() throws {
|
||||
let home = try storeHome()
|
||||
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
|
||||
try PostStore.snapshotPass(id: "ghost", kind: .pass1, body: "x", home: home)
|
||||
}
|
||||
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path))
|
||||
}
|
||||
|
||||
@Test func `advancePassState stamps Pass-1 Done preserving origin type and body`() throws {
|
||||
let home = try storeHome { home in
|
||||
let dir = home.appendingPathComponent("projects/essays/essay", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try "---\ntype: outline\npass_state: First Draft\norigin: ai\n---\n# Essay\n\nArgued body."
|
||||
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
let newState = try PostStore.advancePassState(id: "essay", kind: .pass1, home: home)
|
||||
|
||||
#expect(newState == .pass1Done)
|
||||
// Stamp round-trip: pass_state advanced, origin/type/body byte-preserved.
|
||||
#expect(try readPiece(home, root: "projects", project: "essays", "essay")
|
||||
== "---\ntype: outline\npass_state: Pass-1 Done\norigin: ai\n---\n# Essay\n\nArgued body.")
|
||||
#expect(PostStore.readBody(id: "essay", home: home) == "# Essay\n\nArgued body.")
|
||||
let scanned = try #require(Post.scan(home: home).first)
|
||||
#expect(scanned.passState == .pass1Done)
|
||||
#expect(scanned.origin == .ai)
|
||||
#expect(scanned.type == .outline)
|
||||
}
|
||||
|
||||
@Test func `advancePassState reaches Pass-2 Done straight from First Draft`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Direct\n\nBody.", home: home)
|
||||
// Passes run in any order — Pass 2 first is legal.
|
||||
#expect(try PostStore.advancePassState(id: post.id, kind: .pass2, home: home) == .pass2Done)
|
||||
#expect(Post.scan(home: home).first?.passState == .pass2Done)
|
||||
}
|
||||
|
||||
@Test func `advancePassState never regresses a higher state`() throws {
|
||||
let home = try storeHome { home in
|
||||
let dir = home.appendingPathComponent("projects/posts/done-both", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try "---\ntype: post\npass_state: Pass-2 Done\norigin: writer\n---\n# Done\n\nBody."
|
||||
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
// A Pass 1 completing on a Pass-2 Done piece keeps the higher state.
|
||||
let newState = try PostStore.advancePassState(id: "done-both", kind: .pass1, home: home)
|
||||
|
||||
#expect(newState == .pass2Done)
|
||||
#expect(Post.scan(home: home).first?.passState == .pass2Done)
|
||||
#expect(try readPost(home, "done-both").contains("pass_state: Pass-2 Done"))
|
||||
}
|
||||
|
||||
@Test func `advancePassState is idempotent on re-run`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
|
||||
_ = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
|
||||
let first = try readPost(home, post.id)
|
||||
|
||||
#expect(try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) == .pass1Done)
|
||||
#expect(try readPost(home, post.id) == first)
|
||||
}
|
||||
|
||||
@Test func `advancePassState on vanished piece throws`() throws {
|
||||
let home = try storeHome()
|
||||
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
|
||||
_ = try PostStore.advancePassState(id: "ghost", kind: .pass1, home: home)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `stub carries pass name piece path and fix-card reminder`() {
|
||||
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
|
||||
let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false)
|
||||
|
||||
#expect(stub.contains("Pass 1 — paragraph level and up."))
|
||||
#expect(stub.contains("Piece: /vault/projects/essays/essay/post.md"))
|
||||
#expect(!stub.contains("Research notes:"))
|
||||
let closing = "Critique the piece for this pass. Deliver the verdict in your reply — "
|
||||
+ "findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder."
|
||||
#expect(stub.contains(closing))
|
||||
#expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false)
|
||||
.contains("Pass 2 — sentence level and below."))
|
||||
}
|
||||
|
||||
@Test func `stub adds the research line only when research exists`() {
|
||||
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
|
||||
let research = "/vault/projects/essays/essay/research"
|
||||
#expect(PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: true)
|
||||
.contains("Research notes: \(research)"))
|
||||
#expect(!PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false).contains(research))
|
||||
}
|
||||
|
||||
@Test func `estimateTokens is stub plus body chars over four rounded up`() {
|
||||
let pieceURL = URL(fileURLWithPath: "/vault/essay/post.md")
|
||||
let body = "# Title\n\nTwo paragraphs of argued prose."
|
||||
for kind in PassKind.allCases {
|
||||
for hasResearch in [true, false] {
|
||||
let total = PassContext.stub(kind: kind, pieceURL: pieceURL, hasResearch: hasResearch).count + body.count
|
||||
let expected = total % 4 == 0 ? total / 4 : total / 4 + 1 // ceil — derived independently of the impl
|
||||
#expect(PassContext.estimateTokens(kind: kind, body: body, pieceURL: pieceURL, hasResearch: hasResearch)
|
||||
== expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,10 @@ import Foundation
|
||||
import Testing
|
||||
|
||||
/// Throwaway Home + model (EditorSessionTests convention: direct @MainActor
|
||||
/// instantiation, no app gate).
|
||||
/// instantiation, no app gate). Internal — PassRunTests builds its rig on
|
||||
/// it (review: a hand-copy drifted).
|
||||
@MainActor
|
||||
private func makeModelHome() throws -> (PostsModel, URL) {
|
||||
func makeModelHome() throws -> (PostsModel, URL) {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("postsmodel-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
@@ -468,3 +469,75 @@ private func writeMixedOutline(home: URL) throws -> Post {
|
||||
#expect(onDisk.contains("type: post"))
|
||||
#expect(onDisk.contains("A paragraph between bullets.")) // verbatim kept everything
|
||||
}
|
||||
|
||||
// #23 (M2, slice 3): the open piece's stored fix cards surface live.
|
||||
// The card Input helper is MCPToolsTests' internal card() — one shape,
|
||||
// no hand-copy (review).
|
||||
|
||||
/// refreshCards hops off MainActor (scan runs in Task.detached) — poll for
|
||||
/// the hop-back instead of asserting synchronously.
|
||||
@MainActor
|
||||
private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
|
||||
for _ in 0 ..< 250 where model.openPieceCards.count < count {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @MainActor func `opening a piece surfaces its stored fix cards`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
|
||||
let folder = try #require(PostStore.folder(of: post.id, home: home))
|
||||
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
|
||||
|
||||
model.select(post.id, home: home)
|
||||
try await waitForCards(model, 1)
|
||||
|
||||
#expect(model.openPieceCards.map(\.pattern) == ["Hedging"])
|
||||
#expect(model.openPieceCards.first?.anchorStatus == .valid)
|
||||
}
|
||||
|
||||
@Test @MainActor func `a card landing after open joins the list without reselect`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
|
||||
let folder = try #require(PostStore.folder(of: post.id, home: home))
|
||||
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
|
||||
model.select(post.id, home: home)
|
||||
try await waitForCards(model, 1)
|
||||
|
||||
// An MCP client submits another card while the piece stays open —
|
||||
// the piece-roots watcher fires on <piece>/cards/ and the rescan
|
||||
// tail refreshes (poll-loop convention).
|
||||
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Telling", quote: "The anchor sentence.")])
|
||||
|
||||
for _ in 0 ..< 250 where model.openPieceCards.count < 2 {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(model.openPieceCards.count == 2) // grew live, no reselect
|
||||
}
|
||||
|
||||
@Test @MainActor func `closing the piece clears the card list`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
|
||||
let folder = try #require(PostStore.folder(of: post.id, home: home))
|
||||
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
|
||||
model.select(post.id, home: home)
|
||||
try await waitForCards(model, 1)
|
||||
|
||||
model.newPost()
|
||||
|
||||
#expect(model.openPieceCards == []) // the nil-session rule
|
||||
}
|
||||
|
||||
@Test @MainActor func `an archived piece opened shows its cards too`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Filed\n\nThe anchor sentence.\n", home: home)
|
||||
try PostStore.archive(post, home: home)
|
||||
let folder = try #require(PostStore.folder(of: post.id, home: home))
|
||||
#expect(folder.path.contains("/archive/"))
|
||||
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
|
||||
|
||||
model.select(post.id, home: home) // opened from the Archive pane
|
||||
try await waitForCards(model, 1)
|
||||
|
||||
#expect(model.openPieceCards.count == 1)
|
||||
}
|
||||
@@ -32,10 +32,14 @@ struct ProfileProvisionerFailureTests {
|
||||
#expect(model.hasFailure)
|
||||
}
|
||||
|
||||
@Test func `provisioning never writes mcp_servers into the profile config`() {
|
||||
// #44 negative invariant: a pre-existing engine-owned config.yaml stays
|
||||
// byte-identical through a failed AND a successful pass — no museion-tools entry.
|
||||
@Test func `registration only via the mcp add cli rail never hand-written yaml`() {
|
||||
// #44 invariant, slice-2 form: museion-tools registration happens ONLY
|
||||
// through the `hermes -p museion mcp add` CLI rail — the provisioner
|
||||
// never writes mcp_servers YAML itself. A pre-existing engine-owned
|
||||
// config.yaml stays byte-identical through a failed pass, a skipped
|
||||
// (nil server) pass, AND a pass that registers via the CLI.
|
||||
let binDir = provTempDir("mcp")
|
||||
let binary = makeFakeHermes(at: binDir, mode: "ok")
|
||||
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
|
||||
let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
|
||||
let configPath = (profileDir as NSString).appendingPathComponent("config.yaml")
|
||||
@@ -50,27 +54,61 @@ struct ProfileProvisionerFailureTests {
|
||||
)
|
||||
try? FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
|
||||
try? config.write(toFile: configPath, atomically: true, encoding: .utf8)
|
||||
let binary = makeFakeHermes(at: binDir, mode: "ok")
|
||||
func configUntouched() -> Bool {
|
||||
(try? String(contentsOfFile: configPath, encoding: .utf8)) == config
|
||||
}
|
||||
|
||||
// Failed pass: registration never reached, config untouched.
|
||||
let failed = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: badPayload)
|
||||
guard case .failed = failed else {
|
||||
Issue.record("expected copy failure, got \(failed)")
|
||||
return
|
||||
}
|
||||
#expect((try? String(contentsOfFile: configPath, encoding: .utf8)) == config)
|
||||
#expect(configUntouched())
|
||||
|
||||
// The failed pass copied both real skills before hitting the missing entry
|
||||
// (partial progress is the point — retry resumes additively), so the clean
|
||||
// re-run finds them present.
|
||||
let seeded = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: goodPayload)
|
||||
#expect(seeded == .seeded(copied: 0, present: 2))
|
||||
#expect((try? String(contentsOfFile: configPath, encoding: .utf8)) == config)
|
||||
// Skipped pass: nil serverBinaryPath is the test seam — nothing
|
||||
// registers, config untouched.
|
||||
let skipped = ProfileProvisioner.perform(
|
||||
hermesBinary: binary,
|
||||
profileRoot: profileRoot,
|
||||
payloadRoot: goodPayload,
|
||||
serverBinaryPath: nil,
|
||||
)
|
||||
#expect(skipped == .seeded(copied: 0, present: 2))
|
||||
#expect(configUntouched())
|
||||
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation")))
|
||||
|
||||
// #44, fresh-profile case: a profile the fake hermes just created carries
|
||||
// no config.yaml at all — provisioning never writes one.
|
||||
let freshRoot = (provTempDir("fresh-mcp") as NSString).appendingPathComponent("profiles")
|
||||
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: freshRoot, payloadRoot: goodPayload)
|
||||
let freshConfig = ((freshRoot as NSString).appendingPathComponent("museion") as NSString).appendingPathComponent("config.yaml")
|
||||
// Registering pass: the CLI rail ran (marker + invocation recorded) and
|
||||
// still not one byte of config.yaml is written by the provisioner — the
|
||||
// entry lands through the CLI, or not at all.
|
||||
let registered = ProfileProvisioner.perform(
|
||||
hermesBinary: binary,
|
||||
profileRoot: profileRoot,
|
||||
payloadRoot: goodPayload,
|
||||
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
|
||||
)
|
||||
#expect(registered == .seeded(copied: 0, present: 2))
|
||||
#expect(configUntouched())
|
||||
#expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered")))
|
||||
let invocation = (try? String(
|
||||
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation"),
|
||||
encoding: .utf8,
|
||||
)) ?? ""
|
||||
#expect(invocation.contains("mcp add museion-tools"))
|
||||
|
||||
// #44, fresh-profile case (own binary dir so the add truly runs): a
|
||||
// registering pass still writes no config.yaml — the CLI owns that
|
||||
// file, not us.
|
||||
let freshBinDir = provTempDir("fresh-mcp")
|
||||
let freshRoot = (freshBinDir as NSString).appendingPathComponent("profiles")
|
||||
_ = ProfileProvisioner.perform(
|
||||
hermesBinary: makeFakeHermes(at: freshBinDir, mode: "ok"),
|
||||
profileRoot: freshRoot,
|
||||
payloadRoot: goodPayload,
|
||||
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
|
||||
)
|
||||
let freshConfig = ((freshRoot as NSString).appendingPathComponent("museion") as NSString)
|
||||
.appendingPathComponent("config.yaml")
|
||||
#expect(!FileManager.default.fileExists(atPath: freshConfig))
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,14 @@ struct SeedSkill {
|
||||
/// - ok: creates the dir, exit 0. exists: creates the dir, "already exists" on
|
||||
/// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1.
|
||||
/// stderr-only: error on stderr with empty stdout (#48 fallback).
|
||||
///
|
||||
/// Also speaks `mcp` behind the `-p museion` global flag (#23): `mcp list`
|
||||
/// prints "museion-tools" iff `<binaryDir>/mcp-registered` exists, else
|
||||
/// "No MCP servers configured."; `mcp add` verifies its argv, reads ONE "y"
|
||||
/// line from stdin (mismatch/EOF → "Cancelled.", exit 1 — nothing saved),
|
||||
/// records the exact invocation in `<binaryDir>/mcp-add-invocation`, drops the
|
||||
/// marker, prints "Saved 'museion-tools' to …" (verified wire strings).
|
||||
/// `<binaryDir>/mcp-add-fails` forces "Error: mcp add exploded", exit 1.
|
||||
func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
|
||||
let path = (dir as NSString).appendingPathComponent(name)
|
||||
let createBlock = switch mode {
|
||||
@@ -57,6 +65,35 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
|
||||
NAME="$3"
|
||||
\(createBlock)
|
||||
fi
|
||||
if [[ "$1" == "-p" && "$2" == "museion" && "$3" == "mcp" ]]; then
|
||||
if [[ "$4" == "list" ]]; then
|
||||
if [[ -f "${0:h}/mcp-registered" ]]; then
|
||||
print "museion-tools enabled"
|
||||
exit 0
|
||||
fi
|
||||
print "No MCP servers configured."
|
||||
exit 0
|
||||
fi
|
||||
if [[ "$4" == "add" ]]; then
|
||||
if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then
|
||||
print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9"
|
||||
exit 1
|
||||
fi
|
||||
if [[ -f "${0:h}/mcp-add-fails" ]]; then
|
||||
print "Error: mcp add exploded"
|
||||
exit 1
|
||||
fi
|
||||
read -r ANSWER
|
||||
if [[ "$ANSWER" != "y" ]]; then
|
||||
print "Cancelled."
|
||||
exit 1
|
||||
fi
|
||||
print -r -- "$*" > "${0:h}/mcp-add-invocation"
|
||||
touch "${0:h}/mcp-registered"
|
||||
print "Saved 'museion-tools' to ${0:h}/profiles/museion/config.yaml"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
exit 97
|
||||
"""
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
@@ -277,6 +314,58 @@ struct ProfileProvisionerTests {
|
||||
#expect(!FileManager.default.fileExists(atPath: orphan))
|
||||
}
|
||||
|
||||
@Test func `fresh pass registers museion-tools via the cli with the exact command line`() {
|
||||
let binDir = provTempDir("mcp-add")
|
||||
let serverPath = (provTempDir("server") as NSString).appendingPathComponent("Museion")
|
||||
let outcome = ProfileProvisioner.perform(
|
||||
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
|
||||
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
|
||||
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
|
||||
serverBinaryPath: serverPath,
|
||||
)
|
||||
#expect(outcome == .seeded(copied: 2, present: 0))
|
||||
let invocation = ((try? String(
|
||||
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation"),
|
||||
encoding: .utf8,
|
||||
)) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
#expect(invocation == "-p museion mcp add museion-tools --command \(serverPath) --args --serve-mcp")
|
||||
}
|
||||
|
||||
@Test func `already-registered profile skips the add`() {
|
||||
let binDir = provTempDir("mcp-skip")
|
||||
// Pre-existing registration → `mcp list` reports it → no add: a re-add
|
||||
// would prompt "Overwrite? [y/N]" — the skip avoids that branch.
|
||||
try? "".write(
|
||||
toFile: (binDir as NSString).appendingPathComponent("mcp-registered"),
|
||||
atomically: true,
|
||||
encoding: .utf8,
|
||||
)
|
||||
let outcome = ProfileProvisioner.perform(
|
||||
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
|
||||
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
|
||||
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
|
||||
serverBinaryPath: "/fake/Museon",
|
||||
)
|
||||
#expect(outcome == .seeded(copied: 2, present: 0))
|
||||
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation")))
|
||||
}
|
||||
|
||||
@Test func `rejected add fails the register phase with the cli excerpt`() {
|
||||
let binDir = provTempDir("mcp-reject")
|
||||
try? "".write(
|
||||
toFile: (binDir as NSString).appendingPathComponent("mcp-add-fails"),
|
||||
atomically: true,
|
||||
encoding: .utf8,
|
||||
)
|
||||
let outcome = ProfileProvisioner.perform(
|
||||
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
|
||||
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
|
||||
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
|
||||
serverBinaryPath: "/fake/Museion",
|
||||
)
|
||||
#expect(outcome == .failed(phase: .register, excerpt: "Error: mcp add exploded"))
|
||||
}
|
||||
|
||||
@Test func `bundled manifest matches bundled payload`() {
|
||||
// url(forResource:) doesn't resolve folder references — use the same path
|
||||
// the provisioner itself builds.
|
||||
|
||||
Reference in new issue
Block a user