Files
museion/Museion/HermesSettingsWriter.swift
T
AlexKucera a8b158ca26
CI / ci (push) Canceled after 0s
refactor(profiles): one layout + config-set rail
#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
2026-11-10 11:32:47 +01:00

261 lines
11 KiB
Swift

//
// HermesSettingsWriter.swift
// Museion
//
// #136 (Profiles S3): the real SettingsWriting — surface model blocks via
// the engine's own CLI (`hermes -p <profile> config set/unset`, format
// owned by Hermes, wire-verified `✓` lines — the provisioner's posture),
// provider keys via direct `.env` edit per matching profile (one key fans
// out to every profile on that provider, no Keychain — ADR-0014), and the
// z.ai key type's endpoint family written through as `model.base_url`.
//
// Live-probed wire facts (2026-10-27): `config set` prints
// `✓ Set <key> = <value> in <path>` exit 0; `config unset` prints
// `✓ Unset <key> from <path>` exit 0 and exits 1 with
// `Config key not set: <key>` when already absent (idempotent success);
// `config get` prints the value exit 0, or the not-set line on stderr
// exit 1. Setting `model.provider` CLEARS a stale `model.base_url` — so
// the z.ai endpoint is (re)written after the provider, and key writes
// write it again (both paths converge on the same value).
//
import Foundation
/// The write-path seam (#135/#136). `HermesSettingsWriter` is the
/// production implementation — `hermes -p <profile> config set` for the
/// model block (validated keys, format owned by Hermes), `.env` fan-out for
/// provider keys (ADR-0014). Contract for implementers (finish-audit
/// #135, amended #136): the MODEL coalesces rapid edits per target before
/// calling (a superseded write never reaches the writer), but calls still
/// arrive tentative — implementations MUST hop off-main internally (the
/// CLI rail blocks) and keep surfaced error text free of key-bearing
/// content (`lastWriteError` renders verbatim). Secrets never ride argv
/// (`ps` reads live command lines).
@MainActor
protocol SettingsWriting: Sendable {
/// `zaiEndpoint`: the z.ai endpoint family when (and only when) the
/// config's provider is z.ai — written LAST because setting
/// `model.provider` clears a stale `model.base_url` (live-probed).
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig, zaiEndpoint: String?) async throws
/// The key lands in ALL THREE profiles' `.env` (a key entered before
/// any surface is on its provider still persists and pre-lands for any
/// later switch; inert vars are ignored by hermes for other providers).
/// `profiles` gates only the z.ai `base_url` write-through. An empty
/// `config.apiKey` leaves `.env` alone — the field sets, never removes.
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, profiles: [ProfileSurface]) async throws
/// The profile's live model block for hydration; nil = unreadable or a
/// provider Settings doesn't offer (the surface keeps its seed — never
/// stomped by defaults).
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)?
/// The provider's persisted key from the profiles' `.env` (first
/// non-empty wins); nil = nothing stored. Hydration fills the key
/// fields so a restart doesn't read as "no key" — the probe and the
/// masked field ride the STORED truth.
func readProviderKey(provider: ModelProvider) async throws -> String?
}
/// The inert writer: previews and pre-gate states; the UI runs over the
/// in-memory model.
struct NoopSettingsWriter: SettingsWriting {
func writeSurface(_: ProfileSurface, config _: SurfaceModelConfig, zaiEndpoint _: String?) async throws {}
func writeProviderKey(
provider _: ModelProvider,
config _: ProviderKeyConfig,
profiles _: [ProfileSurface],
) async throws {}
func readSurface(_: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
nil
}
func readProviderKey(provider _: ModelProvider) async throws -> String? {
nil
}
}
struct HermesSettingsWriter: SettingsWriting {
let hermesBinary: String?
var profileRoot: String = ProfileLayout.defaultRoot
struct WriteError: LocalizedError, Equatable {
let message: String
var errorDescription: String? {
message
}
}
// MARK: Surface writes (the profile's `model:` block)
func writeSurface(
_ surface: ProfileSurface,
config: SurfaceModelConfig,
zaiEndpoint: String?,
) async throws {
guard let hermesBinary else {
throw WriteError(message: "hermes binary not found — pass the engine gate first")
}
let binary = hermesBinary, profile = surface.profileName
try await Task.detached(priority: .utility) {
// 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 {
ops.append(.set(key: "model.reasoning_effort", value: effort.rawValue, force: false))
} else {
ops.append(.unset(key: "model.reasoning_effort"))
}
// 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
}
// MARK: Provider keys (.env fan-out + the z.ai endpoint family)
/// The key upserts into ALL THREE profiles' `.env` (it pre-lands for
/// any later provider switch; an EMPTY key leaves `.env` alone — the
/// field sets a key, it never removes one). The z.ai endpoint family
/// write-through (`model.base_url`, factsheet §1.1) rides only the
/// profiles currently on z.ai — a zai endpoint in an anthropic profile
/// would be wrong.
func writeProviderKey(
provider: ModelProvider,
config: ProviderKeyConfig,
profiles: [ProfileSurface],
) async throws {
// 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")
}
let root = profileRoot, key = config.apiKey, varName = provider.envVarName
let endpoint = writesBaseURL ? config.endpoint : nil
let binary = hermesBinary
try await Task.detached(priority: .utility) {
for surface in ProfileSurface.allCases {
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 HermesConfigRail.apply(
[.set(key: "model.base_url", value: endpoint, force: false)],
profile: surface.profileName,
binary: binary,
timeout: 30,
)
}
}
}.value
}
// MARK: Reads (hydration)
/// The profile's live `model:` block. nil = unreadable profile or a
/// provider Settings doesn't offer (a hand-configured kimi-coding
/// surface stays untouched rather than stomped by defaults).
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
guard let hermesBinary else { return nil }
let binary = hermesBinary, profile = surface.profileName
return await Task.detached(priority: .utility) { () -> (SurfaceModelConfig, String?)? in
func get(_ key: String) -> String? {
let run = EngineProbe.execute([binary, "-p", profile, "config", "get", key], timeout: 30)
guard run.exitCode == 0 else { return nil } // not set / unknown profile
let value = run.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
return value.isEmpty ? nil : value
}
guard let slug = get("model.provider"), let provider = ModelProvider(rawValue: slug) else { return nil }
return (
SurfaceModelConfig(
provider: provider,
model: get("model.default") ?? ProfileSurface.defaultModelID,
effort: get("model.reasoning_effort").flatMap(ReasoningEffort.init(rawValue:)),
),
get("model.base_url"),
)
}.value
}
/// The provider's persisted key: the first non-empty `VAR=` line
/// across the profiles' `.env` files (the write landed the same key in
/// all of them; one authoritative copy is enough to refill the field).
/// File reads only — no CLI spawn.
func readProviderKey(provider: ModelProvider) async throws -> String? {
let root = profileRoot, varName = provider.envVarName
return await Task.detached(priority: .utility) { () -> String? in
for surface in ProfileSurface.allCases {
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)
if !value.isEmpty {
return value
}
}
}
return nil
}.value
}
// MARK: .env edit
/// Upsert `VAR=value` preserving every other line (hermes' own .env
/// header comments and foreign keys survive byte-for-byte). Pure — the
/// fan-out tests pin the edges.
nonisolated static func upsertEnv(varName: String, value: String, in text: String) -> String {
let prefix = "\(varName)="
var lines = text.isEmpty
? []
: text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
if lines.last == "" {
lines.removeLast()
} // trailing-newline artifact; re-added below
lines = lines.filter { !$0.hasPrefix(prefix) }
lines.append(prefix + value)
return lines.joined(separator: "\n") + "\n"
}
/// 2026-10-28 audit fix: a pasted value containing a line break (or
/// NUL) is an env-file injection — "key\nOTHER_VAR=x" would land as a
/// real second line in every profile's `.env`. One guard at the shared
/// sink; the thrown error rides `lastWriteError`, nothing is written.
/// The lock serializes the read→upsert→write across concurrent
/// cross-provider key writes (same three files — last writer would
/// otherwise drop the other's var).
private nonisolated static let envWriteLock = NSLock()
private nonisolated static func upsertEnvFile(varName: String, value: String, profileDir: String, profile: String) throws {
guard !value.contains(where: { $0 == "\n" || $0 == "\r" || $0 == "\0" }) else {
throw WriteError(message: "\(varName) value contains a line break — not written")
}
envWriteLock.lock()
defer { envWriteLock.unlock() }
let envPath = ProfileLayout.envFile(in: profileDir)
let existing = (try? String(contentsOfFile: envPath, encoding: .utf8)) ?? ""
let updated = upsertEnv(varName: varName, value: value, in: existing)
do {
try FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
try updated.write(toFile: envPath, atomically: true, encoding: .utf8)
// Hermes' own .env files are 0600; a secret we just wrote must
// not be group/world-readable (String.write creates 0644).
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: envPath)
} catch {
throw WriteError(message: "couldn't write \(profile)/.env: \(error.localizedDescription)")
}
}
}