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

+2 -1
View File
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (621 symbols, 860 relationships, 6 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. This project is indexed by GitNexus as **museion** (752 symbols, 1122 relationships, 11 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -177,5 +177,6 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start --> <!-- write-log: window-start -->
| Date | Log | | Date | Log |
|------|-----| |------|-----|
| 2026-09-05 | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](docs/devlog/20260905-issue48-provisioning-failure-alert-retry-ux_log.md) |
| 2026-09-03 | [20260903-issue42-engine-gate-s2-1_log.md](docs/devlog/20260903-issue42-engine-gate-s2-1_log.md) | | 2026-09-03 | [20260903-issue42-engine-gate-s2-1_log.md](docs/devlog/20260903-issue42-engine-gate-s2-1_log.md) |
<!-- write-log: window-end --> <!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added ### Added
- **provisioning:** S2.1 profile provisioning — idempotent per-gate pass creates the `museion` Hermes profile (`hermes profile create --no-alias --no-skills`) and additively seeds the bundled writing skills via `seed-manifest.txt`; existing skills are never overwritten (issue #47)
- **provisioning:** Failure alert & retry UX — provisioning failures show a separate phase-named alert (never re-raising the gate) with the error excerpt behind Technical details; Retry re-runs the whole pass, Not Now defers to the next launch's silent retry (issue #48)
- **gate:** Engine gate (launch gate, PRD S2.1) — discovers the user-installed Hermes engine via the documented six-path probe, health-checks it (`hermes acp --check`), and blocks app launch behind a sheet on every launch: checking/pass/fail cards with install instructions and re-check on fail, engine version in the pass card, About window, and a `state.json` record of every completed check (issue #42) - **gate:** Engine gate (launch gate, PRD S2.1) — discovers the user-installed Hermes engine via the documented six-path probe, health-checks it (`hermes acp --check`), and blocks app launch behind a sheet on every launch: checking/pass/fail cards with install instructions and re-check on fail, engine version in the pass card, About window, and a `state.json` record of every completed check (issue #42)
- Initial project scaffold: Xcode project (SwiftUI, macOS 26.5+, Swift 6), unit + UI smoke tests, GPL-3.0-or-later license, Gitea Actions CI (dormant until a macOS runner registers), DOX agent documentation tree, ADRs 0001–0003 (stack, license, forge). - Initial project scaffold: Xcode project (SwiftUI, macOS 26.5+, Swift 6), unit + UI smoke tests, GPL-3.0-or-later license, Gitea Actions CI (dormant until a macOS runner registers), DOX agent documentation tree, ADRs 0001–0003 (stack, license, forge).
- **skills:** Pass and Session container persona skills — mentor manner by blend arithmetic (constant Knife floor, silent Learnings, voice anchor) - **skills:** Pass and Session container persona skills — mentor manner by blend arithmetic (constant Knife floor, silent Learnings, voice anchor)
+7
View File
@@ -6,6 +6,10 @@
objectVersion = 77; objectVersion = 77;
objects = { objects = {
/* Begin PBXBuildFile section */
FA47B002303F047000000002 /* writing skills in Resources */ = {isa = PBXBuildFile; fileRef = FA47B001303F047000000001 /* writing skills */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */ /* Begin PBXContainerItemProxy section */
FA17A9EF303F03A00023843F /* PBXContainerItemProxy */ = { FA17A9EF303F03A00023843F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy; isa = PBXContainerItemProxy;
@@ -24,6 +28,7 @@
/* End PBXContainerItemProxy section */ /* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
FA47B001303F047000000001 /* writing skills */ = {isa = PBXFileReference; lastKnownFileType = folder; name = "writing skills"; path = "ref/writing skills"; sourceTree = "<group>"; };
FA17A9DF303F039F0023843F /* Museion.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Museion.app; sourceTree = BUILT_PRODUCTS_DIR; }; FA17A9DF303F039F0023843F /* Museion.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Museion.app; sourceTree = BUILT_PRODUCTS_DIR; };
FA17A9EE303F03A00023843F /* MuseionTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MuseionTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; FA17A9EE303F03A00023843F /* MuseionTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MuseionTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
FA17A9F8303F03A00023843F /* MuseionUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MuseionUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; FA17A9F8303F03A00023843F /* MuseionUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MuseionUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -78,6 +83,7 @@
FA17A9E1303F039F0023843F /* Museion */, FA17A9E1303F039F0023843F /* Museion */,
FA17A9F1303F03A00023843F /* MuseionTests */, FA17A9F1303F03A00023843F /* MuseionTests */,
FA17A9FB303F03A00023843F /* MuseionUITests */, FA17A9FB303F03A00023843F /* MuseionUITests */,
FA47B001303F047000000001 /* writing skills */,
FA17A9E0303F039F0023843F /* Products */, FA17A9E0303F039F0023843F /* Products */,
); );
sourceTree = "<group>"; sourceTree = "<group>";
@@ -212,6 +218,7 @@
isa = PBXResourcesBuildPhase; isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
FA47B002303F047000000002 /* writing skills in Resources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
+10 -3
View File
@@ -6,7 +6,7 @@ The Museion application target: the native SwiftUI macOS app shell of the Agenti
## Ownership ## 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 ## 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) ## 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. - `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. - `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. - 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 ## Work Guidance
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001). - 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 { struct ContentView: View {
@Environment(AppGateState.self) private var gate @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 { var body: some View {
@Bindable var gate = gate @Bindable var gate = gate
@@ -33,10 +49,21 @@ struct ContentView: View {
EngineGateView( EngineGateView(
model: gate.gateModel, model: gate.gateModel,
onEnginePass: { 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`. /// 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] let path = arguments[0]
guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) } guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) }
let process = Process() let process = Process()
@@ -138,7 +138,7 @@ nonisolated enum EngineProbe {
} }
/// Captured output of one child process run. /// Captured output of one child process run.
private struct ProcessOutput { struct ProcessOutput {
let exitCode: Int32 let exitCode: Int32
var stdout: String = "" var stdout: String = ""
var stderr: String = "" var stderr: String = ""
@@ -214,6 +214,9 @@ final class EngineGateModel {
var onPass: (@MainActor @Sendable () -> Void)? var onPass: (@MainActor @Sendable () -> Void)?
private var hasStarted = false private var hasStarted = false
private var running = 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. /// Runs the probe loop off the main actor, then updates phase. Guards double-run.
func runCheck( func runCheck(
@@ -231,6 +234,7 @@ final class EngineGateModel {
switch result { switch result {
case let .pass(engineVersion, binaryPath): case let .pass(engineVersion, binaryPath):
phase = .pass(engineVersion: engineVersion, binaryPath: binaryPath) phase = .pass(engineVersion: engineVersion, binaryPath: binaryPath)
currentBinaryPath = binaryPath
onPass?() onPass?()
case let .fail(firstProbePath, stderrExcerpt): case let .fail(firstProbePath, stderrExcerpt):
phase = .fail(firstProbePath: firstProbePath, stderrExcerpt: 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" 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 { #Preview {
EngineGateView(model: EngineGateModel()) EngineGateView(model: EngineGateModel())
} }
#Preview("provisioning failure") {
ProvisioningFailureCard(
model: ProvisioningModel(),
onRetry: {},
)
}
+4
View File
@@ -13,7 +13,11 @@ import SwiftUI
@Observable @Observable
final class AppGateState { final class AppGateState {
var gateRaised = true 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 gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
} }
@main @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
}
}
}
+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. - 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. - `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 ## Verification
+3 -1
View File
@@ -115,7 +115,9 @@ struct EngineGateTests {
let result = EngineProbe.perform( let result = EngineProbe.perform(
probePaths: [hung, good], probePaths: [hung, good],
shellFallback: false, 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"), appSupportDir: tempDir("state"),
) )
#expect(result == .pass(version: "9.9.9", binaryPath: good)) #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)
}
}
@@ -0,0 +1,63 @@
# Provisioning failure alert & retry UX (#48)
> **Date:** 2026-09-05
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/48
## Goal
Ship #48 — the failure path of S2.1 provisioning on top of #47's uncommitted success path: when a provisioning pass fails (profile-create error, copy error, missing manifest entry), Museion shows a separate phase-named alert; the gate never re-raises. Retry re-runs the whole idempotent pass; Not Now defers to the next launch's silent retry.
## What Was Done
- `ProvisioningModel` gained `hasFailure` + `deferFailure()` (Not Now) — ProfileProvisioner.swift.
- `ProvisioningFailureCard` (EngineGateView.swift) — separate sheet: phase rawValue as title, excerpt behind Technical details, Retry + Not Now, `interactiveDismissDisabled`.
- `ContentView.failurePresented` — second sheet bound to `hasFailure && gateDismissed`; `AppGateState.gateDismissed` set in the gate sheet's `onDismiss` so the failure sheet presents only after the gate sheet's dismissal *completes* (macOS can drop a sheet presented during another's dismissal animation).
- Card snapshots the failure into `@State`, refreshed only on new failures — a successful Retry nils `model.lastFailure` without blanking the card mid-dismiss.
- Tests (+7): stderr-fallback create excerpt, config.yaml byte-identity (pre-existing + fresh-profile), state.json engine-gate-only, copy-phase catch branch, Not-Now defer + re-fail, path-traversal rejection, orphaned-temp sweep. 30/30 green.
- Audit fixes: kebab-case guard on manifest entries at the trust boundary (`isKebabCaseDirectoryName`); orphaned `.name-UUID` temp dirs swept at pass start (`sweepOrphanedTemps`); deleted the unreachable `firstAvailableBinary()` fallback; `SeedSkill` memberwise init; test suite split at SwiftLint's file-length cap into `ProfileProvisionerFailureTests.swift` with shared internal helpers (`provTempDir` avoids EngineGateTests' `tempDir` collision).
- Docs: frontmatter `email` restored in fiction-craft + serif-writing; stale #13 ref fixed; pbxproj folder-reference exception documented in Museion/AGENTS.md; DOX contracts updated for the card, the guard, and the sweep.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Failure card keyed on `gateDismissed`, not `!gateRaised` | Sheet-level `onDismiss` fires at dismissal completion; `!gateRaised` flips at start and can race a second sheet into being dropped |
| Snapshot failure in card `@State` | Live read of `lastFailure` blanks the card during Retry's dismiss animation |
| Kebab-case guard vs. regex blocklist | One `allSatisfy` at the trust boundary enforces the documented payload contract and kills `/`, `..`, absolute escapes in one line |
| Declined: manifest → directory scan | Closed #46/#47 resolutions pin the manifest file; #48 AC5 names it |
| Declined: stderr-preference excerpt | #43 documents create errors print on stdout; current order is the spec |
| Declined: symlink hardening | ADR-0009 accepted same-user posture; no privilege boundary crossed |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| mcp-servers test expected `copied: 2` on retry | Failed pass copies skills *before* hitting the missing entry — partial progress is the idempotence design | Expect `copied: 0, present: 2` |
| SwiftFormat/SwiftLint closure-parameter fight in ContentView | Inline `Binding(get:set:)` reflows differently per tool | Extract `failurePresented` computed property |
| `defaultSkills`/helpers invisible after test-file split | `private` file scope; EngineGateTests owns `tempDir` already | Internal + `provTempDir` rename |
| Subagent summaries truncated at ~400 chars in transcripts | Transcript line cap | Full outputs live in `subagent-summary-*.txt`; read those |
| One reviewer died at iteration cap (API timeout on final call) | 90 s non-streaming timeout | Re-dispatched with tight scope + word cap; recovered findings from live log |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ProfileProvisioner.swift` | `hasFailure`/`deferFailure`; kebab guard; orphan sweep; fallback deleted |
| `Museion/EngineGateView.swift` | `ProvisioningFailureCard` + snapshot state |
| `Museion/ContentView.swift` | `failurePresented` binding + second sheet |
| `Museion/MuseionApp.swift` | `gateDismissed` flag |
| `MuseionTests/ProfileProvisionerTests.swift` | +5 tests; shared helpers; memberwise init |
| `MuseionTests/ProfileProvisionerFailureTests.swift` | New file — failure-path suite (5 tests) |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | Contracts updated for #48 |
| `ref/writing skills/{fiction-craft,serif-writing}/SKILL.md` | `email` frontmatter restored |
## Open Items & Next Steps
- [ ] Verify the failure card by hand on a machine where `hermes profile create` errors (retry + Not Now paths)
- [ ] Empty-dir create edge (crashed create leaves `museion/` dir) — declined this session; revisit if hermes documents empty-dir healing
- [ ] `#23` registers museion-tools via `hermes mcp add` once the mode serves — never in provisioning (#44)
---
*Log written by write-log skill*
+1
View File
@@ -5,4 +5,5 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index --> <!-- write-log: full-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 2026-09-05 | issue | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](20260905-issue48-provisioning-failure-alert-retry-ux_log.md) | #48 shipped: failure card with retry/Not-Now, traversal guard, temp sweep — 30 tests green |
| 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green | | 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green |
+1
View File
@@ -13,6 +13,7 @@ Owned by the root AGENTS.md contract. Vocabulary is bound by CONTEXT.md (Mentor,
- One skill per kebab-case directory holding a `SKILL.md`. - One skill per kebab-case directory holding a `SKILL.md`.
- Frontmatter: `name`, `description` (quoted string), `license: GNU GPLv3`, `metadata` (author, email, version). - Frontmatter: `name`, `description` (quoted string), `license: GNU GPLv3`, `metadata` (author, email, version).
- Seeding is additive-only: bundled skills land in the profile if absent; existing profile skills are never overwritten. - Seeding is additive-only: bundled skills land in the profile if absent; existing profile skills are never overwritten.
- `seed-manifest.txt` lists the shipped set — update it when adding or removing a mentor skill. `ste-writing` and `writing-for-agents` stay in ref/ as authoring tools, never seeded.
- Deslop owns the single subtractive rule set; serif-writing owns the method. Other skills reference both; none restates them. - Deslop owns the single subtractive rule set; serif-writing owns the method. Other skills reference both; none restates them.
- The persona pair shares three sections verbatim by design (Knife floor, silent learnings, voice anchor) — edit them together or not at all. - The persona pair shares three sections verbatim by design (Knife floor, silent learnings, voice anchor) — edit them together or not at all.
@@ -8,6 +8,11 @@ triggers:
- "novel" - "novel"
- "story" - "story"
- "developmental edit" - "developmental edit"
license: GNU GPLv3
metadata:
author: Alexander Kucera
email: a.kucera@babylondreams.de
version: "1.0"
--- ---
# Fiction Craft — Developmental Level # Fiction Craft — Developmental Level
+12
View File
@@ -0,0 +1,12 @@
# Seeded mentor skills — one skill-dir name per line (ref/writing skills/AGENTS.md sync contract).
demonstrator
deslop
fiction-craft
micro-drill
pass-persona
prose-craft
reader-psychology
rhetoric
serif-writing
session-persona
titles-and-hooks
@@ -6,6 +6,11 @@ triggers:
- "rewrite" - "rewrite"
- "writing quality" - "writing quality"
- "draft" - "draft"
license: GNU GPLv3
metadata:
author: Alexander Kucera
email: a.kucera@babylondreams.de
version: "1.0"
--- ---
# Serif Writing Methodology # Serif Writing Methodology