Files
museion/Museion/ProfileProvisioner.swift
AlexKucera d7fd11cf0d
CI / ci (push) Canceled after 0s
chore(lint): repo-wide green becomes the contract
Close the lint arc #194-#197: deliberate-style rule disables with
rationales (#194), filter-safe test renames + --test-case-name-format
preserve (#195), every surviving warning fixed through the sanctioned
lint-stable shapes (#196), and the docs now state the true contract
(#197): bare swiftlint . reports zero violations and swiftformat .
reformats nothing, while push gates stay scoped to the push's own
files (settled #190 design) — the pre-push hook's stale 'pre-existing
violations' rationale blocks refreshed, gate logic untouched.

Also in the sweep: quiesce the FSEvent-burst watcher race in
LibrarySearchTests (two rescans double-count one shared PostScanCache
miss; benign revision over-bump), pin the learnings scan's symlink-skip
contract (flip-verified — defended in depth by the lstat guard AND
contentsOfDirectory's own symlink refusal), reorder that scan's guard
so cheap rejections precede the directory listing, and park the roster
chmod window with a ceiling comment.

Finish-audit: 3 reviewers, 0 blocking; the one code finding was
disproved by probe (&& out-binds ?? — the guard was correct). Suite
693/693 via scripts/full-test.sh; swiftlint 0 violations; swiftformat
0/141; hook rig 23/23.

Closes #197
2026-11-17 16:29:46 +01:00

659 lines
27 KiB
Swift
Raw Permalink 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.
//
// ProfileProvisioner.swift
// Museion
//
// S2.1 provisioning (#47): create the museion profile via the Hermes CLI,
// then seed the bundled writing skills additively (#43/#45/#46), then
// register museion-tools via `hermes -p <profile> mcp add` (#23 slice 2 —
// the CLI rail only, never hand-written mcp_servers YAML, #44).
//
// #134 (Profiles S1, ADR-0014): one pass provisions ALL THREE surface
// profiles — `museion` adopted in place, `museion-pass1/2` created fresh
// with the #132 defaults written via `hermes -p <profile> config set`
// (#128: create-time inheritance follows the ACTIVE profile and never
// carries keys — probed; never rely on it). Skills: ONE master copy under
// Application Support, symlinked into each profile per the #133 allocation;
// copy-era dirs migrate to symlinks only on byte-match against the master
// (the link's target — identical to the payload on first seed, and a
// lagging master after an app update keeps the copy rather than silently
// changing skill content through the swap; G3a).
//
import Foundation
import Observation
import os
/// #134 (Profiles S1): the static surface→profile map (ADR-0014). Sessions
/// rides Chat — one engine session model, no profile of its own (#126).
nonisolated enum ProfileSurface: CaseIterable, Sendable {
/// Declaration order = provision and backup order: chat first, so the
/// resident surface is healthy before any pass-profile failure stops
/// the loop.
case chat
case pass1
case pass2
/// Adopted in place for chat — sessions, memory, transcripts survive.
var profileName: String {
switch self {
case .chat: "museion"
case .pass1: "museion-pass1"
case .pass2: "museion-pass2"
}
}
/// #133 allocation table — Pass 1: 10 · Pass 2: 9 · Chat: 11. The persona
/// pair never co-occurs (two manner doctrines fighting for the voice);
/// fiction-craft is structural (P1), reader-psychology is sentence
/// surgery (P2's core), titles-and-hooks is structural critique;
/// owned-insight rides all three (#58 — whether a piece says anything
/// is every surface's question).
var allocatedSkills: [String] {
switch self {
case .pass1: [
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
"micro-drill", "owned-insight", "pass-persona", "fiction-craft", "titles-and-hooks",
]
case .pass2: [
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
"micro-drill", "owned-insight", "pass-persona", "reader-psychology",
]
case .chat: [
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
"micro-drill", "owned-insight", "session-persona", "fiction-craft",
"reader-psychology", "titles-and-hooks",
]
}
}
init?(passKind: PassKind) {
switch passKind {
case .pass1: self = .pass1
case .pass2: self = .pass2
}
}
/// #132 fresh-seed defaults: claude-sonnet-5-5 on all three surfaces,
/// reasoning_effort unset (Anthropic 5.x thinking is adaptive; the bench
/// never varied sonnet effort). Never copied from the live museion
/// profile — it runs glm-5.3-max until switched in Settings.
static let defaultModelProvider = "anthropic"
static let defaultModelID = "claude-sonnet-5-5"
/// #128/#134: 24k output budget — a provisioning-time guardrail via
/// `extra_body.max_tokens --force`, never a Settings control.
static let outputBudgetTokens = 24000
}
/// Outcome of one provisioning pass — `failed` feeds the #48 alert.
nonisolated enum ProfileProvisioner {
/// Which phase failed; names the alert copy (#45).
enum Phase: String, Equatable, Sendable {
case create = "couldn't set up the writing profile"
case copy = "couldn't copy the writing skills"
case register = "couldn't register the writing tools"
case configure = "couldn't set the model defaults"
}
enum Outcome: Equatable, Sendable {
case seeded(copied: Int, present: Int)
/// #134: names the failing profile — the #48 card surfaces it. nil
/// when the failure predates any profile (payload/manifest-level).
case failed(profile: String?, phase: Phase, excerpt: String)
}
/// One idempotent pass over all three surface profiles: master-seed the
/// skills, then per surface — create (or adopt), write defaults on fresh
/// profiles via the CLI rail, link skills per allocation, register
/// museion-tools (#23). First failure wins; the next pass heals.
/// - Parameters:
/// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes).
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
/// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle).
/// - masterRoot: the ONE master skills copy (#133; tests inject; default
/// Application Support — never a symlink into the bundle, which moves
/// on updates).
/// - serverBinaryPath: MCP server the engine spawns — this app's binary with
/// `--serve-mcp` (tests inject; nil skips registration).
static func perform(
hermesBinary: String?,
profileRoot: String = ProfileLayout.defaultRoot,
payloadRoot: String = defaultPayloadRoot(),
masterRoot: String = defaultMasterRoot(),
serverBinaryPath: String? = Bundle.main.executableURL?.path,
timeout: TimeInterval = 60,
) -> Outcome {
var copied = 0
var present = 0
// Phase 0 — the ONE master copy (#133): every manifest skill seeded
// additively as real dirs; profiles symlink in, so a master refresh
// updates every profile instantly and nothing can drift.
guard let manifest = loadManifest(payloadRoot: payloadRoot) else {
return logFailure(.failed(profile: nil, phase: .copy, excerpt: "seed-manifest.txt missing from payload"))
}
switch seedMaster(manifest: manifest, payloadRoot: payloadRoot, masterRoot: masterRoot) {
case let .seeded(deltaCopied, deltaPresent):
copied += deltaCopied
present += deltaPresent
case let .failed(profile, phase, excerpt):
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt))
}
let env = SurfaceEnv(
hermesBinary: hermesBinary,
profileRoot: profileRoot,
masterRoot: masterRoot,
manifest: manifest,
serverBinaryPath: serverBinaryPath,
timeout: timeout,
)
for surface in ProfileSurface.allCases {
switch provisionSurface(surface, env: env) {
case let .seeded(deltaCopied, deltaPresent):
copied += deltaCopied
present += deltaPresent
case let .failed(profile, phase, excerpt):
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt))
}
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
provisioned \(ProfileSurface.allCases.count, privacy: .public) profiles \
(\(copied, privacy: .public) skills linked/copied, \(present, privacy: .public) present)
""")
return .seeded(copied: copied, present: present)
}
/// Per-`perform` context threaded into every surface pass — everything
/// except the surface itself (the loop variable), so the per-surface
/// seam stays under the parameter-count ceiling.
private struct SurfaceEnv {
let hermesBinary: String?
let profileRoot: String
let masterRoot: String
let manifest: [String]
let serverBinaryPath: String?
let timeout: TimeInterval
}
/// Phases 1–4 for ONE surface profile (#134): create (or adopt), write
/// defaults on fresh profiles via the CLI rail, link skills per
/// allocation, register museion-tools (#23).
private static func provisionSurface(
_ surface: ProfileSurface,
env: SurfaceEnv,
) -> Outcome {
let fileManager = FileManager.default
let profileDir = ProfileLayout.profileDir(surface.profileName, root: env.profileRoot)
// Phase 1 — profile create. Dir-check first; spawn only when
// missing (#45). `museion` is adopted, never re-created (ADR-0014).
// `--no-alias` (no shell wrapper), `--no-skills` (the profiles
// carry only Museion's curated set — coding and writing never mix, G3).
var createdFresh = false
if !fileManager.fileExists(atPath: profileDir) {
guard let binary = env.hermesBinary else {
return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found")
}
let run = EngineProbe.execute(
[binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"],
timeout: env.timeout,
)
// #43: exit 1 + "already exists" on stdout = success (a
// concurrent create — not ours, so not fresh); all errors print on stdout.
let alreadyExists = run.exitCode == 1 && run.stdout.contains("already exists")
guard run.exitCode == 0 || alreadyExists, fileManager.fileExists(atPath: profileDir) else {
return .failed(profile: surface.profileName, phase: .create, excerpt: HermesConfigRail.excerpt(run))
}
createdFresh = run.exitCode == 0
}
// Phase 2 — model defaults via the engine's own CLI (#128/#132).
// Marker-gated so a re-pass is a no-op and a user's later Settings
// change survives: fresh creates configure, an unconfigured PASS
// profile (interrupted before its marker landed) is healed, and
// the adopted museion is never touched — its model is the user's.
if createdFresh || (surface != .chat && !markerExists(at: profileDir)) {
guard let binary = env.hermesBinary else {
return .failed(profile: surface.profileName, phase: .configure, excerpt: "hermes binary not found")
}
if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: env.timeout) {
return failure
}
// A marker we couldn't record = configure incomplete — surface it
// (finish-audit: swallowing this re-armed the defaults stomp
// against the user's later Settings change on every later pass).
if let failure = markConfigured(profileDir, profile: surface.profileName) {
return failure
}
}
// Phase 3 — per-profile skills: symlinks per allocation + the
// copy-era → symlink migration (#133).
let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: env.masterRoot, manifest: env.manifest)
if case .failed = linked {
return linked
}
// Phase 4 — museion-tools registration per profile (ADR-0008
// amendment). nil on either binary is the test-injection seam;
// production always has both after a gate pass.
guard let hermesBinary = env.hermesBinary, let serverBinaryPath = env.serverBinaryPath else {
Logger(subsystem: subsystem, category: "provisioning")
.info("museion-tools registration skipped: engine or server binary missing")
return linked
}
if let failure = registerTools(
profile: surface.profileName,
hermesBinary: hermesBinary,
serverBinaryPath: serverBinaryPath,
timeout: env.timeout,
) {
return failure
}
return linked
}
/// The bundled payload ships as a plain Resources directory (#46 map decision).
static func defaultPayloadRoot() -> String {
((Bundle.main.resourcePath ?? "") as NSString).appendingPathComponent("writing skills")
}
/// #133: the ONE master skills copy lives beside state.json and Backups
/// — app-owned, consistent with the rest; never inside the app bundle
/// (the bundle path moves on updates — the mcp-registration stale-path
/// lesson).
static func defaultMasterRoot() -> String {
("~/Library/Application Support/Museion/skills" as NSString).expandingTildeInPath
}
private static let subsystem = "com.babylondreams.Museion"
/// Configured marker: written only by us, after the config rail
/// completes. This is what makes a re-pass a no-op without stomping a
/// later Settings-written model block. The path derivation lives in the
/// layout (#182); the marker-gating policy stays here.
private static func markerExists(at profileDir: String) -> Bool {
FileManager.default.fileExists(atPath: ProfileLayout.configuredMarker(in: profileDir))
}
/// Records the configured marker; nil on success, a configure-phase
/// failure when the write fails — an unrecorded configure must not count
/// as done (the next pass would re-stomp the defaults).
private static func markConfigured(_ profileDir: String, profile: String) -> Outcome? {
let marker = ProfileLayout.configuredMarker(in: profileDir)
do {
try Data().write(to: URL(fileURLWithPath: marker))
return nil
} catch {
return .failed(profile: profile, phase: .configure, excerpt: "couldn't record the provisioning marker: \(error.localizedDescription)")
}
}
/// #128/#132: write the per-surface defaults through the engine's own
/// CLI rail (#182) — provider first (switching providers clears a stale
/// inherited base_url — live-probed), then the model, then the output
/// budget (`--force`: the budget key is unrecognized by some engine
/// versions).
private static func configureDefaults(
profile: String,
hermesBinary: String,
timeout: TimeInterval,
) -> Outcome? {
do {
try HermesConfigRail.apply(
[
.set(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
.set(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
.set(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
],
profile: profile,
binary: hermesBinary,
timeout: timeout,
)
} catch {
let failure = error as? HermesConfigRail.Failure
return .failed(
profile: profile,
phase: .configure,
excerpt: failure?.excerpt ?? error.localizedDescription,
)
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
set model defaults on \(profile, privacy: .public): \
\(ProfileSurface.defaultModelID, privacy: .public), \
budget \(ProfileSurface.outputBudgetTokens, privacy: .public)
""")
return nil
}
/// Seed the master copy: every manifest skill as a REAL dir, additively
/// — present skills are never opened, never overwritten (G3a). Profiles
/// symlink into this one tree.
private static func seedMaster(manifest: [String], payloadRoot: String, masterRoot: String) -> Outcome {
let fileManager = FileManager.default
sweepOrphanedTemps(masterRoot)
var copied = 0
var present = 0
var versions: [String] = []
for name in manifest {
// Trust boundary carried from the manifest parse: kebab-case
// only, so no `/`, `..`, or absolute escape.
guard isKebabCaseDirectoryName(name) else {
return .failed(profile: nil, phase: .copy, excerpt: "invalid manifest entry: \(name)")
}
let source = (payloadRoot as NSString).appendingPathComponent(name)
guard fileManager.fileExists(atPath: source) else {
return .failed(profile: nil, phase: .copy, excerpt: "manifest entry missing from payload: \(name)")
}
versions.append("\(name) \(frontmatterVersion(source) ?? "?")")
let destination = (masterRoot as NSString).appendingPathComponent(name)
if fileManager.fileExists(atPath: destination) {
present += 1
continue
}
// Per-skill atomic: copy to a temp name, rename into place; an
// interrupted copy is healed by the next launch's additive pass
// (#45 — no journal).
let temp = (masterRoot as NSString).appendingPathComponent(".\(name)-\(UUID().uuidString)")
do {
try fileManager.createDirectory(atPath: masterRoot, withIntermediateDirectories: true)
try fileManager.copyItem(atPath: source, toPath: temp)
purgeDotDSStore(temp)
try fileManager.moveItem(atPath: temp, toPath: destination) // lost race → present
copied += 1
} catch {
try? fileManager.removeItem(atPath: temp)
if fileManager.fileExists(atPath: destination) {
present += 1
} else {
return .failed(profile: nil, phase: .copy, excerpt: "copy \(name): \(error.localizedDescription)")
}
}
}
let summary = versions.joined(separator: ", ")
Logger(subsystem: subsystem, category: "provisioning")
.info("master writing skills: \(summary, privacy: .public) (\(copied, privacy: .public) copied, \(present, privacy: .public) present)")
return .seeded(copied: copied, present: present)
}
/// Per-profile skills (#133): create missing symlinks for the surface's
/// allocation; migrate a manifest-tracked copy-era REAL dir to a master
/// symlink only when it still byte-matches (a diverged dir stays a copy;
/// untracked/user skills are never touched; existing links are never
/// retargeted — additive-only, G3a).
private static func linkSkills(
surface: ProfileSurface,
profileDir: String,
masterRoot: String,
manifest: [String],
) -> Outcome {
let fileManager = FileManager.default
let skillsDir = ProfileLayout.skillsDir(in: profileDir)
sweepOrphanedTemps(skillsDir)
var linked = 0
var present = 0
for name in manifest {
let destination = (skillsDir as NSString).appendingPathComponent(name)
let masterSkill = (masterRoot as NSString).appendingPathComponent(name)
// A link (live or dangling) is never touched — additive-only.
if (try? fileManager.destinationOfSymbolicLink(atPath: destination)) != nil {
present += 1
continue
}
if fileManager.fileExists(atPath: destination) {
// Copy-era dir: swap storage to a symlink only when the bytes
// still match the master the link will resolve to — the swap
// must be invisible. Never reached without the dir existing.
if treesByteMatch(masterSkill, destination) {
let aside = (skillsDir as NSString).appendingPathComponent(".\(name)-old-\(UUID().uuidString)")
do {
try fileManager.moveItem(atPath: destination, toPath: aside)
try fileManager.createSymbolicLink(atPath: destination, withDestinationPath: masterSkill)
try? fileManager.removeItem(atPath: aside)
linked += 1
} catch {
try? fileManager.moveItem(atPath: aside, toPath: destination) // never lose the copy
present += 1
}
} else {
present += 1 // diverged: the writer's edits stay a real copy
}
continue
}
// Nothing on disk: only the surface's allocation gets a link —
// an unallocated skill (session-persona on a pass engine) never
// lands (curation, #133).
guard surface.allocatedSkills.contains(name) else { continue }
do {
try fileManager.createDirectory(atPath: skillsDir, withIntermediateDirectories: true)
try fileManager.createSymbolicLink(atPath: destination, withDestinationPath: masterSkill)
linked += 1
} catch {
if fileManager.fileExists(atPath: destination) {
present += 1 // lost race — the link is there
} else {
return .failed(profile: surface.profileName, phase: .copy, excerpt: "copy \(name): \(error.localizedDescription)")
}
}
}
return .seeded(copied: linked, present: present)
}
/// #23 slice 2: register museion-tools into the profile exactly once, via
/// the hermes CLI only — the provisioner never writes mcp_servers YAML
/// itself (#44). `mcp list` first: a re-add would prompt "Overwrite? [y/N]"
/// interactively; the skip avoids that branch. ponytail: a stale command
/// path after the app moves is refreshed manually via
/// `hermes -p <profile> mcp remove museion-tools`.
private static func registerTools(
profile: String,
hermesBinary: String,
serverBinaryPath: String,
timeout: TimeInterval,
) -> Outcome? {
let list = EngineProbe.execute([hermesBinary, "-p", profile, "mcp", "list"], timeout: timeout)
if list.stdout.contains("museion-tools") {
return nil
}
let add = EngineProbe.execute(
[
hermesBinary, "-p", profile, "mcp", "add", "museion-tools",
"--command", serverBinaryPath, "--args", "--serve-mcp",
],
timeout: timeout,
stdin: String(repeating: "y\n", count: 4), // answers "Enable all tools? [Y/n]" — and survives
// profile-startup stdin consumers (observed live: a seeded profile burned
// one line before the prompt; a single y cancelled the save)
)
// Verified wire contract: exit 0 + "Saved 'museion-tools'" on stdout.
guard add.exitCode == 0, add.stdout.contains("Saved 'museion-tools'") else {
return .failed(profile: profile, phase: .register, excerpt: HermesConfigRail.excerpt(add))
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
registered museion-tools via hermes CLI on \(profile, privacy: .public) \
(command: \(serverBinaryPath, privacy: .public))
""")
return nil
}
/// #45: at most one os_log line per failure, carrying the excerpt for Console.app.
@discardableResult
private static func logFailure(_ outcome: Outcome) -> Outcome {
if case let .failed(profile, phase, excerpt) = outcome {
Logger(subsystem: subsystem, category: "provisioning")
.error("""
\(phase.rawValue, privacy: .public) [\(profile ?? "payload", privacy: .public)]: \
\(String(excerpt.prefix(300)), privacy: .public)
""")
}
return outcome
}
}
/// Pure payload/tree filesystem helpers — same-file extension so the
/// provisioner enum stays under its type-body ceiling (MentorPaneView
/// posture). `nonisolated` to match the enum under default-MainActor mode.
nonisolated extension ProfileProvisioner {
/// The manifest as the inclusion list (blank/`#` lines ignored, entries
/// kebab-validated at the trust boundary in `seedMaster`). nil when
/// unreadable.
private static func loadManifest(payloadRoot: String) -> [String]? {
let manifestPath = (payloadRoot as NSString).appendingPathComponent("seed-manifest.txt")
guard let manifest = try? String(contentsOfFile: manifestPath, encoding: .utf8) else {
return nil
}
return manifest.split(separator: "\n")
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty && !$0.hasPrefix("#") }
}
/// ponytail: whole-string character class, not a regex — `allSatisfy` reads
/// as intent and covers `.`/`..`/`/`-prefixed entries without a pattern.
private static func isKebabCaseDirectoryName(_ name: String) -> Bool {
!name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" }
}
/// True when `path` is a symlink (lstat-true, before any open) — the
/// payload never ships one, so a linked entry refuses the tree match.
private static func isSymlinked(_ path: String) -> Bool {
(try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil
}
/// Recursive byte-comparison of two dir trees — same entry names, every
/// file byte-identical. `.DS_Store` is filtered from BOTH listings before
/// the name-equality check (Finder noise, not a user edit — a
/// merely-browsed skill dir must still migrate; the master side is purged
/// at seed time, so a browsed copy-era dir would otherwise never match).
/// A symlinked entry refuses the match outright (finish-audit: the
/// copy-era tree is untrusted — following a link there could open a FIFO
/// or read unbounded bytes; no match simply keeps the dir as a copy).
private static func treesByteMatch(_ lhs: String, _ rhs: String) -> Bool {
let fileManager = FileManager.default
guard let lhsAll = try? fileManager.contentsOfDirectory(atPath: lhs).sorted(),
let rhsAll = try? fileManager.contentsOfDirectory(atPath: rhs).sorted()
else { return false }
let lhsEntries = lhsAll.filter { $0 != ".DS_Store" }
let rhsEntries = rhsAll.filter { $0 != ".DS_Store" }
guard lhsEntries == rhsEntries else { return false }
for name in lhsEntries {
let lhsPath = (lhs as NSString).appendingPathComponent(name)
let rhsPath = (rhs as NSString).appendingPathComponent(name)
// Neither side may carry a symlink at this entry (lstat-true,
// before any open) — the payload never ships one.
if isSymlinked(lhsPath) || isSymlinked(rhsPath) {
return false
}
var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: lhsPath, isDirectory: &lhsIsDirectory),
fileManager.fileExists(atPath: rhsPath, isDirectory: &rhsIsDirectory),
lhsIsDirectory.boolValue == rhsIsDirectory.boolValue
else { return false }
if lhsIsDirectory.boolValue {
if !treesByteMatch(lhsPath, rhsPath) {
return false
}
} else {
guard let lhsData = try? Data(contentsOf: URL(fileURLWithPath: lhsPath)),
let rhsData = try? Data(contentsOf: URL(fileURLWithPath: rhsPath)),
lhsData == rhsData
else { return false }
}
}
return true
}
/// Sweep `.name-UUID` temp entries left by an interrupted copy+rename;
/// the next pass re-copies the skill, but the orphan would linger
/// forever otherwise.
private static func sweepOrphanedTemps(_ dir: String) {
let fileManager = FileManager.default
guard let entries = try? fileManager.contentsOfDirectory(atPath: dir) else { return }
for entry in entries where entry.hasPrefix(".") {
try? fileManager.removeItem(atPath: (dir as NSString).appendingPathComponent(entry))
}
}
/// ponytail: first `version:` line inside the frontmatter block wins — the
/// only place it appears; full YAML parsing isn't worth it for a log line.
private static func frontmatterVersion(_ skillDir: String) -> String? {
let path = (skillDir as NSString).appendingPathComponent("SKILL.md")
guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { return nil }
var inFrontmatter = false
for rawLine in text.split(separator: "\n") {
let line = rawLine.trimmingCharacters(in: .whitespaces)
if line == "---" {
if inFrontmatter {
break
}
inFrontmatter = true
continue
}
if inFrontmatter, line.hasPrefix("version:") {
return line.dropFirst("version:".count)
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
}
}
return nil
}
/// The payload excludes .DS_Store (#46); strip any that sneaked into a copy.
private static func purgeDotDSStore(_ dir: String) {
let fileManager = FileManager.default
guard let entries = try? fileManager.contentsOfDirectory(atPath: dir) else { return }
for entry in entries {
let path = (dir as NSString).appendingPathComponent(entry)
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue {
purgeDotDSStore(path)
} else if entry == ".DS_Store" {
try? fileManager.removeItem(atPath: path)
}
}
}
}
/// App-scoped provisioning state; #48 renders its `lastFailure` as the alert.
@MainActor
@Observable
final class ProvisioningModel {
private(set) var lastFailure: ProfileProvisioner.Outcome?
private var running = false
/// True when a failed pass is waiting to be shown (#48 card's visibility).
var hasFailure: Bool {
lastFailure != nil
}
/// One idempotent pass, off the main actor. Guarded against stacking (#45:
/// onPass fires per passing check; a pass already in flight absorbs re-fires).
func runPass(
hermesBinary: String? = nil,
profileRoot: String? = nil,
payloadRoot: String? = nil,
masterRoot: String? = nil,
) async {
guard !running else { return }
running = true
defer { running = false }
let outcome = await Task.detached(priority: .utility) {
ProfileProvisioner.perform(
hermesBinary: hermesBinary,
profileRoot: profileRoot ?? ProfileLayout.defaultRoot,
payloadRoot: payloadRoot ?? ProfileProvisioner.defaultPayloadRoot(),
masterRoot: masterRoot ?? ProfileProvisioner.defaultMasterRoot(),
)
}.value
if case .failed = outcome {
lastFailure = outcome // verbatim — the #48 card names the profile (#134)
} else {
lastFailure = nil
}
}
}