refactor(profiles): one layout + config-set rail
CI / ci (push) Canceled after 0s
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:
1 parent
f49e4b6ca0
commit
a8b158ca26
14 files changed
+484
-113
No files matched your search
+5
-3
@@ -43,7 +43,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
||||
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
|
||||
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
|
||||
- Prose list machinery — `ProseList.swift` (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); `ProseListTextView.swift` — folds are VIEW state (buffer never changes; hidden scopes styled via `foldedAttributes`), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (`rekey`), the newline gate is `\.isNewline` NEVER literal `\n`/`\r` compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through `ProseDropBridge` into `ingestDrop` (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure `dropIndex` (sampling + bracket + binary search; the SwiftUI closure's `location` is unusable under this hosting, off-screen rects return garbage).
|
||||
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
|
||||
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: surface writes and the base_url write-through ride the HermesConfigRail (#182 — the writer only builds its key list: provider, default, effort set-or-unset, base_url LAST); provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection; paths via ProfileLayout). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
|
||||
- Focus mode — transient per-launch (no persistence); `FocusChrome` hover zones + overlay panels float over the measure, never push it; `CaretCentering` is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (`ColdTurkeySeat`/`ColdTurkeyDot`) mounts as overlays on the focused branch only.
|
||||
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
|
||||
- `AppGateState.museionHome` — fresh installs resolve once and PIN the winner: legacy `~/Documents/Museion` (dir-ness gated) → `<CloudDocs>/Museion` (resolved at the unprefixed path, never a hard-coded `iCloud~` form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched.
|
||||
@@ -57,12 +57,14 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
||||
|
||||
## Profile provisioning
|
||||
|
||||
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the engine's own CLI, provider first; success WIRE-VERIFIED `✓ Set` on stdout; marker-gated by `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
|
||||
- `ProfileLayout.swift` — #182: the ONE owner of the Hermes profile layout: `defaultRoot` (`~/.hermes/profiles`) and the per-profile path builders (`profileDir`, `envFile(in:)`, `configuredMarker(in:)`, `gatewayPID(in:)`, `skillsDir(in:)`). The provisioner, the settings writer, and backup derive every path through it — no literal profile-root string lives outside (RESTORE.md prose and the ps-scan grep pattern are text, not paths; pinned in ProfileLayoutTests).
|
||||
- `HermesConfigRail.swift` — #182: the ONE owner of the `hermes -p <profile> config set/unset` contract: argv shape (set value + `--force`), provider-first ordering (switching providers clears a stale inherited `model.base_url` — the rail hoists `model.provider` first, callers can't order it wrong), ✓-line verification (exit 0 AND `✓ Set`/`✓ Unset` on stdout; unset-of-absent = idempotent success). Callers hand it their own key lists: the provisioner seeds provider/default/max_tokens, the settings writer edits provider/default/effort/base_url. `Failure` carries key/profile/excerpt for both error surfaces; secrets never ride it (argv only carries non-secret keys).
|
||||
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the HermesConfigRail — provider first, wire-verified; marker-gated by the layout's `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
|
||||
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/`. 12 mentor skills ship; the master seeds all 12, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
|
||||
|
||||
## Profile backup
|
||||
|
||||
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
|
||||
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours; profile + pid paths via ProfileLayout, #182); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
|
||||
|
||||
## museion-tools MCP server
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//
|
||||
// HermesConfigRail.swift
|
||||
// Museion
|
||||
//
|
||||
// #182: the ONE owner of the `hermes -p <profile> config set/unset` CLI
|
||||
// contract — argv shape, provider-first ordering (switching providers
|
||||
// clears stale inherited values — live-probed), and ✓-line verification.
|
||||
// The provisioner (seeds provider/default/max_tokens) and the settings
|
||||
// writer (edits provider/default/effort/base_url) hand the rail their own
|
||||
// key lists; the mechanism and ordering rule live only here (pinned once
|
||||
// in HermesConfigRailTests over the shared fake-hermes double).
|
||||
//
|
||||
// Secrets never ride this rail (`ps` reads live command lines) — it only
|
||||
// ever carries provider/model/effort/base_url values.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
nonisolated enum HermesConfigRail {
|
||||
/// One CLI write: a set (key/value, `--force` for keys some engine
|
||||
/// versions don't recognize), or an unset.
|
||||
enum Write: Sendable {
|
||||
case set(key: String, value: String, force: Bool)
|
||||
case unset(key: String)
|
||||
}
|
||||
|
||||
/// A wire-verified write that failed — structured so each caller keeps
|
||||
/// its own error surface (the provisioner's Outcome excerpt; the
|
||||
/// writer's `lastWriteError` text).
|
||||
struct Failure: Error, Sendable, LocalizedError {
|
||||
let verb: String
|
||||
let key: String
|
||||
let profile: String
|
||||
let excerpt: String
|
||||
|
||||
var errorDescription: String? {
|
||||
"couldn't \(verb) \(key) on \(profile): \(excerpt)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes the ops provider-first, each wire-verified: exit 0 AND the
|
||||
/// `✓ Set <key>` / `✓ Unset <key>` line on stdout — a CLI that exits 0
|
||||
/// while writing nothing must not count as configured. An unset of an
|
||||
/// absent key is idempotent success (exit 1 + the not-set line).
|
||||
static func apply(_ writes: [Write], profile: String, binary: String, timeout: TimeInterval) throws {
|
||||
// Provider first, relative order otherwise preserved: `config set
|
||||
// model.provider` clears a stale inherited `model.base_url`, so
|
||||
// everything after it sees the new provider.
|
||||
let ordered = writes.filter(isProviderSet) + writes.filter { !isProviderSet($0) }
|
||||
for write in ordered {
|
||||
switch write {
|
||||
case let .set(key, value, force):
|
||||
// Trust boundary: free-text fields (model IDs, endpoints)
|
||||
// feed this rail, and a leading `-` is an option to the
|
||||
// child CLI, never a value — no legitimate value starts
|
||||
// with a dash (learning #6's class: gate at the seam).
|
||||
guard !value.hasPrefix("-") else {
|
||||
throw Failure(verb: "set", key: key, profile: profile, excerpt: "value starts with '-' — not written")
|
||||
}
|
||||
var arguments = [binary, "-p", profile, "config", "set", key, value]
|
||||
if force {
|
||||
arguments.append("--force")
|
||||
}
|
||||
let run = EngineProbe.execute(arguments, timeout: timeout)
|
||||
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
|
||||
throw Failure(verb: "set", key: key, profile: profile, excerpt: excerpt(run))
|
||||
}
|
||||
case let .unset(key):
|
||||
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
|
||||
let output = run.stdout + run.stderr
|
||||
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
|
||||
throw Failure(verb: "unset", key: key, profile: profile, excerpt: excerpt(run))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func isProviderSet(_ write: Write) -> Bool {
|
||||
if case let .set(key, _, _) = write {
|
||||
key == "model.provider"
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors carry CLI output only — key-bearing text never reaches error
|
||||
/// surfaces. #180 audit: the rail absorbed the two callers' excerpts and
|
||||
/// keeps the provisioner's 500-char cap (the more-lossless twin; the
|
||||
/// writer's old 300 was the outlier), a deliberate divergence.
|
||||
static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
|
||||
let text = run.stdout.isEmpty ? run.stderr : run.stdout
|
||||
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500))
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -54,19 +54,19 @@ nonisolated enum ProfileBackup {
|
||||
/// hasn't landed yet) is simply absent from the stamp; only NO profile
|
||||
/// at all skips.
|
||||
/// - Parameters:
|
||||
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
|
||||
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
|
||||
/// - backupsRoot: snapshots base dir (tests inject; default Museion's
|
||||
/// Application Support / Backups).
|
||||
/// - now: clock injection for the age check (tests pass fixed dates).
|
||||
static func perform(
|
||||
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
|
||||
profileRoot: String = ProfileLayout.defaultRoot,
|
||||
backupsRoot: String = defaultBackupsRoot(),
|
||||
now: Date = Date(),
|
||||
psScan: () -> Bool = psContainsMuseion,
|
||||
) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
let sources = ProfileSurface.allCases
|
||||
.map { (profileRoot as NSString).appendingPathComponent($0.profileName) }
|
||||
.map { ProfileLayout.profileDir($0.profileName, root: profileRoot) }
|
||||
.filter { fileManager.fileExists(atPath: $0) }
|
||||
guard !sources.isEmpty else {
|
||||
logInfo("skipped — no profile found")
|
||||
@@ -174,7 +174,7 @@ nonisolated enum ProfileBackup {
|
||||
/// the ps scan is global (one scan answers for every surface profile),
|
||||
/// so the caller evaluates it once.
|
||||
private static func idleProfileDir(_ profileDir: String) -> Bool {
|
||||
let pidPath = (profileDir as NSString).appendingPathComponent("gateway.pid")
|
||||
let pidPath = ProfileLayout.gatewayPID(in: profileDir)
|
||||
if let pid = parsePID(fromFile: pidPath), kill(pid, 0) == 0 {
|
||||
return false
|
||||
}
|
||||
@@ -311,7 +311,7 @@ final class BackupModel {
|
||||
guard !running else { return }
|
||||
running = true
|
||||
defer { running = false }
|
||||
let profileRoot = profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath
|
||||
let profileRoot = profileRoot ?? ProfileLayout.defaultRoot
|
||||
let backupsRoot = backupsRoot ?? ProfileBackup.defaultBackupsRoot()
|
||||
lastOutcome = await Task.detached(priority: .utility) {
|
||||
ProfileBackup.perform(profileRoot: profileRoot, backupsRoot: backupsRoot)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//
|
||||
// ProfileLayout.swift
|
||||
// Museion
|
||||
//
|
||||
// #182: the ONE owner of the Hermes profile layout — the root default and
|
||||
// every per-profile path derivation. The provisioner, the settings writer,
|
||||
// and backup/restore build paths only through here; no literal
|
||||
// profile-root string lives outside this module (pinned in
|
||||
// ProfileLayoutTests — a layout change is this module + that one suite).
|
||||
//
|
||||
// Deliberately NOT layout-owned: the RESTORE.md copy names
|
||||
// `~/.hermes/profiles` as prose (static text that must outlive the app),
|
||||
// and the backup ps scan greps argv text, not filesystem paths.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
nonisolated enum ProfileLayout {
|
||||
/// The profiles base dir (`~/.hermes/profiles`; tests inject their own root).
|
||||
static let defaultRoot = ("~/.hermes/profiles" as NSString).expandingTildeInPath
|
||||
|
||||
/// `<root>/<profileName>` — the profile's home dir.
|
||||
static func profileDir(_ profile: String, root: String) -> String {
|
||||
(root as NSString).appendingPathComponent(profile)
|
||||
}
|
||||
|
||||
/// The profile's `.env` — provider keys (the writer's fan-out surface).
|
||||
static func envFile(in profileDir: String) -> String {
|
||||
(profileDir as NSString).appendingPathComponent(".env")
|
||||
}
|
||||
|
||||
/// The configured marker — written by the provisioner after the config
|
||||
/// rail completes; marker-gating keeps a re-pass from stomping a user's
|
||||
/// later Settings change.
|
||||
static func configuredMarker(in profileDir: String) -> String {
|
||||
(profileDir as NSString).appendingPathComponent(".museion-provisioned")
|
||||
}
|
||||
|
||||
/// The engine gateway's pid file (the backup liveness gate reads it).
|
||||
static func gatewayPID(in profileDir: String) -> String {
|
||||
(profileDir as NSString).appendingPathComponent("gateway.pid")
|
||||
}
|
||||
|
||||
/// The profile's skills dir — the symlink farm into the ONE master copy.
|
||||
static func skillsDir(in profileDir: String) -> String {
|
||||
(profileDir as NSString).appendingPathComponent("skills")
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user