From a8b158ca26d4d502388ac2426b7cb8b7ffa9d7b0 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 10 Nov 2026 11:32:47 +0100 Subject: [PATCH] refactor(profiles): one layout + config-set rail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #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 --- AGENTS.md | 4 +- Museion/AGENTS.md | 8 +- Museion/HermesConfigRail.swift | 94 ++++++++++++ Museion/HermesSettingsWriter.swift | 82 ++++------- Museion/ProfileBackup.swift | 10 +- Museion/ProfileLayout.swift | 48 ++++++ Museion/ProfileProvisioner.swift | 82 +++++------ MuseionTests/AGENTS.md | 1 + MuseionTests/HermesConfigRailTests.swift | 139 ++++++++++++++++++ MuseionTests/HermesSettingsWriterTests.swift | 24 +++ MuseionTests/ProfileLayoutTests.swift | 35 +++++ MuseionTests/ProfileProvisionerTests.swift | 8 +- ...ue182-profilelayout-config-set-rail_log.md | 61 ++++++++ docs/devlog/INDEX.md | 1 + 14 files changed, 484 insertions(+), 113 deletions(-) create mode 100644 Museion/HermesConfigRail.swift create mode 100644 Museion/ProfileLayout.swift create mode 100644 MuseionTests/HermesConfigRailTests.swift create mode 100644 MuseionTests/ProfileLayoutTests.swift create mode 100644 docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md diff --git a/AGENTS.md b/AGENTS.md index 7034e90..096fa94 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6832 symbols, 32511 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (6864 symbols, 33665 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -184,6 +184,7 @@ This project is indexed by GitNexus as **museion** (6832 symbols, 32511 relation - Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33); the race persists in a chained read one command later — read the bundle from a LATER terminal invocation and retry the identical read once before diagnosing (#179) - A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177) - Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177) +- `test-without-building` tests the BUILT PRODUCTS, not the sources — a rename/edit landing after `build-for-testing` (e.g. while a long suite runs in background) leaves the green detached from the tree; rebuild + rerun for the definitive gate (#182) - Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33) - An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151) - When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift ` check of the pure logic still verify honestly (#134) @@ -207,6 +208,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-10 | [20261110-issue182-profilelayout-config-set-rail_log.md](docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md) | | 2026-11-10 | [20261110-issue181-provider-descriptor-pass-readiness_log.md](docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md) | | 2026-11-10 | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | | 2026-11-09 | [20261109-issue179-postsmodel-write-rail_log.md](docs/devlog/20261109-issue179-postsmodel-write-rail_log.md) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 6e28b83..4f5c2e2 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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); `` 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) → `/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 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 diff --git a/Museion/HermesConfigRail.swift b/Museion/HermesConfigRail.swift new file mode 100644 index 0000000..bf99dd9 --- /dev/null +++ b/Museion/HermesConfigRail.swift @@ -0,0 +1,94 @@ +// +// HermesConfigRail.swift +// Museion +// +// #182: the ONE owner of the `hermes -p 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 ` / `✓ Unset ` 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)) + } +} diff --git a/Museion/HermesSettingsWriter.swift b/Museion/HermesSettingsWriter.swift index 7b76e50..35bebe2 100644 --- a/Museion/HermesSettingsWriter.swift +++ b/Museion/HermesSettingsWriter.swift @@ -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 { diff --git a/Museion/ProfileBackup.swift b/Museion/ProfileBackup.swift index f6d4a7d..acea7ed 100644 --- a/Museion/ProfileBackup.swift +++ b/Museion/ProfileBackup.swift @@ -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) diff --git a/Museion/ProfileLayout.swift b/Museion/ProfileLayout.swift new file mode 100644 index 0000000..01edac0 --- /dev/null +++ b/Museion/ProfileLayout.swift @@ -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 + + /// `/` — 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") + } +} diff --git a/Museion/ProfileProvisioner.swift b/Museion/ProfileProvisioner.swift index 1ca7bba..3bd2dbf 100644 --- a/Museion/ProfileProvisioner.swift +++ b/Museion/ProfileProvisioner.swift @@ -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 = 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(), ) diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 70e9813..ff7d8d0 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -32,6 +32,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — - `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture). - `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on. - `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched). +- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists. - `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness). - `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates). - `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts. diff --git a/MuseionTests/HermesConfigRailTests.swift b/MuseionTests/HermesConfigRailTests.swift new file mode 100644 index 0000000..fcae220 --- /dev/null +++ b/MuseionTests/HermesConfigRailTests.swift @@ -0,0 +1,139 @@ +// +// HermesConfigRailTests.swift +// MuseionTests +// +// #182 — the config-set CLI contract's ONE pinning suite, over the shared +// fake-hermes double (makeFakeHermes, ProfileProvisionerTests.swift). The +// callers' suites pin only their own key lists. +// +// Scenario: The config-set wire is owned once — From user story #182 +// Given the provisioner and the settings writer both write config keys +// through `hermes -p config set` +// When either hands the rail its key list +// Then every write rides the exact argv (with --force where asked), is +// verified against the `✓ Set` line (not exit code alone), executes +// provider-first (switching providers clears stale inherited values), +// and a failed write surfaces key + profile + CLI excerpt. +// + +import Foundation +@testable import Museion +import Testing + +@Suite("HermesConfigRailTests") +struct HermesConfigRailTests { + @Test func `set argv rides the exact wire with force`() throws { + let binDir = provTempDir("rail") + let binary = makeFakeHermes(at: binDir, mode: "ok") + try HermesConfigRail.apply( + [ + .set(key: "model.provider", value: "anthropic", force: false), + .set(key: "model.extra_body.max_tokens", value: "24000", force: true), + ], + profile: "museion-pass1", + binary: binary, + timeout: 5, + ) + #expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [ + "-p museion-pass1 config set model.provider anthropic", + "-p museion-pass1 config set model.extra_body.max_tokens 24000 --force", + ]) + } + + @Test func `provider goes first whatever the caller s list order`() throws { + // model.provider clears a stale inherited base_url — the rail owns + // the rule; a caller can't order it wrong. Relative order holds. + let binDir = provTempDir("rail-order") + let binary = makeFakeHermes(at: binDir, mode: "ok") + try HermesConfigRail.apply( + [ + .set(key: "model.base_url", value: "https://x", force: false), + .unset(key: "model.reasoning_effort"), + .set(key: "model.default", value: "m", force: false), + .set(key: "model.provider", value: "zai", force: false), + ], + profile: "museion", + binary: binary, + timeout: 5, + ) + #expect(fakeHermesLog(binDir, "config-set-museion") == [ + "-p museion config set model.provider zai", + "-p museion config set model.base_url https://x", + "-p museion config set model.default m", + ]) + #expect(fakeHermesLog(binDir, "config-unset-museion") == [ + "-p museion config unset model.reasoning_effort", + ]) + } + + @Test func `unset of an absent key is idempotent success`() throws { + let binDir = provTempDir("rail-unset") + let binary = makeFakeHermes(at: binDir, mode: "ok") + try HermesConfigRail.apply([.unset(key: "model.reasoning_effort")], profile: "museion", binary: binary, timeout: 5) + } + + @Test func `a failed set throws naming key and profile with the cli excerpt`() { + let binDir = provTempDir("rail-fail") + try? "".write(toFile: binDir + "/config-set-fails", atomically: true, encoding: .utf8) + let binary = makeFakeHermes(at: binDir, mode: "ok") + do { + try HermesConfigRail.apply( + [.set(key: "model.default", value: "m", force: false)], + profile: "museion-pass2", + binary: binary, + timeout: 5, + ) + Issue.record("expected a throw") + } catch { + let failure = error as? HermesConfigRail.Failure + #expect(failure?.key == "model.default") + #expect(failure?.profile == "museion-pass2") + #expect(failure?.excerpt == "Error: config set exploded") + #expect(failure?.errorDescription == "couldn't set model.default on museion-pass2: Error: config set exploded") + } + } + + @Test func `a failed unset throws the structured failure`() { + // The fourth branch: neither ✓ Unset nor the not-set line. + let binDir = provTempDir("rail-unset-fail") + try? "".write(toFile: binDir + "/config-unset-fails", atomically: true, encoding: .utf8) + let binary = makeFakeHermes(at: binDir, mode: "ok") + do { + try HermesConfigRail.apply([.unset(key: "model.reasoning_effort")], profile: "museion", binary: binary, timeout: 5) + Issue.record("expected a throw") + } catch { + let failure = error as? HermesConfigRail.Failure + #expect(failure?.verb == "unset") + #expect(failure?.key == "model.reasoning_effort") + #expect(failure?.excerpt == "Error: config unset exploded") + } + } + + @Test func `a value that looks like an option is refused before any spawn`() { + // Free-text fields (model IDs, endpoints) feed the rail; a leading + // `-` is an option to the child CLI, never a value. + let binDir = provTempDir("rail-dash") + let binary = makeFakeHermes(at: binDir, mode: "ok") + do { + try HermesConfigRail.apply( + [.set(key: "model.default", value: "--force", force: false)], + profile: "museion", + binary: binary, + timeout: 5, + ) + Issue.record("expected a throw") + } catch { + let failure = error as? HermesConfigRail.Failure + #expect(failure?.key == "model.default") + #expect(failure?.excerpt == "value starts with '-' — not written") + } + #expect(fakeHermesLog(binDir, "config-set-museion").isEmpty) // nothing reached the CLI + } + + @Test func `excerpt caps at 500 chars`() { + // The #180 deliberate divergence (writer's old 300 is gone): pinned, + // not just commented. + let output = EngineProbe.ProcessOutput(exitCode: 1, stdout: String(repeating: "x", count: 900)) + #expect(HermesConfigRail.excerpt(output).count == 500) + } +} diff --git a/MuseionTests/HermesSettingsWriterTests.swift b/MuseionTests/HermesSettingsWriterTests.swift index fe7721d..61d1f9b 100644 --- a/MuseionTests/HermesSettingsWriterTests.swift +++ b/MuseionTests/HermesSettingsWriterTests.swift @@ -173,6 +173,30 @@ struct HermesSettingsWriterTests { } } + @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" diff --git a/MuseionTests/ProfileLayoutTests.swift b/MuseionTests/ProfileLayoutTests.swift new file mode 100644 index 0000000..b69aa35 --- /dev/null +++ b/MuseionTests/ProfileLayoutTests.swift @@ -0,0 +1,35 @@ +// +// ProfileLayoutTests.swift +// MuseionTests +// +// #182 — the profile layout's one pinning suite. +// +// Scenario: A layout change is one module + one suite — From user story #182 +// Given the Hermes profile layout (root, per-profile dir, .env, marker, +// gateway pid, skills dir) is owned by ProfileLayout alone +// When any layout fact moves (root renamed, a file renamed) +// Then ProfileLayout.swift plus exactly this suite change — the provisioner, +// the settings writer, and backup/restore derive every path through it and +// no literal profile-root string exists outside the layout module. +// + +import Foundation +@testable import Museion +import Testing + +@Suite("ProfileLayoutTests") +struct ProfileLayoutTests { + /// Pinned against LITERALS (not the layout's own inputs) so a fact change + /// fails here — this suite is the layout contract of record. + @Test func `root default is the hermes profiles dir`() { + #expect(ProfileLayout.defaultRoot == NSHomeDirectory() + "/.hermes/profiles") + } + + @Test func `per-profile path builders pin every layout fact`() { + #expect(ProfileLayout.profileDir("museion-pass1", root: "/r") == "/r/museion-pass1") + #expect(ProfileLayout.envFile(in: "/r/museion") == "/r/museion/.env") + #expect(ProfileLayout.configuredMarker(in: "/r/museion") == "/r/museion/.museion-provisioned") + #expect(ProfileLayout.gatewayPID(in: "/r/museion") == "/r/museion/gateway.pid") + #expect(ProfileLayout.skillsDir(in: "/r/museion") == "/r/museion/skills") + } +} diff --git a/MuseionTests/ProfileProvisionerTests.swift b/MuseionTests/ProfileProvisionerTests.swift index 6a35a2f..69c50e4 100644 --- a/MuseionTests/ProfileProvisionerTests.swift +++ b/MuseionTests/ProfileProvisionerTests.swift @@ -35,8 +35,8 @@ struct SeedSkill { /// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire /// strings). `config set [--force]` appends the exact argv to /// `/config-set-` and prints the verified "✓ Set …" -/// line. `/mcp-add-fails` / `config-set-fails` force the matching -/// failure. Every `profile create` name appends to +/// line. `/mcp-add-fails` / `config-set-fails` / `config-unset-fails` +/// force the matching failure. Every `profile create` name appends to /// `/profile-create-log`. /// #136: `config set` also records KEY=VALUE into /// `/config-store-` (dedup per key), and the fake speaks @@ -77,6 +77,10 @@ private func fakeHermesConfigCLI() -> String { fi if [[ "$1" == "-p" && "$3" == "config" && "$4" == "unset" ]]; then PROFILE="$2"; KEY="$5" + if [[ -f "${0:h}/config-unset-fails" ]]; then + print "Error: config unset exploded" + exit 1 + fi print -r -- "$*" >> "${0:h}/config-unset-$PROFILE" STORE="${0:h}/config-store-$PROFILE" if [[ -f "$STORE" && -n "$(grep -m1 "^${KEY}=" "$STORE")" ]]; then diff --git a/docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md b/docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md new file mode 100644 index 0000000..a4dd5f5 --- /dev/null +++ b/docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md @@ -0,0 +1,61 @@ +# ProfileLayout + one config-set rail — the Hermes profile's paths and CLI contract get owners + +> **Date:** 2026-11-10 +> **Type:** issue +> **Reference:** Closes #182 (settings cluster, 2026-11-09 architecture review) + +## Goal + +The profile-root string repeated five times across provisioner/settings-writer/backup and the `config set` CLI contract (argv shape, provider-first ordering, ✓-line verification) was hand-rolled twice. Give both a single owner so a layout or contract change is one module + one pinning suite. + +## What Was Done + +- `Museion/ProfileLayout.swift` (new) — `defaultRoot` + five per-profile path builders (`profileDir`, `envFile(in:)`, `configuredMarker(in:)`, `gatewayPID(in:)`, `skillsDir(in:)`). +- `Museion/HermesConfigRail.swift` (new) — the ONE `config set/unset` owner: argv (+`--force`), provider-first hoisting (`isProviderSet`, stable relative order), ✓-line verification, unset-idempotence, leading-dash value refusal, structured `Failure` (verb/key/profile/excerpt) consumed by both callers' error surfaces. +- Adopted: provisioner (`perform` default, `provisionSurface`, marker reads/writes, skills dir, `ProvisioningModel.runPass` fallback, `configureDefaults` now hands the rail provider/default/max_tokens), settings writer (`profileRoot` default, env fan-out + read paths, `writeSurface` hands the rail provider/default/effort-set-or-unset/base_url, `writeProviderKey` base_url write-through), backup (`perform` default, source dirs, `gateway.pid`, `BackupModel.runPass` fallback). +- Deleted: `ConfigWrite`, the writer's `setKey`/`unsetKey`/`excerpt` trio, the provisioner's private `excerpt` (rail exports one, #180-audited 500 cap). +- Pinning suites (new): `ProfileLayoutTests` (every builder against literals), `HermesConfigRailTests` (argv+force, provider-first hoisting, ✓-verification, unset-idempotence, failed-unset, dash-refusal, excerpt cap). Fake-hermes gained a `config-unset-fails` knob. Writer suite gained the whitespace-endpoint pin (both gates). +- Audit fixes (finish-audit fanout): cut `providerKey` constant, `Equatable` conformances, and the tautological layout pin (ponytail); trimmed-emptiness at both endpoint gates (learning #6's class); leading-dash value guard (security LOW-1 — free-text values can't reach the child CLI as options). +- DOX: `Museion/AGENTS.md` (ProfileLayout + HermesConfigRail map entries, configure/backup/settings bullets updated), `MuseionTests/AGENTS.md` suite map. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Rail hoists `model.provider` first, callers' lists stay literal | The ordering RULE is the rail's (a caller can't order it wrong); each caller's ordered key list is its own pin — the spec's "each caller keeps its own key list" | +| `Failure` throws structured fields, writer rethrows directly | `SettingsModel` renders `error.localizedDescription`; message shape byte-matches the old `WriteError`; provisioner maps to `Outcome.failed` with the excerpt | +| Excerpt cap 500 (not the writer's old 300) | The more-lossless twin wins when absorbing near-twins (#180); marked deliberate AND pinned (`excerpt(900).count == 500`) | +| `RESTORE.md` prose + ps-scan grep keep their literal path text | Prose that must outlive the app, and argv-text matching — not path derivations; documented in the layout header | +| `Op` renamed `Write` | SwiftLint 3-char identifier floor | +| Declined: precondition on layout builders | Every production call site passes the fixed `ProfileSurface` table (verified twice by reviewers) — YAGNI | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| First background full-suite ran on pre-rename products | `test-without-building` tests the BUILT products; the `Op`→`Write` rename landed after `build-for-testing` | Rebuilt + reran the definitive gate on the final tree (680/0 → 684/0 after audit pins) | +| One patch gutted `non-zai key write only touches env` | Inverted old/new strings in the patch — signature kept, body deleted | Re-read region, restored body + inserted the new whitespace pin | +| `detect-changes` listed untouched `ref/writing skills` files | Index-relative noise (mid-session analyze snapshot vs pre-audit index) | `git status` is the file-list truth; re-ran `analyze` after the audit edits | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/ProfileLayout.swift` | new — the profile layout owner (root default + 5 path builders) | +| `Museion/HermesConfigRail.swift` | new — the config set/unset CLI rail (argv, hoist, ✓-verify, dash guard, Failure) | +| `Museion/ProfileProvisioner.swift` | paths via layout; configureDefaults → rail; private excerpt deleted | +| `Museion/ProfileBackup.swift` | paths via layout (perform default, sources, gateway.pid, model fallback) | +| `Museion/HermesSettingsWriter.swift` | profileRoot default, env/base_url paths via layout; set/unset → rail; trimmed endpoint gates | +| `MuseionTests/ProfileLayoutTests.swift` | new — the layout pinning suite | +| `MuseionTests/HermesConfigRailTests.swift` | new — the rail contract suite (7 pins) | +| `MuseionTests/ProfileProvisionerTests.swift` | fake-hermes config-unset-fails knob | +| `MuseionTests/HermesSettingsWriterTests.swift` | whitespace-endpoint pin (both gates) | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass + gitnexus stats bump | + +## Open Items & Next Steps + +- None — all five acceptance criteria met and verified (full suite **684 passed / 0 failed** on the final tree; swiftformat/swiftlint clean; flip-cycle verified the dash + whitespace pins discriminate). + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 7b0f155..05de9fb 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-10 | issue | [20261110-issue182-profilelayout-config-set-rail_log.md](20261110-issue182-profilelayout-config-set-rail_log.md) | ProfileLayout owns every profile path; HermesConfigRail owns the config-set CLI contract; audited, 684 green (#182) | | 2026-11-10 | issue | [20261110-issue181-provider-descriptor-pass-readiness_log.md](20261110-issue181-provider-descriptor-pass-readiness_log.md) | Provider facts one table on the enum; one credential rail serves probe + readiness; readiness module; shared run guard (#181) | | 2026-11-10 | issue | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | One PostFrontmatter codec: lenient read + three byte-identical write postures, named eligibility predicates both gates consume | | 2026-11-09 | issue | [20261109-issue179-postsmodel-write-rail_log.md](20261109-issue179-postsmodel-write-rail_log.md) | One `performWrite` rail pairs every library write with one rescan and owns the strip; model owns the Home (#179) |