Files
museion/MuseionTests/ProfileProvisionerTests.swift
T
AlexKucera 5ad605eb3c feat(settings): profiles write path + Test Connection (#136)
Profiles S3 over the S2 shell: every Settings change now persists.

Model/effort writes ride the engine's own CLI — `hermes -p <profile>
config set/unset` for model.provider / model.default /
model.reasoning_effort / model.base_url (zai endpoint family written
LAST: setting model.provider clears a stale base_url, live-probed;
unset-when-absent is idempotent success). Provider keys upsert
VAR=value into ALL THREE profiles' .env — a key entered before any
surface is on its provider still persists and pre-lands for any later
switch (maintainer ruling 2026-10-28; no switch re-fire). 0600,
foreign lines preserved byte-for-byte, line-broken values refused at
the shared sink (env-file injection guard), NSLock serializes the
read-upsert-write across concurrent provider writes.

Hydration reads model blocks and keys back at pane open — a restart
neither blanks the key fields nor refuses Test Connection; an edit
made mid-read owns the truth (no stomp), and a custom z.ai base_url
seeds the endpoint field instead of being clobbered to a family
default. Per-target writes coalesce AND chain past the debounce
guard: cancellation can't stop a past-the-guard CLI write, so the
newer write queues — the last edit is always the last write to land
(finish-audit race fix, pinned).

Test Connection = two-step probe (GET /models, then a minimal
streaming chat) with honest decode per the factsheet: zai 1113 →
wrong key type, 401s → auth failed (Anthropic request_id),
finish=length → starved, empty 200 → request failed, errors riding a
2xx decoded as the provider error.

Live-probed wire corrections (dogfood, 2026-10-28): Content-Type
application/json on every request — URLSession defaults to
form-urlencoded and providers diverge (zai 200+envelope, OpenAI 400,
Anthropic tolerates); OpenAI speaks the Responses API (/responses,
input + max_output_tokens, flagship gpt-6.1-sol); probe token cap 512
(64 starved reasoning models into "no content"); OpenAI's
"error": null event snapshots don't decode as failures.

Finish-audit (ponytail + security + general reviewers): write-ordering
race + .env lost update + hydrate stomp + custom-endpoint clobber
fixed and pinned (one-shot hold / latched read knobs in the test
double); ~30 lines of dead flexibility cut (keyType protocol param,
works(reply:) payload, unused timeout knob, double JSON round trips).

Suite 468/468 xcresult-verified; swiftlint clean; factsheet §6
correction logged. Closes #136
2026-10-27 18:32:30 +01:00

458 lines
19 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// ProfileProvisionerTests.swift
// MuseionTests
//
// Exercises the real Process path with a fake hermes binary and injected
// profile/payload/master dirs (#47, #134) — same pattern as EngineGateTests.
//
// Convention: the fake creates profiles at `<binaryDir>/profiles/<name>`
// (derived from its own path — race-free under parallel tests), so each test
// passes `profileRoot = binaryDir + "/profiles"`.
//
import Foundation
@testable import Museion
import Testing
/// One payload skill: dir name, frontmatter version, and body text.
struct SeedSkill {
let name: String
let version: String
let body: String
}
/// Fake `hermes`: `profile create <name>` behaves per `mode` (#43 semantics).
/// - 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` and `config set` behind the `-p <profile>` global flag
/// (#23, #134): `mcp list` prints "museion-tools" iff
/// `<binaryDir>/mcp-registered-<profile>` 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-<profile>`, drops the
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
/// strings). `config set <key> <value> [--force]` appends the exact argv to
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …"
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` force the matching
/// failure. Every `profile create` name appends to
/// `<binaryDir>/profile-create-log`.
/// #136: `config set` also records KEY=VALUE into
/// `<binaryDir>/config-store-<profile>` (dedup per key), and the fake speaks
/// `config get <key>` (store value, or the not-set line on stderr exit 1)
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line,
/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins.
// #136: the config rail (set/get/unset over the config-store map) — its
// own literal so makeFakeHermes stays under its function-body ceiling.
private func fakeHermesConfigCLI() -> String {
"""
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then
PROFILE="$2"
if [[ -f "${0:h}/config-set-fails" ]]; then
print "Error: config set exploded"
exit 1
fi
STORE="${0:h}/config-store-$PROFILE"
touch "$STORE"
grep -v "^$5=" "$STORE" > "$STORE.tmp" && mv "$STORE.tmp" "$STORE"
print -r -- "$5=$6" >> "$STORE"
print -r -- "$*" >> "${0:h}/config-set-$PROFILE"
print "✓ Set $5 = $6 in ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "get" ]]; then
PROFILE="$2"; KEY="$5"
STORE="${0:h}/config-store-$PROFILE"
if [[ -f "$STORE" ]]; then
VAL="$(grep -m1 "^${KEY}=" "$STORE" | cut -d= -f2-)"
if [[ -n "$VAL" ]]; then
print -r -- "$VAL"
exit 0
fi
fi
print "Config key not set: $KEY" >&2
exit 1
fi
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "unset" ]]; then
PROFILE="$2"; KEY="$5"
print -r -- "$*" >> "${0:h}/config-unset-$PROFILE"
STORE="${0:h}/config-store-$PROFILE"
if [[ -f "$STORE" && -n "$(grep -m1 "^${KEY}=" "$STORE")" ]]; then
grep -v "^${KEY}=" "$STORE" > "$STORE.tmp" && mv "$STORE.tmp" "$STORE"
print "✓ Unset $KEY from ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
print "Config key not set: $KEY" >&2
exit 1
fi
"""
}
func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
let path = (dir as NSString).appendingPathComponent(name)
let createBlock = switch mode {
case "ok":
"""
mkdir -p "${0:h}/profiles/$NAME"
print "Profile '$NAME' created at ${0:h}/profiles/$NAME"
exit 0
"""
case "exists":
"""
mkdir -p "${0:h}/profiles/$NAME"
print "Error: Profile '$NAME' already exists at ${0:h}/profiles/$NAME"
exit 1
"""
case "stderr-only":
"""
print "Error: stderr-only boom" >&2
exit 1
"""
default: // fail
"""
print "Error: create exploded"
exit 1
"""
}
// #136: the config rail lives in fakeHermesConfigCLI().
let script = """
#!/bin/zsh
if [[ "$1" == "profile" && "$2" == "create" ]]; then
NAME="$3"
print -r -- "$NAME" >> "${0:h}/profile-create-log"
\(createBlock)
fi
if [[ "$1" == "-p" && "$3" == "mcp" ]]; then
PROFILE="$2"
if [[ "$4" == "list" ]]; then
if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; 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-$PROFILE"
touch "${0:h}/mcp-registered-$PROFILE"
print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
fi
\(fakeHermesConfigCLI())
exit 97
"""
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
}
/// Builds a payload dir shaped like the bundled one: seed-manifest.txt + skill dirs.
func makePayload(at dir: String, skills: [SeedSkill]) -> String {
let fileManager = FileManager.default
try? fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true)
let manifest = skills.map(\.name).joined(separator: "\n") + "\n"
try? manifest.write(toFile: (dir as NSString).appendingPathComponent("seed-manifest.txt"), atomically: true, encoding: .utf8)
for skill in skills {
let skillDir = (dir as NSString).appendingPathComponent(skill.name)
try? fileManager.createDirectory(atPath: skillDir, withIntermediateDirectories: true)
let skillMarkdown = """
---
name: \(skill.name)
license: GNU GPLv3
metadata:
author: Test
version: "\(skill.version)"
---
# \(skill.name)
\(skill.body)
"""
try? skillMarkdown.write(
toFile: (skillDir as NSString).appendingPathComponent("SKILL.md"),
atomically: true,
encoding: .utf8,
)
}
// Non-skill extras that must never seed (the repo's AGENTS.md, the manifest).
try? "doc".write(toFile: (dir as NSString).appendingPathComponent("AGENTS.md"), atomically: true, encoding: .utf8)
return dir
}
/// Shared provisioning-test temp dir (distinct name from EngineGateTests' own).
func provTempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-prov-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir
}
func skillPath(_ profileRoot: String, _ profile: String, _ name: String) -> String {
((profileRoot as NSString).appendingPathComponent("\(profile)/skills") as NSString).appendingPathComponent(name)
}
func readSkillBody(_ path: String) -> String {
(try? String(contentsOfFile: (path as NSString).appendingPathComponent("SKILL.md"), encoding: .utf8)) ?? ""
}
/// Shared payload fixtures: both provisioning suites seed these two skills.
let defaultSkills = [
SeedSkill(name: "serif-writing", version: "1.3", body: "method body"),
SeedSkill(name: "deslop", version: "1.1", body: "tell catalog"),
]
@Suite("ProfileProvisionerTests")
struct ProfileProvisionerTests {
private let skills = defaultSkills
@Test func `fresh pass creates profile and copies every manifest skill`() {
let binDir = provTempDir("fresh")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: master,
)
// #134: 2 master copies + one symlink per skill per profile (×3).
#expect(outcome == .seeded(copied: 8, present: 0))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "museion", "serif-writing")))
#expect(readSkillBody(skillPath(profileRoot, "museion-pass1", "deslop")).contains("tell catalog"))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "museion-pass2", "serif-writing")))
}
@Test func `already-exists exit 1 is success and profile is left intact`() {
let binDir = provTempDir("exists")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "exists")
let master = provTempDir("master")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
// Writer-modified skill in place — the next pass must never overwrite
// it (G3a: through a linked skill the edit lands in the shared
// master, which seeding never touches).
try? "mentor's own edits".write(
toFile: (skillPath(profileRoot, "museion", "serif-writing") as NSString).appendingPathComponent("SKILL.md"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
// Master 2 present; museion 2 links; pass profiles 2 links each —
// nothing new, nothing overwritten.
#expect(outcome == .seeded(copied: 0, present: 8))
#expect(readSkillBody(skillPath(profileRoot, "museion", "serif-writing")) == "mentor's own edits")
}
@Test func `later app version adds new skill without touching old ones`() {
let binDir = provTempDir("upgrade")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let master = provTempDir("master")
let payloadV1 = makePayload(at: provTempDir("p1"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV1, masterRoot: master)
let payloadV2 = makePayload(
at: provTempDir("p2"),
skills: skills + [SeedSkill(name: "rhetoric", version: "1.0", body: "persuasion")],
)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV2, masterRoot: master)
// rhetoric joins the master (1 copy) and every profile's links (3).
#expect(outcome == .seeded(copied: 4, present: 8))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "museion", "rhetoric")))
}
@Test func `create failure reports phase-named excerpt`() {
let binDir = provTempDir("createfail")
let binary = makeFakeHermes(at: binDir, mode: "fail")
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
)
// Chat provisions first (#134 loop order) — its create failed.
#expect(outcome == .failed(profile: "museion", phase: .create, excerpt: "Error: create exploded"))
}
@Test func `create failure with empty stdout falls back to stderr`() {
// #48: excerpt prefers stdout (#43), stderr is the fallback.
let binDir = provTempDir("stderr")
let binary = makeFakeHermes(at: binDir, mode: "stderr-only")
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
)
#expect(outcome == .failed(profile: "museion", phase: .create, excerpt: "Error: stderr-only boom"))
}
@Test func `manifest entry missing from payload is a copy failure`() {
let binDir = provTempDir("missing")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
// Manifest names a dir the payload doesn't carry.
try? "serif-writing\ndeslop\nrhetoric\n".write(
toFile: (payload as NSString).appendingPathComponent("seed-manifest.txt"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
// Master-level failure — before any profile, so no profile named.
guard case let .failed(profile, phase, excerpt) = outcome else {
Issue.record("expected copy failure, got \(outcome)")
return
}
#expect(profile == nil)
#expect(phase == .copy)
#expect(excerpt.contains("rhetoric"))
}
@Test func `path-traversal manifest entry is rejected`() {
// LOW-1: a `/`-leading or `..` entry would escape skillsDir via
// appendingPathComponent — must fail the copy phase, not write outside.
let binDir = provTempDir("traversal")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
for bad in ["../escape", "/tmp/evil", ".", ".."] {
try? "serif-writing\n\(bad)\n".write(
toFile: (payload as NSString).appendingPathComponent("seed-manifest.txt"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
guard case let .failed(profile, phase, excerpt) = outcome else {
Issue.record("'\(bad)' must fail the pass, got \(outcome)")
continue
}
#expect(profile == nil)
#expect(phase == .copy)
#expect(excerpt.contains(bad))
}
}
@Test func `missing manifest is a copy failure`() {
let binDir = provTempDir("nomanifest")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let payload = provTempDir("empty-payload")
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
#expect(outcome == .failed(profile: nil, phase: .copy, excerpt: "seed-manifest.txt missing from payload"))
}
@Test func `non-manifest payload files never seed`() {
let binDir = provTempDir("extras")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let master = provTempDir("master")
_ = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: master,
)
let seededRoot = (profileRoot as NSString).appendingPathComponent("museion/skills")
let seeded = (try? FileManager.default.contentsOfDirectory(atPath: seededRoot)) ?? []
#expect(Set(seeded) == Set(["serif-writing", "deslop"]))
let masterEntries = (try? FileManager.default.contentsOfDirectory(atPath: master)) ?? []
#expect(Set(masterEntries) == Set(["serif-writing", "deslop"]))
}
@Test func `orphaned temp dirs from an interrupted copy are swept`() {
let binDir = provTempDir("orphan")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let master = provTempDir("master")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
// Simulate an interrupted pass: the temp dir landed, the rename never ran.
let skillsDir = (profileRoot as NSString).appendingPathComponent("museion/skills")
let orphan = (skillsDir as NSString).appendingPathComponent(".serif-writing-DEADBEEF")
try? FileManager.default.createDirectory(atPath: orphan, withIntermediateDirectories: true)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
#expect(outcome == .seeded(copied: 0, present: 8))
#expect(!FileManager.default.fileExists(atPath: orphan))
}
@Test func `bundled manifest matches bundled payload`() {
// url(forResource:) doesn't resolve folder references — use the same path
// the provisioner itself builds.
let payload = ProfileProvisioner.defaultPayloadRoot()
guard FileManager.default.fileExists(atPath: payload) else {
Issue.record("bundled writing-skills payload missing from app resources")
return
}
let manifest = (try? String(contentsOfFile: (payload as NSString).appendingPathComponent("seed-manifest.txt"), encoding: .utf8)) ?? ""
let listed = Set(manifest.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty && !$0.hasPrefix("#") })
let dirEntries = Set(
(try? FileManager.default.contentsOfDirectory(atPath: payload))?
.filter { ($0 as NSString).pathExtension.isEmpty } ?? [],
)
// Every entry exists in the payload…
for name in listed where !dirEntries.contains(name) {
Issue.record("manifest entry '\(name)' missing from payload")
}
// …every mentor skill dir is listed — the authoring tools are never seeded.
let authoringTools: Set = ["ste-writing", "writing-for-agents"]
let mentorDirs = dirEntries.filter { !$0.hasSuffix(".md") && !$0.hasPrefix(".") && !authoringTools.contains($0) }
for entry in mentorDirs where !listed.contains(entry) {
Issue.record("payload dir '\(entry)' missing from manifest")
}
#expect(!listed.contains("ste-writing"))
#expect(!listed.contains("writing-for-agents"))
}
@MainActor
@Test func `model runPass records failure and clears on later success`() async {
let binDir = provTempDir("model")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
let model = ProvisioningModel()
await model.runPass(
hermesBinary: makeFakeHermes(at: binDir, name: "hermes-fail", mode: "fail"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
#expect(model.lastFailure != nil)
await model.runPass(
hermesBinary: makeFakeHermes(at: binDir, name: "hermes-ok", mode: "ok"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
#expect(model.lastFailure == nil)
}
}