Files
museion/MuseionTests/ProfileProvisionerTests.swift
T
AlexKucera 610f8789bd
CI / ci (push) Canceled after 0s
feat(profiles): registry + provisioning ×3
Profiles S1 (#134, ADR-0014): one gate pass provisions all three
surface profiles — museion adopted in place (never reconfigured; its
glm-5.3-max stays the user's), museion-pass1/-pass2 created fresh with
the #132 sonnet defaults + 24k budget via the hermes 'config set' CLI
rail, marker-gated so a re-pass is a no-op and Settings changes
survive; a failed provision names the profile on the #48 card.

Skills move to ONE master copy under Application Support, symlinked
per profile per the #133 allocation (P1 9 · P2 8 · Chat 10); copy-era
dirs migrate on byte-match (.DS_Store-tolerant, symlink-refusing),
diverged dirs stay copies, user skills untouched (G3a). Backup widens
to one three-subdir stamp, any-live-skip-all; RESTORE.md names the
three folders.

Two review rounds (standards+spec, then finish-audit ponytail/
security/general) caught and fixed: the dead .DS_Store leniency in
treesByteMatch, exit-code-only config-set trust, the swallowed marker
write (defaults-stomp re-arm), symlink-following in the untrusted
tree, and a fixture-skewed count pin. Suite: 412 passed / 414 (fork
flake green in isolation 16/16; UI launch = pre-existing testmanagerd
flake, failed identically pre-change). DOX: Museion/AGENTS.md,
MuseionTests/AGENTS.md, ref/writing skills/AGENTS.md rewritten.

Closes #134
2026-10-27 09:23:56 +01:00

414 lines
17 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`.
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
"""
}
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
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
print -r -- "$*" >> "${0:h}/config-set-$PROFILE"
print "✓ Set $5 = $6 in ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
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)
}
}