Files
museion/MuseionTests/HermesSettingsWriterTests.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

259 lines
10 KiB
Swift

//
// HermesSettingsWriterTests.swift
// MuseionTests
//
// #136 (Profiles S3) — scenario headers:
//
// ## Scenario: Settings writes reach the profile
// From user story #136
// Given the gate passed and a surface profile exists
// When the user changes that surface's model in Settings
// Then `hermes -p <profile> config get model.default` returns it and the
// write order keeps the z.ai endpoint family intact (provider first —
// switching clears base_url, live-probed).
//
// ## Scenario: one provider key fans out
// From user story #136
// Given profiles on provider z.ai
// When the user saves a z.ai key
// Then every fanned-out profile's .env carries GLM_API_KEY (foreign lines
// preserved, 0600) and model.base_url matches the key-type family.
//
import Foundation
@testable import Museion
import Testing
@Suite("HermesSettingsWriterTests")
struct HermesSettingsWriterTests {
/// Fresh temp dir + fake hermes per test (Real-Process pattern).
private func makeRig() -> (binDir: String, writer: HermesSettingsWriter) {
let binDir = provTempDir("s3writer")
let writer = HermesSettingsWriter(hermesBinary: makeFakeHermes(at: binDir, mode: "ok"), profileRoot: binDir + "/profiles")
return (binDir, writer)
}
@Test func `surface write round-trips through config get`() async throws {
let (binDir, writer) = makeRig()
let config = SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .high)
try await writer.writeSurface(.pass1, config: config, zaiEndpoint: ZaiKeyType.coding.endpoint)
let read = try await writer.readSurface(.pass1)
#expect(read?.config == config)
#expect(read?.baseURL == ZaiKeyType.coding.endpoint)
}
@Test func `surface write order is provider model effort then base_url`() async throws {
let (binDir, writer) = makeRig()
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .high),
zaiEndpoint: ZaiKeyType.coding.endpoint,
)
// base_url LAST: setting model.provider clears a stale base_url, so
// the endpoint family must be (re)written after the provider.
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
"-p museion-pass1 config set model.provider zai",
"-p museion-pass1 config set model.default glm-5.3",
"-p museion-pass1 config set model.reasoning_effort high",
"-p museion-pass1 config set model.base_url \(ZaiKeyType.coding.endpoint)",
])
}
@Test func `nil effort unsets and unset-when-absent stays success`() async throws {
let (binDir, writer) = makeRig()
// Never set: the unset is idempotent success, no throw.
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: nil),
zaiEndpoint: nil,
)
#expect(fakeHermesLog(binDir, "config-unset-museion-pass1") == [
"-p museion-pass1 config unset model.reasoning_effort",
])
// Set then unset: readSurface sees effort nil.
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: .low),
zaiEndpoint: nil,
)
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: nil),
zaiEndpoint: nil,
)
let read = try await writer.readSurface(.pass1)
#expect(read?.config.effort == nil)
}
@Test func `keys land in every env and the base url write-through rides the listed profiles`() async throws {
let (binDir, writer) = makeRig()
let root = binDir + "/profiles"
let chatEnv = root + "/museion/.env"
try? FileManager.default.createDirectory(atPath: root + "/museion", withIntermediateDirectories: true)
let original = """
# Per-profile secrets for this Hermes profile.
EXA_API_KEY=keep-me
"""
try original.write(toFile: chatEnv, atomically: true, encoding: .utf8)
try await writer.writeProviderKey(
provider: .zai,
config: ProviderKeyConfig(endpoint: ZaiKeyType.coding.endpoint, apiKey: "sk-zai-test"),
profiles: [.chat],
)
let updated = try String(contentsOfFile: chatEnv, encoding: .utf8)
#expect(updated.contains("GLM_API_KEY=sk-zai-test"))
#expect(updated.contains("# Per-profile secrets for this Hermes profile."))
#expect(updated.contains("EXA_API_KEY=keep-me"))
#expect(updated == HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "sk-zai-test", in: original))
let perms = try FileManager.default.attributesOfItem(atPath: chatEnv)[.posixPermissions] as? Int
#expect(perms == 0o600) // hermes' own .env posture; a secret must not be world-readable
// #136 dogfood amendment: the key lands in ALL THREE .env files —
// a key entered before any surface is on its provider still
// persists (inert vars are ignored for other providers).
for name in ["museion", "museion-pass1", "museion-pass2"] {
let env = try String(contentsOfFile: root + "/\(name)/.env", encoding: .utf8)
#expect(env.contains("GLM_API_KEY=sk-zai-test"))
}
// The zai endpoint family write-through rides ONLY the listed
// profiles — a zai endpoint in an anthropic profile would be wrong.
#expect(fakeHermesLog(binDir, "config-set-museion") == [
"-p museion config set model.base_url \(ZaiKeyType.coding.endpoint)",
])
#expect(fakeHermesLog(binDir, "config-set-museion-pass1").isEmpty)
#expect(fakeHermesLog(binDir, "config-set-museion-pass2").isEmpty)
// And it reads back — the restart round trip.
let readBack = try await writer.readProviderKey(provider: .zai)
#expect(readBack == "sk-zai-test")
}
@Test func `empty key leaves env bytes untouched but writes the endpoint family`() async throws {
let (binDir, writer) = makeRig()
let root = binDir + "/profiles"
try? FileManager.default.createDirectory(atPath: root + "/museion", withIntermediateDirectories: true)
let chatEnv = root + "/museion/.env"
try "GLM_API_KEY=existing\n".write(toFile: chatEnv, atomically: true, encoding: .utf8)
let before = try String(contentsOfFile: chatEnv, encoding: .utf8)
try await writer.writeProviderKey(
provider: .zai,
config: ProviderKeyConfig(endpoint: ZaiKeyType.coding.endpoint, apiKey: ""),
profiles: [.chat],
)
#expect(try String(contentsOfFile: chatEnv, encoding: .utf8) == before)
#expect(fakeHermesLog(binDir, "config-set-museion") == [
"-p museion config set model.base_url \(ZaiKeyType.coding.endpoint)",
])
}
@Test func `a line-broken key value is refused with nothing written`() async throws {
// 2026-10-28 audit pin: a pasted "key\nOTHER_VAR=x" is an env-file
// injection — the shared sink refuses it before any file is
// touched (the error rides lastWriteError in the app).
let (binDir, writer) = makeRig()
do {
try await writer.writeProviderKey(
provider: .zai,
config: ProviderKeyConfig(endpoint: "", apiKey: "a\nOPENAI_API_KEY=x"),
profiles: [],
)
Issue.record("expected a throw")
} catch {
let message = (error as? HermesSettingsWriter.WriteError)?.message ?? String(describing: error)
#expect(message.contains("line break"))
}
let root = binDir + "/profiles"
for name in ["museion", "museion-pass1", "museion-pass2"] {
#expect(!FileManager.default.fileExists(atPath: root + "/\(name)/.env"))
}
}
@Test func `whitespace-only endpoint is treated as empty at both gates`() async throws {
// Learning #6's class: raw isEmpty passes whitespace through; the
// gates mirror the trimmed emptiness the model side validates.
let (binDir, writer) = makeRig()
// Surface gate: a blank endpoint never rides base_url.
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil),
zaiEndpoint: " ",
)
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
"-p museion-pass1 config set model.provider zai",
"-p museion-pass1 config set model.default glm-5.3",
])
// Key gate: a blank zai endpoint skips the write-through (the key
// still fans out to .env).
try await writer.writeProviderKey(
provider: .zai,
config: ProviderKeyConfig(endpoint: " ", apiKey: "sk-z"),
profiles: [.chat],
)
#expect(fakeHermesLog(binDir, "config-set-museion").isEmpty)
}
@Test func `non-zai key write only touches env`() async throws {
let (binDir, writer) = makeRig()
let root = binDir + "/profiles"
try? FileManager.default.createDirectory(atPath: root + "/museion-pass1", withIntermediateDirectories: true)
try await writer.writeProviderKey(
provider: .anthropic,
config: ProviderKeyConfig(endpoint: "https://api.anthropic.com", apiKey: "sk-ant-test"),
profiles: [.pass1],
)
let env = try String(contentsOfFile: root + "/museion-pass1/.env", encoding: .utf8)
#expect(env == "ANTHROPIC_API_KEY=sk-ant-test\n")
#expect(fakeHermesLog(binDir, "config-set-museion-pass1").isEmpty)
}
@Test func `failing config set names the profile`() async {
let (binDir, writer) = makeRig()
try? "".write(toFile: binDir + "/config-set-fails", atomically: true, encoding: .utf8)
do {
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: nil),
zaiEndpoint: nil,
)
Issue.record("expected a throw")
} catch {
#expect("\(error)".contains("museion-pass1"))
}
}
@Test func `missing binary refuses writes and reads nil`() async throws {
let writer = HermesSettingsWriter(hermesBinary: nil)
await #expect(throws: (any Error).self) {
try await writer.writeSurface(.pass1, config: .surfaceDefault, zaiEndpoint: nil)
}
let read = try await writer.readSurface(.pass1)
#expect(read == nil)
}
// MARK: upsertEnv (pure)
@Test func `upsertEnv replaces in place appends fresh and keeps trailing newline`() {
#expect(
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "GLM_API_KEY=a\nOTHER=x\n")
== "OTHER=x\nGLM_API_KEY=b\n",
)
#expect(
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "# comment\n")
== "# comment\nGLM_API_KEY=b\n",
)
#expect(
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "")
== "GLM_API_KEY=b\n",
)
#expect(
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "GLM_API_KEY=a")
== "GLM_API_KEY=b\n",
)
}
}