Files
museion/MuseionTests/ProfileProvisionerTests.swift
T
AlexKuceraandCipher c0b2cb0b93
CI / ci (push) Canceled after 0s
feat(provisioning): add S2.1 pass with failure alert & retry (fixes #47, #48)
Idempotent per-gate pass: create the museion Hermes profile only when
missing (exit-1 "already exists" = success), then additively seed the
bundled writing skills from seed-manifest.txt — temp-copy+rename, present
skills never touched, orphaned temps swept, manifest entries validated
kebab-case at the trust boundary.

Failures surface a separate phase-named alert ("couldn't set up the
writing profile" / "couldn't copy the writing skills"), never re-raising
the gate: excerpt behind Technical details (stdout per #43, stderr
fallback), Retry re-runs the whole pass, Not Now defers to the next
launch's silent retry. The card presents only after the gate sheet's
dismissal completes and snapshots its failure so a successful Retry
doesn't blank it mid-animation.

Provisioning writes nothing to the profile config (no mcp_servers entry,
#44) and leaves state.json engine-gate-only. 30/30 tests green.

Co-Authored-By: Cipher <cipher@babylondreams.de>
2026-09-05 15:03:01 +02:00

329 lines
13 KiB
Swift

//
// ProfileProvisionerTests.swift
// MuseionTests
//
// Exercises the real Process path with a fake hermes binary and injected
// profile/payload dirs (#47) — same pattern as EngineGateTests.
//
// Convention: the fake creates the profile 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).
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"
\(createBlock)
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, _ name: String) -> String {
((profileRoot as NSString).appendingPathComponent("museion/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 outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
)
#expect(outcome == .seeded(copied: 2, present: 0))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "serif-writing")))
#expect(readSkillBody(skillPath(profileRoot, "deslop")).contains("tell catalog"))
}
@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 payload = makePayload(at: provTempDir("payload"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
// Writer-modified skill in place — second pass must never overwrite it.
try? "mentor's own edits".write(
toFile: (skillPath(profileRoot, "serif-writing") as NSString).appendingPathComponent("SKILL.md"),
atomically: true, encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
#expect(outcome == .seeded(copied: 0, present: 2))
#expect(readSkillBody(skillPath(profileRoot, "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 payloadV1 = makePayload(at: provTempDir("p1"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV1)
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)
#expect(outcome == .seeded(copied: 1, present: 2))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "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),
)
#expect(outcome == .failed(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),
)
#expect(outcome == .failed(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,
)
guard case let .failed(phase, excerpt) = outcome else {
Issue.record("expected copy failure, got \(outcome)")
return
}
#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,
)
guard case let .failed(phase, excerpt) = outcome else {
Issue.record("'\(bad)' must fail the pass, got \(outcome)")
continue
}
#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,
)
#expect(outcome == .failed(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")
_ = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
)
let seededRoot = (profileRoot as NSString).appendingPathComponent("museion/skills")
let seeded = (try? FileManager.default.contentsOfDirectory(atPath: seededRoot)) ?? []
#expect(Set(seeded) == 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 payload = makePayload(at: provTempDir("payload"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
// 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)
#expect(outcome == .seeded(copied: 0, present: 2))
#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,
)
#expect(model.lastFailure != nil)
await model.runPass(
hermesBinary: makeFakeHermes(at: binDir, name: "hermes-ok", mode: "ok"),
profileRoot: profileRoot,
payloadRoot: payload,
)
#expect(model.lastFailure == nil)
}
}