// // 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 museion mcp add` (#23 slice 2 — // the CLI rail only, never hand-written mcp_servers YAML, #44). // import Foundation import Observation import os /// 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" } enum Outcome: Equatable, Sendable { case seeded(copied: Int, present: Int) case failed(phase: Phase, excerpt: String) } /// One idempotent pass: create the profile if missing, seed missing skills /// (#45), register museion-tools when missing (#23). /// - Parameters: /// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes). /// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`). /// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle). /// - 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 = ("~/.hermes/profiles" as NSString).expandingTildeInPath, payloadRoot: String = defaultPayloadRoot(), serverBinaryPath: String? = Bundle.main.executableURL?.path, timeout: TimeInterval = 60, ) -> Outcome { let profileDir = (profileRoot as NSString).appendingPathComponent("museion") let fileManager = FileManager.default // Phase 1 — profile create. Dir-check first; spawn only when missing (#45). // `--no-alias` (no shell wrapper), `--no-skills` (the mentor's profile carries // only Museion's curated set — coding and writing never mix, G3). if !fileManager.fileExists(atPath: profileDir) { guard let binary = hermesBinary else { return logFailure(.failed(phase: .create, excerpt: "hermes binary not found")) } let run = EngineProbe.execute( [binary, "profile", "create", "museion", "--no-alias", "--no-skills"], timeout: timeout, ) // #43: exit 1 + "already exists" on stdout = success; 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 logFailure(.failed(phase: .create, excerpt: excerpt(run))) } } // Phase 2 — additive seed per seed-manifest.txt (#46). let seeded = seedSkills(payloadRoot: payloadRoot, profileDir: profileDir) guard case .seeded = seeded else { return seeded } // Phase 3 — museion-tools registration (#23 slice 2). nil on either // binary is the test-injection seam; production always has both after a // gate pass (the server IS this app's binary). guard let hermesBinary, let serverBinaryPath else { Logger(subsystem: subsystem, category: "provisioning") .info("museion-tools registration skipped: engine or server binary missing") return seeded } return registerTools(seeded, hermesBinary: hermesBinary, serverBinaryPath: serverBinaryPath, timeout: timeout) } /// The bundled payload ships as a plain Resources directory (#46 map decision). static func defaultPayloadRoot() -> String { ((Bundle.main.resourcePath ?? "") as NSString).appendingPathComponent("writing skills") } private static let subsystem = "com.babylondreams.Museion" /// 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 == "-" } } /// Copy every manifest-listed skill that's missing; never touch present ones (G3a). private static func seedSkills(payloadRoot: String, profileDir: String) -> Outcome { let fileManager = FileManager.default let skillsDir = (profileDir as NSString).appendingPathComponent("skills") sweepOrphanedTemps(skillsDir) let manifestPath = (payloadRoot as NSString).appendingPathComponent("seed-manifest.txt") guard let manifest = try? String(contentsOfFile: manifestPath, encoding: .utf8) else { return logFailure(.failed(phase: .copy, excerpt: "seed-manifest.txt missing from payload")) } let names = manifest.split(separator: "\n") .map { $0.trimmingCharacters(in: .whitespaces) } .filter { !$0.isEmpty && !$0.hasPrefix("#") } var copied = 0 var present = 0 var versions: [String] = [] for name in names { // Trust boundary: manifest entries become path components — kebab-case // only (the payload contract), so no `/`, `..`, or absolute escape. guard isKebabCaseDirectoryName(name) else { return logFailure(.failed(phase: .copy, excerpt: "invalid manifest entry: \(name)")) } let source = (payloadRoot as NSString).appendingPathComponent(name) guard fileManager.fileExists(atPath: source) else { return logFailure(.failed(phase: .copy, excerpt: "manifest entry missing from payload: \(name)")) } versions.append("\(name) \(frontmatterVersion(source) ?? "?")") let destination = (skillsDir as NSString).appendingPathComponent(name) if fileManager.fileExists(atPath: destination) { present += 1 // present skills are never opened, never overwritten (G3a) 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 = (skillsDir as NSString).appendingPathComponent(".\(name)-\(UUID().uuidString)") do { try fileManager.createDirectory(atPath: skillsDir, 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 logFailure(.failed(phase: .copy, excerpt: "copy \(name): \(error.localizedDescription)")) } } } let summary = versions.joined(separator: ", ") Logger(subsystem: subsystem, category: "provisioning") .info("seeded writing skills: \(summary, privacy: .public) (\(copied, privacy: .public) copied, \(present, privacy: .public) present)") return .seeded(copied: copied, 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 museion mcp remove museion-tools`. private static func registerTools( _ seeded: Outcome, hermesBinary: String, serverBinaryPath: String, timeout: TimeInterval, ) -> Outcome { let list = EngineProbe.execute([hermesBinary, "-p", "museion", "mcp", "list"], timeout: timeout) if list.stdout.contains("museion-tools") { return seeded } let add = EngineProbe.execute( [ hermesBinary, "-p", "museion", "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 logFailure(.failed(phase: .register, excerpt: excerpt(add))) } Logger(subsystem: subsystem, category: "provisioning") .info("registered museion-tools via hermes CLI (command: \(serverBinaryPath, privacy: .public))") return seeded } /// Sweep `.name-UUID` temp dirs left by an interrupted copy+rename; the next /// pass re-copies the skill, but the orphan would linger forever otherwise. private static func sweepOrphanedTemps(_ skillsDir: String) { let fileManager = FileManager.default guard let entries = try? fileManager.contentsOfDirectory(atPath: skillsDir) else { return } for entry in entries where entry.hasPrefix(".") { try? fileManager.removeItem(atPath: (skillsDir as NSString).appendingPathComponent(entry)) } } /// #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(phase, excerpt) = outcome { Logger(subsystem: subsystem, category: "provisioning") .error("\(phase.rawValue, privacy: .public): \(String(excerpt.prefix(300)), privacy: .public)") } return outcome } /// Create-phase errors print on stdout (#43); copy-phase on stderr — take both. private static func excerpt(_ run: EngineProbe.ProcessOutput) -> String { let text = run.stdout.isEmpty ? run.stderr : run.stdout return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500)) } /// 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 } /// Not Now (#48): defer to the next launch's silent retry. func deferFailure() { 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, ) async { guard !running else { return } running = true defer { running = false } let outcome = await Task.detached(priority: .utility) { ProfileProvisioner.perform( hermesBinary: hermesBinary, profileRoot: profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath, payloadRoot: payloadRoot ?? ProfileProvisioner.defaultPayloadRoot(), ) }.value if case let .failed(phase, excerpt) = outcome { lastFailure = .failed(phase: phase, excerpt: excerpt) } else { lastFailure = nil } } }