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

+10 -3
View File
@@ -6,7 +6,7 @@ The Museion application target: the native SwiftUI macOS app shell of the Agenti
## Ownership
Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchronized groups** — files on disk are the truth; add/move/delete sources here and Xcode follows. Never hand-edit project.pbxproj beyond plain build-setting values (bundle id, version, Swift version).
Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchronized groups** — files on disk are the truth; add/move/delete sources here and Xcode follows. Never hand-edit project.pbxproj beyond plain build-setting values and the one sanctioned exception: the `ref/writing skills` **folder reference** into the Resources phase (#46 map decision — a folder reference can't be expressed through fs-sync groups).
## Local Contracts
@@ -19,12 +19,19 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Engine gate (launch gate, tickets #35–#41)
- `EngineGate.swift` — `EngineProbe` (nonisolated): six-path probe order, `acp --check` health (stdin closed, 5 s timeout, exit-status branching), `acp --version` version, `state.json` writer/reader. `EngineGateModel` (@MainActor @Observable): phases for the UI, `onPass` seam for #13 provisioning.
- `EngineGate.swift` — `EngineProbe` (nonisolated): six-path probe order, `acp --check` health (stdin closed, 5 s timeout, exit-status branching), `acp --version` version, `state.json` writer/reader. `EngineGateModel` (@MainActor @Observable): phases for the UI, `onPass` seam (fires provisioning, #47), `currentBinaryPath` handed to provisioning. `execute(_:timeout:)`/`ProcessOutput` are internal — shared child-process machinery.
- `EngineGateView.swift` — blocking sheet card: checking / pass (version + Start Writing) / fail (two install steps per #40, Re-check, Technical details disclosure). `interactiveDismissDisabled`; sheet never closes itself.
- `state.json` lives at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check; fail records carry no `engineVersion`. Gate renders in-memory; About (`AboutEngineView` in `MuseionApp.swift`) reads the file and never triggers a check.
- Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` is where provisioning (#13) will fire in parallel on pass.
- Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` fires provisioning (#47) in parallel on pass.
- Tests: `MuseionTests/EngineGateTests.swift` builds fake `hermes` shell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records.
## Profile provisioning (S2.1, tickets #43–#48)
- `ProfileProvisioner.swift` — `ProfileProvisioner` (nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawn `hermes profile create museion --no-alias --no-skills` only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: `seed-manifest.txt` in the payload root is the inclusion list (blank/`#` lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping `skills/`); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned `.`-prefixed temp dirs from an interrupted copy are swept at pass start; `.DS_Store` purged from copies. One os_log line per pass (`seeded writing skills: <name> <version>, … (N copied, M present)`) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). `ProvisioningModel` (@MainActor @Observable): runs the pass off-main, guards stacking, records `lastFailure` (phase-named copy + excerpt); failure never re-raises the gate.
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented` = `hasFailure && gateDismissed`, where `gateDismissed` is set in the gate sheet's `onDismiss` — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into `@State` so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (`deferFailure`) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning writes nothing to the profile config — never an `mcp_servers` entry (#44 negative invariant, test-pinned).
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills seeded; `ste-writing`/`writing-for-agents` ship but never seed.
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `<binaryDir>/profiles/<name>`), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload.
## Work Guidance
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001).
+29 -2
View File
@@ -15,6 +15,22 @@ enum AppMetadata {
struct ContentView: View {
@Environment(AppGateState.self) private var gate
/// #48: provisioning failure presents only once the gate sheet has fully
/// dismissed — keying on `gateDismissed` (set in the sheet's onDismiss,
/// which fires at dismissal completion) rather than `!gateRaised` (which
/// flips at dismissal start); macOS can drop a sheet presented during
/// another sheet's dismissal animation.
private var failurePresented: Binding<Bool> {
Binding(
get: { gate.provisioning.hasFailure && gate.gateDismissed },
set: {
if !$0 {
gate.provisioning.deferFailure()
}
},
)
}
var body: some View {
@Bindable var gate = gate
@@ -33,10 +49,21 @@ struct ContentView: View {
EngineGateView(
model: gate.gateModel,
onEnginePass: {
// Ticket #41: provisioning (#13) fires here in parallel — stub until #13 lands.
// #47: provisioning runs in parallel on pass; idempotent, so re-fires
// are no-ops. Alert UX on failure is #48.
Task { await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath) }
},
onDismiss: {
gate.gateRaised = false
gate.gateDismissed = true
},
onDismiss: { gate.gateRaised = false },
)
}
.sheet(isPresented: failurePresented) {
ProvisioningFailureCard(model: gate.provisioning) {
Task { await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath) }
}
.interactiveDismissDisabled()
}
}
}
+6 -2
View File
@@ -87,7 +87,7 @@ nonisolated enum EngineProbe {
}
/// Run a process with stdin closed, capture stdout/stderr, kill after `timeout`.
private static func execute(_ arguments: [String], timeout: TimeInterval) -> ProcessOutput {
static func execute(_ arguments: [String], timeout: TimeInterval) -> ProcessOutput {
let path = arguments[0]
guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) }
let process = Process()
@@ -138,7 +138,7 @@ nonisolated enum EngineProbe {
}
/// Captured output of one child process run.
private struct ProcessOutput {
struct ProcessOutput {
let exitCode: Int32
var stdout: String = ""
var stderr: String = ""
@@ -214,6 +214,9 @@ final class EngineGateModel {
var onPass: (@MainActor @Sendable () -> Void)?
private var hasStarted = false
private var running = false
/// The gate's winning binary path — handed to provisioning (#47) so the
/// profile-create spawn uses the exact binary the gate just health-checked.
private(set) var currentBinaryPath: String?
/// Runs the probe loop off the main actor, then updates phase. Guards double-run.
func runCheck(
@@ -231,6 +234,7 @@ final class EngineGateModel {
switch result {
case let .pass(engineVersion, binaryPath):
phase = .pass(engineVersion: engineVersion, binaryPath: binaryPath)
currentBinaryPath = binaryPath
onPass?()
case let .fail(firstProbePath, stderrExcerpt):
phase = .fail(firstProbePath: firstProbePath, stderrExcerpt: stderrExcerpt)
+74
View File
@@ -159,6 +159,80 @@ struct EngineGateView: View {
private let installCommand = "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"
}
/// #48: provisioning failure card — separate from the gate, which never re-raises.
/// Presented only after the gate sheet has been dismissed.
struct ProvisioningFailureCard: View {
let model: ProvisioningModel
/// Retry re-runs the whole idempotent pass with the gate's binary (#45).
let onRetry: () -> Void
/// Snapshot taken when the card appears; a successful Retry nils
/// `model.lastFailure` mid-presentation, and reading it live would blank
/// the card during its dismiss animation.
@State private var failure: ProfileProvisioner.Outcome?
var body: some View {
if let failure, case let .failed(phase, excerpt) = failure {
VStack(spacing: 14) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30))
.foregroundStyle(.orange)
Text(phase.rawValue)
.font(.title3)
Text("Museion couldn't finish setting up the mentor's writing profile. Nothing is lost — the setup is safe to run again.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
if !excerpt.isEmpty {
DisclosureGroup("Technical details") {
Text(excerpt)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
.frame(maxWidth: .infinity, alignment: .leading)
}
HStack {
Button("Not Now") {
model.deferFailure()
}
.keyboardShortcut(.cancelAction)
Button("Retry") {
onRetry()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
}
}
.padding(24)
.frame(width: 460)
.onAppear(perform: refreshIfNewFailure)
.onChange(of: model.lastFailure) {
refreshIfNewFailure()
}
}
}
/// Refresh only on a new failure — never on clearing, so the card stays
/// rendered until the sheet dismisses it.
private func refreshIfNewFailure() {
if case .failed = model.lastFailure {
failure = model.lastFailure
}
}
}
#Preview {
EngineGateView(model: EngineGateModel())
}
#Preview("provisioning failure") {
ProvisioningFailureCard(
model: ProvisioningModel(),
onRetry: {},
)
}
+4
View File
@@ -13,7 +13,11 @@ import SwiftUI
@Observable
final class AppGateState {
var gateRaised = true
/// True once the gate sheet's onDismiss fired (dismissal completion, #48) —
/// the provisioning failure card presents only after this.
var gateDismissed = false
let gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
}
@main
+238
View File
@@ -0,0 +1,238 @@
//
// 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).
//
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"
}
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).
/// - 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).
static func perform(
hermesBinary: String?,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
payloadRoot: String = defaultPayloadRoot(),
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).
return seedSkills(payloadRoot: payloadRoot, profileDir: profileDir)
}
/// 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)
}
/// 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
}
}
}