feat(provisioning): add S2.1 pass with failure alert & retry (fixes #47, #48)
CI / ci (push) Canceled after 0s

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>
This commit is contained in:
AlexKuceraandCipher committed 2026-09-05 15:03:01 +02:00
1 parent 67cf3d42e4
commit c0b2cb0b93
19 files changed
+912 -9

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ 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.
- `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`.
## Verification
+3 -1
View File
@@ -115,7 +115,9 @@ struct EngineGateTests {
let result = EngineProbe.perform(
probePaths: [hung, good],
shellFallback: false,
timeout: 1,
// ponytail: 3 s, not 1 — a zsh fake's startup can exceed 1 s under
// parallel-suite load and the good candidate would be killed too.
timeout: 3,
appSupportDir: tempDir("state"),
)
#expect(result == .pass(version: "9.9.9", binaryPath: good))
@@ -0,0 +1,121 @@
//
// ProfileProvisionerFailureTests.swift
// MuseionTests
//
// #48 failure path: alert state (defer/retry), config.yaml and state.json
// invariants, error excerpt surfacing. Shares the fake-binary harness with
// ProfileProvisionerTests.swift.
//
import Foundation
@testable import Museion
import Testing
@Suite("ProfileProvisionerFailureTests")
struct ProfileProvisionerFailureTests {
private let skills = defaultSkills
@MainActor
@Test func `not-now defers and a later pass can fail again`() async {
let binDir = provTempDir("defer")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
let failing = makeFakeHermes(at: binDir, name: "hermes-fail", mode: "fail")
let model = ProvisioningModel()
await model.runPass(hermesBinary: failing, profileRoot: profileRoot, payloadRoot: payload)
#expect(model.hasFailure)
model.deferFailure() // Not Now (#48)
#expect(!model.hasFailure)
#expect(model.lastFailure == nil)
// Next launch's silent retry fails again — the card may show again.
await model.runPass(hermesBinary: failing, profileRoot: profileRoot, payloadRoot: payload)
#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.
let binDir = provTempDir("mcp")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
let configPath = (profileDir as NSString).appendingPathComponent("config.yaml")
let config = "model: glm-5.3\nmcp_servers:\n weather: {}\n"
let goodPayload = makePayload(at: provTempDir("payload"), skills: skills)
// Payload whose manifest names a skill it doesn't carry → copy failure (#48 AC).
let badPayload = makePayload(at: provTempDir("bad-payload"), skills: skills)
try? "serif-writing\ndeslop\nabsent-skill\n".write(
toFile: (badPayload as NSString).appendingPathComponent("seed-manifest.txt"),
atomically: true,
encoding: .utf8,
)
try? FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
try? config.write(toFile: configPath, atomically: true, encoding: .utf8)
let binary = makeFakeHermes(at: binDir, mode: "ok")
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)
// 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)
// #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")
#expect(!FileManager.default.fileExists(atPath: freshConfig))
}
@Test func `provisioning failure leaves state json engine-gate-only`() {
let appSupport = provTempDir("state")
EngineProbe.writeState(.pass(version: "9.9", binaryPath: "/fake/hermes"), appSupportDir: appSupport)
let binDir = provTempDir("statefail")
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "fail"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
)
guard case .failed = outcome else {
Issue.record("expected create failure, got \(outcome)")
return
}
// state.json stays schemaVersion 1, engine-gate-only (#48 AC).
let record = EngineProbe.readStateRecord(appSupportDir: appSupport)
#expect(record?.schemaVersion == 1)
#expect(record?.status == "pass")
#expect(record?.engineVersion == "9.9")
}
@Test func `copy failure surfaces the file-manager error`() {
let binDir = provTempDir("catch")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
try? FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
// `skills` pre-exists as a FILE → directory creation throws → the copy
// catch branch (the only copy-error path no other test reaches).
try? "blocker".write(
toFile: (profileDir as NSString).appendingPathComponent("skills"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
)
guard case let .failed(phase, excerpt) = outcome else {
Issue.record("expected copy failure, got \(outcome)")
return
}
#expect(phase == .copy)
#expect(excerpt.hasPrefix("copy serif-writing:"))
}
}
+328
View File
@@ -0,0 +1,328 @@
//
// 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)
}
}