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

+27 -55
View File
@@ -79,7 +79,7 @@ struct NoopSettingsWriter: SettingsWriting {
struct HermesSettingsWriter: SettingsWriting {
let hermesBinary: String?
var profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath
var profileRoot: String = ProfileLayout.defaultRoot
struct WriteError: LocalizedError, Equatable {
let message: String
@@ -100,18 +100,24 @@ struct HermesSettingsWriter: SettingsWriting {
}
let binary = hermesBinary, profile = surface.profileName
try await Task.detached(priority: .utility) {
// Provider first (switching clears a stale base_url — probed),
// then the model, then effort, then the z.ai endpoint family.
try Self.setKey("model.provider", config.provider.rawValue, profile: profile, binary: binary, timeout: 30)
try Self.setKey("model.default", config.model, profile: profile, binary: binary, timeout: 30)
// The rail owns the mechanism and the provider-first rule (#182):
// provider (switching clears a stale base_url — probed), then the
// model, then effort (set or unset), then the z.ai endpoint family.
var ops: [HermesConfigRail.Write] = [
.set(key: "model.provider", value: config.provider.rawValue, force: false),
.set(key: "model.default", value: config.model, force: false),
]
if let effort = config.effort {
try Self.setKey("model.reasoning_effort", effort.rawValue, profile: profile, binary: binary, timeout: 30)
ops.append(.set(key: "model.reasoning_effort", value: effort.rawValue, force: false))
} else {
try Self.unsetKey("model.reasoning_effort", profile: profile, binary: binary, timeout: 30)
ops.append(.unset(key: "model.reasoning_effort"))
}
if let zaiEndpoint, !zaiEndpoint.isEmpty {
try Self.setKey("model.base_url", zaiEndpoint, profile: profile, binary: binary, timeout: 30)
// Whitespace-only = empty (learning #6: mirror the trimmed
// emptiness the model side validates, not raw isEmpty).
if let zaiEndpoint, !zaiEndpoint.trimmingCharacters(in: .whitespaces).isEmpty {
ops.append(.set(key: "model.base_url", value: zaiEndpoint, force: false))
}
try HermesConfigRail.apply(ops, profile: profile, binary: binary, timeout: 30)
}.value
}
@@ -128,7 +134,9 @@ struct HermesSettingsWriter: SettingsWriting {
config: ProviderKeyConfig,
profiles: [ProfileSurface],
) async throws {
let writesBaseURL = provider == .zai && !config.endpoint.isEmpty
// Whitespace-only endpoint/key = empty (learning #6: trimmed
// emptiness, never raw isEmpty, at free-text gates).
let writesBaseURL = provider == .zai && !config.endpoint.trimmingCharacters(in: .whitespaces).isEmpty
if writesBaseURL, hermesBinary == nil {
throw WriteError(message: "hermes binary not found — pass the engine gate first")
}
@@ -137,14 +145,19 @@ struct HermesSettingsWriter: SettingsWriting {
let binary = hermesBinary
try await Task.detached(priority: .utility) {
for surface in ProfileSurface.allCases {
let dir = (root as NSString).appendingPathComponent(surface.profileName)
let dir = ProfileLayout.profileDir(surface.profileName, root: root)
if !key.isEmpty {
try Self.upsertEnvFile(varName: varName, value: key, profileDir: dir, profile: surface.profileName)
}
}
if let endpoint, let binary {
for surface in profiles {
try Self.setKey("model.base_url", endpoint, profile: surface.profileName, binary: binary, timeout: 30)
try HermesConfigRail.apply(
[.set(key: "model.base_url", value: endpoint, force: false)],
profile: surface.profileName,
binary: binary,
timeout: 30,
)
}
}
}.value
@@ -185,8 +198,7 @@ struct HermesSettingsWriter: SettingsWriting {
let root = profileRoot, varName = provider.envVarName
return await Task.detached(priority: .utility) { () -> String? in
for surface in ProfileSurface.allCases {
let envPath = ((root as NSString).appendingPathComponent(surface.profileName) as NSString)
.appendingPathComponent(".env")
let envPath = ProfileLayout.envFile(in: ProfileLayout.profileDir(surface.profileName, root: root))
guard let text = try? String(contentsOfFile: envPath, encoding: .utf8) else { continue }
for line in text.split(separator: "\n") where line.hasPrefix("\(varName)=") {
let value = line.dropFirst("\(varName)=".count).trimmingCharacters(in: .whitespaces)
@@ -199,46 +211,6 @@ struct HermesSettingsWriter: SettingsWriting {
}.value
}
// MARK: CLI rail (wire-verified, the provisioner's posture) — nonisolated:
// they run inside Task.detached, off the actor.
private nonisolated static func setKey(
_ key: String,
_ value: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "set", key, value], timeout: timeout)
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
throw WriteError(message: "couldn't set \(key) on \(profile): \(excerpt(run))")
}
}
private nonisolated static func unsetKey(
_ key: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
// Absent already = the desired state (idempotent; exit 1 + not-set line).
let output = run.stdout + run.stderr
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
throw WriteError(message: "couldn't unset \(key) on \(profile): \(excerpt(run))")
}
}
/// Secrets never ride argv (`ps` reads live command lines) — this rail
/// only ever carries provider/model/effort/base_url. Errors keep the
/// same guarantee: excerpt content is CLI output, key text never
/// reaches `lastWriteError`.
private nonisolated static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(300))
}
// MARK: .env edit
/// Upsert `VAR=value` preserving every other line (hermes' own .env
@@ -272,7 +244,7 @@ struct HermesSettingsWriter: SettingsWriting {
}
envWriteLock.lock()
defer { envWriteLock.unlock() }
let envPath = (profileDir as NSString).appendingPathComponent(".env")
let envPath = ProfileLayout.envFile(in: profileDir)
let existing = (try? String(contentsOfFile: envPath, encoding: .utf8)) ?? ""
let updated = upsertEnv(varName: varName, value: value, in: existing)
do {