refactor(profiles): one layout + config-set rail
CI / ci (push) Canceled after 0s

#182: ProfileLayout owns the profile root default and every per-profile
path (dir, .env, configured marker, gateway pid, skills dir) — the five
scattered profile-root literals are gone; the provisioner, the settings
writer, and backup/restore derive paths only through it, pinned once in
ProfileLayoutTests. RESTORE.md prose and the ps-scan grep keep their
literal text deliberately (doc text and argv matching, not paths).

HermesConfigRail owns the config set/unset contract once: argv shape
(+--force), provider-first hoisting (switching providers clears a stale
inherited base_url — a caller can no longer order it wrong), ✓-line
verification, unset-idempotence. The provisioner seeds provider/default/
max_tokens; the writer edits provider/default/effort/base_url — each
keeps its own key list, only the mechanism and ordering rule unify. The
rail's Failure carries key/profile/excerpt for both error surfaces.

Audit hardenings folded in: a leading-dash value refuses before any
spawn (free-text model/endpoint fields cannot reach the child CLI as
options), whitespace-only endpoints read as empty at both writer gates,
the deliberate 500-char excerpt cap is pinned not just commented, and
the failed-unset branch is pinned (the fake hermes grew a
config-unset-fails knob).

Full suite 684 passed / 0 failed; dash + whitespace pins flip-verified.

Closes #182
This commit is contained in:
AlexKucera committed 2026-11-10 11:32:47 +01:00
1 parent f49e4b6ca0
commit a8b158ca26
14 files changed
+484 -113

No files matched your search

+35 -47
View File
@@ -107,7 +107,7 @@ nonisolated enum ProfileProvisioner {
/// museion-tools (#23). First failure wins; the next pass heals.
/// - Parameters:
/// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes).
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
/// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle).
/// - masterRoot: the ONE master skills copy (#133; tests inject; default
/// Application Support — never a symlink into the bundle, which moves
@@ -116,7 +116,7 @@ nonisolated enum ProfileProvisioner {
/// `--serve-mcp` (tests inject; nil skips registration).
static func perform(
hermesBinary: String?,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
profileRoot: String = ProfileLayout.defaultRoot,
payloadRoot: String = defaultPayloadRoot(),
masterRoot: String = defaultMasterRoot(),
serverBinaryPath: String? = Bundle.main.executableURL?.path,
@@ -178,7 +178,7 @@ nonisolated enum ProfileProvisioner {
timeout: TimeInterval,
) -> Outcome {
let fileManager = FileManager.default
let profileDir = (profileRoot as NSString).appendingPathComponent(surface.profileName)
let profileDir = ProfileLayout.profileDir(surface.profileName, root: profileRoot)
// Phase 1 — profile create. Dir-check first; spawn only when
// missing (#45). `museion` is adopted, never re-created (ADR-0014).
@@ -197,7 +197,7 @@ nonisolated enum ProfileProvisioner {
// concurrent create — not ours, so not fresh); all errors print on stdout.
let alreadyExists = run.exitCode == 1 && run.stdout.contains("already exists")
guard run.exitCode == 0 || alreadyExists, fileManager.fileExists(atPath: profileDir) else {
return .failed(profile: surface.profileName, phase: .create, excerpt: excerpt(run))
return .failed(profile: surface.profileName, phase: .create, excerpt: HermesConfigRail.excerpt(run))
}
createdFresh = run.exitCode == 0
}
@@ -263,20 +263,19 @@ nonisolated enum ProfileProvisioner {
private static let subsystem = "com.babylondreams.Museion"
/// Configured-marker filename inside a profile dir — written only by us,
/// after the `config set` rail completes. This is what makes a re-pass a
/// no-op without stomping a later Settings-written model block.
private static let configuredMarker = ".museion-provisioned"
/// Configured marker: written only by us, after the config rail
/// completes. This is what makes a re-pass a no-op without stomping a
/// later Settings-written model block. The path derivation lives in the
/// layout (#182); the marker-gating policy stays here.
private static func markerExists(at profileDir: String) -> Bool {
FileManager.default.fileExists(atPath: (profileDir as NSString).appendingPathComponent(configuredMarker))
FileManager.default.fileExists(atPath: ProfileLayout.configuredMarker(in: profileDir))
}
/// Records the configured marker; nil on success, a configure-phase
/// failure when the write fails — an unrecorded configure must not count
/// as done (the next pass would re-stomp the defaults).
private static func markConfigured(_ profileDir: String, profile: String) -> Outcome? {
let marker = (profileDir as NSString).appendingPathComponent(configuredMarker)
let marker = ProfileLayout.configuredMarker(in: profileDir)
do {
try Data().write(to: URL(fileURLWithPath: marker))
return nil
@@ -285,39 +284,34 @@ nonisolated enum ProfileProvisioner {
}
}
/// One `config set` write: key, value, and whether it needs `--force`
/// (the budget key is unrecognized by some engine versions).
private struct ConfigWrite {
let key: String
let value: String
let force: Bool
}
/// #128/#132: write the per-surface defaults through the engine's own
/// CLI. Provider first (switching providers clears a stale inherited
/// base_url — live-probed), then the model, then the output budget.
/// Verified wire: exit 0, `✓ Set <key> = <value> in …config.yaml`.
/// CLI rail (#182) — provider first (switching providers clears a stale
/// inherited base_url — live-probed), then the model, then the output
/// budget (`--force`: the budget key is unrecognized by some engine
/// versions).
private static func configureDefaults(
profile: String,
hermesBinary: String,
timeout: TimeInterval,
) -> Outcome? {
let writes: [ConfigWrite] = [
ConfigWrite(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
ConfigWrite(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
ConfigWrite(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
]
for write in writes {
var arguments = [hermesBinary, "-p", profile, "config", "set", write.key, write.value]
if write.force {
arguments.append("--force")
}
let run = EngineProbe.execute(arguments, timeout: timeout)
// Wire-verified success, not exit code alone (finish-audit): a CLI
// that exits 0 while writing nothing must not count as configured.
guard run.exitCode == 0, run.stdout.contains("✓ Set \(write.key)") else {
return .failed(profile: profile, phase: .configure, excerpt: excerpt(run))
}
do {
try HermesConfigRail.apply(
[
.set(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
.set(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
.set(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
],
profile: profile,
binary: hermesBinary,
timeout: timeout,
)
} catch {
let failure = error as? HermesConfigRail.Failure
return .failed(
profile: profile,
phase: .configure,
excerpt: failure?.excerpt ?? error.localizedDescription,
)
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
@@ -391,7 +385,7 @@ nonisolated enum ProfileProvisioner {
manifest: [String],
) -> Outcome {
let fileManager = FileManager.default
let skillsDir = (profileDir as NSString).appendingPathComponent("skills")
let skillsDir = ProfileLayout.skillsDir(in: profileDir)
sweepOrphanedTemps(skillsDir)
var linked = 0
var present = 0
@@ -470,7 +464,7 @@ nonisolated enum ProfileProvisioner {
)
// Verified wire contract: exit 0 + "Saved 'museion-tools'" on stdout.
guard add.exitCode == 0, add.stdout.contains("Saved 'museion-tools'") else {
return .failed(profile: profile, phase: .register, excerpt: excerpt(add))
return .failed(profile: profile, phase: .register, excerpt: HermesConfigRail.excerpt(add))
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
@@ -492,12 +486,6 @@ nonisolated enum ProfileProvisioner {
}
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))
}
}
/// Pure payload/tree filesystem helpers — same-file extension so the
@@ -645,7 +633,7 @@ final class ProvisioningModel {
let outcome = await Task.detached(priority: .utility) {
ProfileProvisioner.perform(
hermesBinary: hermesBinary,
profileRoot: profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath,
profileRoot: profileRoot ?? ProfileLayout.defaultRoot,
payloadRoot: payloadRoot ?? ProfileProvisioner.defaultPayloadRoot(),
masterRoot: masterRoot ?? ProfileProvisioner.defaultMasterRoot(),
)