feat(profiles): registry + provisioning ×3
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Profiles S1 (#134, ADR-0014): one gate pass provisions all three surface profiles — museion adopted in place (never reconfigured; its glm-5.3-max stays the user's), museion-pass1/-pass2 created fresh with the #132 sonnet defaults + 24k budget via the hermes 'config set' CLI rail, marker-gated so a re-pass is a no-op and Settings changes survive; a failed provision names the profile on the #48 card. Skills move to ONE master copy under Application Support, symlinked per profile per the #133 allocation (P1 9 · P2 8 · Chat 10); copy-era dirs migrate on byte-match (.DS_Store-tolerant, symlink-refusing), diverged dirs stay copies, user skills untouched (G3a). Backup widens to one three-subdir stamp, any-live-skip-all; RESTORE.md names the three folders. Two review rounds (standards+spec, then finish-audit ponytail/ security/general) caught and fixed: the dead .DS_Store leniency in treesByteMatch, exit-code-only config-set trust, the swallowed marker write (defaults-stomp re-arm), symlink-following in the untrusted tree, and a fixture-skewed count pin. Suite: 412 passed / 414 (fork flake green in isolation 16/16; UI launch = pre-existing testmanagerd flake, failed identically pre-change). DOX: Museion/AGENTS.md, MuseionTests/AGENTS.md, ref/writing skills/AGENTS.md rewritten. Closes #134
This commit is contained in:
1 parent
2032534305
commit
610f8789bd
15 files changed
+1292
-232
No files matched your search
+7
-7
@@ -48,19 +48,19 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` fires provisioning (#47) in parallel on pass.
|
||||
- Tests: `MuseionTests/EngineGateTests.swift` builds fake `hermes` shell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records.
|
||||
|
||||
## Profile provisioning (S2.1, tickets #43–#48)
|
||||
## Profile provisioning (S2.1 #43–#48; #134 Profiles S1)
|
||||
|
||||
- `ProfileProvisioner.swift` — `ProfileProvisioner` (nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawn `hermes profile create museion --no-alias --no-skills` only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: `seed-manifest.txt` in the payload root is the inclusion list (blank/`#` lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping `skills/`); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned `.`-prefixed temp dirs from an interrupted copy are swept at pass start; `.DS_Store` purged from copies. One os_log line per pass (`seeded writing skills: <name> <version>, … (N copied, M present)`) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). `ProvisioningModel` (@MainActor @Observable): runs the pass off-main, guards stacking, records `lastFailure` (phase-named copy + excerpt); failure never re-raises the gate. **#23 register phase:** after a seeded pass (and only when BOTH `hermesBinary` and `serverBinaryPath` are non-nil — production always has both after a gate pass; nil = the test-injection seam, skipped with one os_log line), `registerTools` runs `hermes -p museion mcp list` — "museion-tools" present → idempotent skip (a stale binary path after an app move is refreshed manually via `hermes -p museion mcp remove museion-tools` — ponytail ceiling) — else `hermes -p museion mcp add museion-tools --command <serverBinaryPath> --args --serve-mcp` with stdin fed repeated "y" lines (the CLI's final "Enable all tools? [Y/n]" prompt cancels on EOF, and profile-startup stdin consumers can burn a line — observed live; one y cancelled the save). Success = exit 0 + stdout "Saved 'museion-tools'"; anything else → `.failed(phase: .register)` through the #48 rail. The add LIVE-PROBES the server (spawns the app binary `--serve-mcp` — the headless launcher branch).
|
||||
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented` = `hasFailure && gateDismissed`, where `gateDismissed` is set in the gate sheet's `onDismiss` — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into `@State` so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (`deferFailure`) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning never hand-writes the profile config — the ONLY writer of an `mcp_servers` entry is the `hermes mcp add` CLI rail (#44 invariant as amended by #23/ADR-0008: config.yaml stays byte-identical through provisioning passes; registration itself goes through the engine's own command, test-pinned).
|
||||
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills seeded; `ste-writing`/`writing-for-agents` ship but never seed.
|
||||
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `<binaryDir>/profiles/<name>`; **#23:** the fake also speaks `-p museion mcp list`/`mcp add` — marker file for "already registered", invocation log asserting the exact add command line, one stdin line read, `mcp-add-fails` reject knob), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload; registration tests: fresh pass adds via the CLI with the exact command line, already-registered skips, probe failure → `.failed(.register)`.
|
||||
- `ProfileProvisioner.swift` — the #134 surface registry + the provisioner. **`ProfileSurface`** (nonisolated enum, chat/pass1/pass2; declaration order = provision order — chat first so the resident surface is healthy before any pass-profile failure stops the loop): `profileName` (museion adopted in place / museion-pass1 / museion-pass2, Sessions rides Chat per #126), `allocatedSkills` (#133 table: P1 9 · P2 8 · Chat 10, persona pair never co-occurring), `init?(passKind:)` (the PassKind→profile seam), and the #132 fresh-seed defaults as constants (`defaultModelProvider` anthropic, `defaultModelID` claude-sonnet-5-5, `outputBudgetTokens` 24000 — reasoning_effort never written). **`ProfileProvisioner.perform`** (nonisolated): one idempotent pass = master-seed + per-surface phases. Phase 0 master: every manifest skill seeded additively as REAL dirs into the ONE master copy at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable) — `seed-manifest.txt` is still the shipped-set list (kebab-validated at the trust boundary); temp+rename per skill, never touch present ones, orphaned `.`-temps swept, `.DS_Store` purged. Then per surface (first failure wins; the next pass heals): **create** — dir-check first, `hermes profile create <name> --no-alias --no-skills` only when missing (#43 already-exists semantics); `museion` is adopted, never re-created (ADR-0014). **configure** — the #132 defaults written through the engine's own CLI (`hermes -p <profile> config set model.provider/model.default/model.extra_body.max_tokens 24000 --force`, provider first — switching providers clears a stale inherited base_url, live-probed; #128: never rely on create-time inheritance); success is WIRE-VERIFIED (`exit 0` + `✓ Set <key>` on stdout — not exit code alone, finish-audit) and a marker write that fails surfaces as a configure-phase failure (an unrecorded configure must not count as done). MARKER-GATED by `.museion-provisioned` in the profile dir so a re-pass is a no-op and a user's later Settings change survives: runs for fresh creates and for an unconfigured PASS profile (interrupted before its marker landed — Retry heals); the adopted museion is NEVER configured (its glm-5.3-max is the user's until Settings switches it). **skills** — per profile, symlink each manifest name into the master: an existing link (live or dangling) is never retargeted; a copy-era REAL dir swaps to a symlink only on `treesByteMatch` against the MASTER (the link's target — identical to the payload on first seed; `.DS_Store` filtered from both listings so a Finder-browsed dir still migrates) with move-aside → link → delete-aside, restored on failure; a diverged dir stays a copy, untracked/user skills never touched (G3a); a missing skill links only when the surface ALLOCATES it (curation). **register** — museion-tools per profile (ADR-0008 amendment): `-p <profile> mcp list` skip / `mcp add` with repeated-y stdin, both binaries required (nil = test seam). `Outcome.seeded(copied:present:)` aggregates master copies + links; `.failed(profile:phase:excerpt:)` names the profile (nil for payload-level failures) — phases create/copy/register/configure. `ProvisioningModel` unchanged in shape; `runPass` gained `masterRoot`.
|
||||
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented`); phase rawValue is the title with the failing profile name in mono beneath (#134 — with three profiles, "which one?" is the first question; nil profile hides the row), excerpt behind Technical details; card snapshots the failure into `@State`; Retry re-runs the whole idempotent pass, Not Now defers to next launch. Provisioning still never hand-writes profile config — mcp registration AND the model defaults both go through the engine's own `hermes` CLI (#44 as amended by #23/ADR-0008 and #134/ADR-0014: the provisioner writes no config.yaml bytes itself, but a FRESH pass profile's config.yaml IS legitimately written by `config set` — byte-identity now holds only for adopted/engine-owned configs, test-pinned).
|
||||
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills ship; the master seeds all 11, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
|
||||
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profiles at `<binaryDir>/profiles/<name>`, speaks `-p <any-profile> mcp list`/`mcp add` with per-profile marker/invocation files and `config set` with a per-profile argv log + `config-set-fails`/`mcp-add-fails` knobs, logs every `profile create`), injected profile/payload/master dirs, manifest ↔ payload correspondence. **#134:** `ProfileSurfaceTests.swift` (own file) pins the registry (names/order, PassKind mapping, allocation counts + persona split, defaults, allocation ⊆ bundled manifest), ×3 provisioning with exact config-set command lines, master-once + per-allocation symlinks, re-pass no-op (config-set log byte-stable, no re-creates), adopted-museion untouched, marker heal/no-stomp, failing provision names the profile, configure-phase failure. `ProfileSkillMigrationTests.swift` (own file) pins the byte-match migration (browsed dir with `.DS_Store` still migrates, content identical through the swap; diverged stays a copy; untracked untouched; a symlinked entry inside a copy-era dir refuses the match — never followed, finish-audit). Failure-path tests in `ProfileProvisionerFailureTests.swift` (config.yaml byte-identity through failed/nil-skip/CLI-registering passes, fresh-profile case in its own test, copy-phase catch, path traversal, orphan sweep).
|
||||
|
||||
## Profile backup (S2.6, #15 map / #50)
|
||||
|
||||
- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on gate pass **after** the provisioning pass finishes (await chain in `ContentView.onEnginePass` — a failed provision doesn't skip the backup). Liveness gate first: `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + `ps ax -o command=` scan for `profiles/museion` / `-p museion` (`psScan` injectable for tests); either live → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: recursive enumerator with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars. Directories are `createDirectory`d, files `copyItem`d (the enumerator re-yields children — whole-subtree copyItem would collide); a file vanishing mid-copy is skipped. Install: copy into `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, prune past 7 after a successful rename. `RESTORE.md` (manual Finder copy-back instructions) written once into the Backups root. Failure = one os_log line, never an alert (contrast #45's provisioning card); constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`).
|
||||
- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on gate pass **after** the provisioning pass finishes (await chain in `ContentView.onEnginePass` — a failed provision doesn't skip the backup). **#134/#129 — one stamp, three subdirs:** the sources are the three surface profiles from `ProfileSurface.allCases`; a missing profile dir is simply absent from the stamp (only NO profile at all → `.skippedProfileMissing`); NEVER the profiles root (non-Museion profiles are not ours to back up). Any-live-skip-all: every existing profile dir must be idle or the WHOLE stamp skips (one stamp = one consistent point in time) — per-dir `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + the `ps ax -o command=` scan for `profiles/museion` / `-p museion` (already substring-matches the pass profiles; `psScan` injectable for tests) → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: per profile into `<stamp>/<name>/`, recursive walk with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars; dir symlinks resolve (`fileExists(isDirectory:)` follows) so profile skill symlinks snapshot as content, keeping restores self-contained (#133 folded). A file vanishing mid-copy is skipped. Install: copy into `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, prune past 7 after a successful rename. `RESTORE.md` documents the three folders (written once into the Backups root). Failure = one os_log line, never an alert; constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`).
|
||||
- `BackupModel` (@MainActor @Observable): app-scoped (`AppGateState.backup`), runs the pass off-main, guards stacking, records `lastOutcome` (informational only — no UI).
|
||||
- UI: Help → **Open Backup Folder** (`OpenBackupFolderButton` in `MuseionApp.swift`) reveals the Backups root in Finder; restore docs live in `RESTORE.md` beside the snapshots.
|
||||
- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan: liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept).
|
||||
- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan (`makeProfileFixture(at:name:)` builds any profile): liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept). **#134:** one stamp carries all three profile dirs with RESTORE.md naming them, a live PASS-profile pid skips the whole stamp (nothing half-written), missing pass profiles snapshot the rest.
|
||||
|
||||
## museion-tools MCP server (S2.4, #23)
|
||||
|
||||
|
||||
@@ -172,14 +172,21 @@ struct ProvisioningFailureCard: View {
|
||||
@State private var failure: ProfileProvisioner.Outcome?
|
||||
|
||||
var body: some View {
|
||||
if let failure, case let .failed(phase, excerpt) = failure {
|
||||
if let failure, case let .failed(profile, phase, excerpt) = failure {
|
||||
VStack(spacing: 14) {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.font(.system(size: 30))
|
||||
.foregroundStyle(.orange)
|
||||
Text(phase.rawValue)
|
||||
.font(.title3)
|
||||
Text("Museion couldn't finish setting up the mentor's writing profile. Nothing is lost — the setup is safe to run again.")
|
||||
if let profile {
|
||||
// #134: the card names the failing profile — with three
|
||||
// surface profiles, "which one?" is the first question.
|
||||
Text(profile)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.foregroundStyle(.tertiary)
|
||||
}
|
||||
Text("Museion couldn't finish setting up the writing profiles. Nothing is lost — the setup is safe to run again.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
|
||||
+45
-20
@@ -4,6 +4,10 @@
|
||||
//
|
||||
// S2.6 daily profile backup (#50): liveness-gated, once-a-day FileManager
|
||||
// copy of the museion profile into timestamped snapshots, last 7 kept.
|
||||
// #134 (Profiles S1, #129): one stamp carries all three surface profiles
|
||||
// as subdirs — museion, museion-pass1, museion-pass2. Any live engine
|
||||
// skips the WHOLE stamp; never the profiles root (non-Museion profiles
|
||||
// are not ours to back up).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@@ -43,8 +47,12 @@ nonisolated enum ProfileBackup {
|
||||
case failed
|
||||
}
|
||||
|
||||
/// One backup pass. Runs on gate pass, sequenced after the provisioning
|
||||
/// pass finishes (success or failure — a failed provision doesn't skip it).
|
||||
/// One backup pass over the three surface profiles (#129/#134): one
|
||||
/// stamp, three subdirs. Runs on gate pass, sequenced after the
|
||||
/// provisioning pass finishes (success or failure — a failed provision
|
||||
/// doesn't skip it). A profile dir that doesn't exist (provisioning
|
||||
/// 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`).
|
||||
/// - backupsRoot: snapshots base dir (tests inject; default Museion's
|
||||
@@ -57,12 +65,19 @@ nonisolated enum ProfileBackup {
|
||||
psScan: () -> Bool = psContainsMuseion,
|
||||
) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
let source = (profileRoot as NSString).appendingPathComponent("museion")
|
||||
guard fileManager.fileExists(atPath: source) else {
|
||||
logInfo("skipped — museion profile missing")
|
||||
let sources = ProfileSurface.allCases
|
||||
.map { (profileRoot as NSString).appendingPathComponent($0.profileName) }
|
||||
.filter { fileManager.fileExists(atPath: $0) }
|
||||
guard !sources.isEmpty else {
|
||||
logInfo("skipped — no profile found")
|
||||
return .skippedProfileMissing
|
||||
}
|
||||
guard engineIdle(profileDir: source, psScan: psScan) else {
|
||||
// Any-live-skip-all (#129): one stamp = one consistent point in time.
|
||||
// The ps scan already substring-matches the pass profiles
|
||||
// (`profiles/museion` / `-p museion`), so ONE scan answers for all
|
||||
// (finish-audit: hoisted — per-dir evaluation spawned it up to 3×);
|
||||
// the pid check stays per dir.
|
||||
guard !psScan(), sources.allSatisfy({ idleProfileDir($0) }) else {
|
||||
logInfo("skipped — engine running (liveness gate)")
|
||||
return .skippedEngineRunning
|
||||
}
|
||||
@@ -82,15 +97,18 @@ nonisolated enum ProfileBackup {
|
||||
try fileManager.createDirectory(atPath: backupsRoot, withIntermediateDirectories: true)
|
||||
writeRestoreDocIfMissing(into: backupsRoot)
|
||||
try fileManager.createDirectory(atPath: tempDir, withIntermediateDirectories: true)
|
||||
// Snapshot layout: <stamp>/museion/<profile contents> — the folder
|
||||
// name travels with the snapshot, so restore is one copy-back.
|
||||
let payloadDir = (tempDir as NSString).appendingPathComponent("museion")
|
||||
try fileManager.createDirectory(atPath: payloadDir, withIntermediateDirectories: true)
|
||||
try copyTree(from: source, to: payloadDir)
|
||||
// Snapshot layout (#129): <stamp>/{museion, museion-pass1,
|
||||
// museion-pass2}/<profile contents> — the folder name travels with
|
||||
// the snapshot, so restore is one copy-back.
|
||||
for source in sources {
|
||||
let payloadDir = (tempDir as NSString).appendingPathComponent((source as NSString).lastPathComponent)
|
||||
try fileManager.createDirectory(atPath: payloadDir, withIntermediateDirectories: true)
|
||||
try copyTree(from: source, to: payloadDir)
|
||||
}
|
||||
// Atomic install (seed-phase pattern): rename into place, then prune.
|
||||
try fileManager.moveItem(atPath: tempDir, toPath: finalDir)
|
||||
prune(backupsRoot: backupsRoot)
|
||||
logInfo("snapshot complete: \(stamp)")
|
||||
logInfo("snapshot complete: \(stamp) (\(sources.count) profiles)")
|
||||
return .snapshotted(stamp: stamp)
|
||||
} catch {
|
||||
try? fileManager.removeItem(atPath: tempDir)
|
||||
@@ -112,19 +130,19 @@ nonisolated enum ProfileBackup {
|
||||
let path = (backupsRoot as NSString).appendingPathComponent("RESTORE.md")
|
||||
guard !FileManager.default.fileExists(atPath: path) else { return }
|
||||
let doc = """
|
||||
# Restoring the writing profile
|
||||
# Restoring the writing profiles
|
||||
|
||||
Each folder here is a full snapshot of the writing profile \
|
||||
(`~/.hermes/profiles/museion`), taken once a day when Museion launches.\
|
||||
The 7 most recent are kept.
|
||||
Each folder here is a full snapshot of Museion's writing profiles \
|
||||
(`~/.hermes/profiles/museion`, `museion-pass1`, and `museion-pass2`),\
|
||||
taken once a day when Museion launches. The 7 most recent are kept.
|
||||
|
||||
## Restore (manual, v1)
|
||||
|
||||
1. Quit Museion (and any running Hermes engine).
|
||||
2. Pick the newest healthy snapshot folder.
|
||||
3. Copy the `museion` folder inside it back to `~/.hermes/profiles/`,\
|
||||
replacing the damaged one (rename the old one aside first if you want\
|
||||
it kept).
|
||||
3. Copy the profile folders inside it back to `~/.hermes/profiles/`,\
|
||||
replacing the damaged ones (rename the old ones aside first if you\
|
||||
want them kept).
|
||||
4. Relaunch Museion.
|
||||
|
||||
Note: logs, caches, and lock files are excluded from snapshots by\
|
||||
@@ -149,11 +167,18 @@ nonisolated enum ProfileBackup {
|
||||
/// the file can be stale) + `ps ax -o command=` scan for `profiles/museion`
|
||||
/// or `-p museion`. Either signal live → the engine is running.
|
||||
static func engineIdle(profileDir: String, psScan: () -> Bool = psContainsMuseion) -> Bool {
|
||||
idleProfileDir(profileDir) && !psScan()
|
||||
}
|
||||
|
||||
/// The per-dir half of the liveness gate: gateway.pid liveness only —
|
||||
/// 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")
|
||||
if let pid = parsePID(fromFile: pidPath), kill(pid, 0) == 0 {
|
||||
return false
|
||||
}
|
||||
return !psScan()
|
||||
return true
|
||||
}
|
||||
|
||||
/// The gateway's pid file is a JSON line (`{"pid":…, "hermes_home":"…"}` —
|
||||
|
||||
@@ -4,14 +4,84 @@
|
||||
//
|
||||
// S2.1 provisioning (#47): create the museion profile via the Hermes CLI,
|
||||
// then seed the bundled writing skills additively (#43/#45/#46), then
|
||||
// register museion-tools via `hermes -p museion mcp add` (#23 slice 2 —
|
||||
// register museion-tools via `hermes -p <profile> mcp add` (#23 slice 2 —
|
||||
// the CLI rail only, never hand-written mcp_servers YAML, #44).
|
||||
//
|
||||
// #134 (Profiles S1, ADR-0014): one pass provisions ALL THREE surface
|
||||
// profiles — `museion` adopted in place, `museion-pass1/2` created fresh
|
||||
// with the #132 defaults written via `hermes -p <profile> config set`
|
||||
// (#128: create-time inheritance follows the ACTIVE profile and never
|
||||
// carries keys — probed; never rely on it). Skills: ONE master copy under
|
||||
// Application Support, symlinked into each profile per the #133 allocation;
|
||||
// copy-era dirs migrate to symlinks only on byte-match against the master
|
||||
// (the link's target — identical to the payload on first seed, and a
|
||||
// lagging master after an app update keeps the copy rather than silently
|
||||
// changing skill content through the swap; G3a).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
import os
|
||||
|
||||
/// #134 (Profiles S1): the static surface→profile map (ADR-0014). Sessions
|
||||
/// rides Chat — one engine session model, no profile of its own (#126).
|
||||
nonisolated enum ProfileSurface: CaseIterable, Sendable {
|
||||
/// Declaration order = provision and backup order: chat first, so the
|
||||
/// resident surface is healthy before any pass-profile failure stops
|
||||
/// the loop.
|
||||
case chat
|
||||
case pass1
|
||||
case pass2
|
||||
|
||||
/// Adopted in place for chat — sessions, memory, transcripts survive.
|
||||
var profileName: String {
|
||||
switch self {
|
||||
case .chat: "museion"
|
||||
case .pass1: "museion-pass1"
|
||||
case .pass2: "museion-pass2"
|
||||
}
|
||||
}
|
||||
|
||||
/// #133 allocation table — Pass 1: 9 · Pass 2: 8 · Chat: 10. The persona
|
||||
/// pair never co-occurs (two manner doctrines fighting for the voice);
|
||||
/// fiction-craft is structural (P1), reader-psychology is sentence
|
||||
/// surgery (P2's core), titles-and-hooks is structural critique.
|
||||
var allocatedSkills: [String] {
|
||||
switch self {
|
||||
case .pass1: [
|
||||
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
|
||||
"micro-drill", "pass-persona", "fiction-craft", "titles-and-hooks",
|
||||
]
|
||||
case .pass2: [
|
||||
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
|
||||
"micro-drill", "pass-persona", "reader-psychology",
|
||||
]
|
||||
case .chat: [
|
||||
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
|
||||
"micro-drill", "session-persona", "fiction-craft", "reader-psychology",
|
||||
"titles-and-hooks",
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
init?(passKind: PassKind) {
|
||||
switch passKind {
|
||||
case .pass1: self = .pass1
|
||||
case .pass2: self = .pass2
|
||||
}
|
||||
}
|
||||
|
||||
/// #132 fresh-seed defaults: claude-sonnet-5-5 on all three surfaces,
|
||||
/// reasoning_effort unset (Anthropic 5.x thinking is adaptive; the bench
|
||||
/// never varied sonnet effort). Never copied from the live museion
|
||||
/// profile — it runs glm-5.3-max until switched in Settings.
|
||||
static let defaultModelProvider = "anthropic"
|
||||
static let defaultModelID = "claude-sonnet-5-5"
|
||||
/// #128/#134: 24k output budget — a provisioning-time guardrail via
|
||||
/// `extra_body.max_tokens --force`, never a Settings control.
|
||||
static let outputBudgetTokens = 24000
|
||||
}
|
||||
|
||||
/// Outcome of one provisioning pass — `failed` feeds the #48 alert.
|
||||
nonisolated enum ProfileProvisioner {
|
||||
/// Which phase failed; names the alert copy (#45).
|
||||
@@ -19,62 +89,161 @@ nonisolated enum ProfileProvisioner {
|
||||
case create = "couldn't set up the writing profile"
|
||||
case copy = "couldn't copy the writing skills"
|
||||
case register = "couldn't register the writing tools"
|
||||
case configure = "couldn't set the model defaults"
|
||||
}
|
||||
|
||||
enum Outcome: Equatable, Sendable {
|
||||
case seeded(copied: Int, present: Int)
|
||||
case failed(phase: Phase, excerpt: String)
|
||||
/// #134: names the failing profile — the #48 card surfaces it. nil
|
||||
/// when the failure predates any profile (payload/manifest-level).
|
||||
case failed(profile: String?, phase: Phase, excerpt: String)
|
||||
}
|
||||
|
||||
/// One idempotent pass: create the profile if missing, seed missing skills
|
||||
/// (#45), register museion-tools when missing (#23).
|
||||
/// One idempotent pass over all three surface profiles: master-seed the
|
||||
/// skills, then per surface — create (or adopt), write defaults on fresh
|
||||
/// profiles via the CLI rail, link skills per allocation, register
|
||||
/// 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`).
|
||||
/// - 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
|
||||
/// on updates).
|
||||
/// - serverBinaryPath: MCP server the engine spawns — this app's binary with
|
||||
/// `--serve-mcp` (tests inject; nil skips registration).
|
||||
static func perform(
|
||||
hermesBinary: String?,
|
||||
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
|
||||
payloadRoot: String = defaultPayloadRoot(),
|
||||
masterRoot: String = defaultMasterRoot(),
|
||||
serverBinaryPath: String? = Bundle.main.executableURL?.path,
|
||||
timeout: TimeInterval = 60,
|
||||
) -> Outcome {
|
||||
let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
|
||||
let fileManager = FileManager.default
|
||||
var copied = 0
|
||||
var present = 0
|
||||
|
||||
// Phase 1 — profile create. Dir-check first; spawn only when missing (#45).
|
||||
// `--no-alias` (no shell wrapper), `--no-skills` (the mentor's profile carries
|
||||
// only Museion's curated set — coding and writing never mix, G3).
|
||||
if !fileManager.fileExists(atPath: profileDir) {
|
||||
guard let binary = hermesBinary else {
|
||||
return logFailure(.failed(phase: .create, excerpt: "hermes binary not found"))
|
||||
}
|
||||
let run = EngineProbe.execute(
|
||||
[binary, "profile", "create", "museion", "--no-alias", "--no-skills"],
|
||||
// Phase 0 — the ONE master copy (#133): every manifest skill seeded
|
||||
// additively as real dirs; profiles symlink in, so a master refresh
|
||||
// updates every profile instantly and nothing can drift.
|
||||
guard let manifest = loadManifest(payloadRoot: payloadRoot) else {
|
||||
return logFailure(.failed(profile: nil, phase: .copy, excerpt: "seed-manifest.txt missing from payload"))
|
||||
}
|
||||
switch seedMaster(manifest: manifest, payloadRoot: payloadRoot, masterRoot: masterRoot) {
|
||||
case let .seeded(deltaCopied, deltaPresent):
|
||||
copied += deltaCopied
|
||||
present += deltaPresent
|
||||
case let .failed(profile, phase, excerpt):
|
||||
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt))
|
||||
}
|
||||
|
||||
for surface in ProfileSurface.allCases {
|
||||
switch provisionSurface(
|
||||
surface,
|
||||
hermesBinary: hermesBinary,
|
||||
profileRoot: profileRoot,
|
||||
masterRoot: masterRoot,
|
||||
manifest: manifest,
|
||||
serverBinaryPath: serverBinaryPath,
|
||||
timeout: timeout,
|
||||
)
|
||||
// #43: exit 1 + "already exists" on stdout = success; 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 logFailure(.failed(phase: .create, excerpt: excerpt(run)))
|
||||
) {
|
||||
case let .seeded(deltaCopied, deltaPresent):
|
||||
copied += deltaCopied
|
||||
present += deltaPresent
|
||||
case let .failed(profile, phase, excerpt):
|
||||
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt))
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2 — additive seed per seed-manifest.txt (#46).
|
||||
let seeded = seedSkills(payloadRoot: payloadRoot, profileDir: profileDir)
|
||||
guard case .seeded = seeded else { return seeded }
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.info("""
|
||||
provisioned \(ProfileSurface.allCases.count, privacy: .public) profiles \
|
||||
(\(copied, privacy: .public) skills linked/copied, \(present, privacy: .public) present)
|
||||
""")
|
||||
return .seeded(copied: copied, present: present)
|
||||
}
|
||||
|
||||
// Phase 3 — museion-tools registration (#23 slice 2). nil on either
|
||||
// binary is the test-injection seam; production always has both after a
|
||||
// gate pass (the server IS this app's binary).
|
||||
/// Phases 1–4 for ONE surface profile (#134): create (or adopt), write
|
||||
/// defaults on fresh profiles via the CLI rail, link skills per
|
||||
/// allocation, register museion-tools (#23).
|
||||
private static func provisionSurface(
|
||||
_ surface: ProfileSurface,
|
||||
hermesBinary: String?,
|
||||
profileRoot: String,
|
||||
masterRoot: String,
|
||||
manifest: [String],
|
||||
serverBinaryPath: String?,
|
||||
timeout: TimeInterval,
|
||||
) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
let profileDir = (profileRoot as NSString).appendingPathComponent(surface.profileName)
|
||||
|
||||
// Phase 1 — profile create. Dir-check first; spawn only when
|
||||
// missing (#45). `museion` is adopted, never re-created (ADR-0014).
|
||||
// `--no-alias` (no shell wrapper), `--no-skills` (the profiles
|
||||
// carry only Museion's curated set — coding and writing never mix, G3).
|
||||
var createdFresh = false
|
||||
if !fileManager.fileExists(atPath: profileDir) {
|
||||
guard let binary = hermesBinary else {
|
||||
return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found")
|
||||
}
|
||||
let run = EngineProbe.execute(
|
||||
[binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"],
|
||||
timeout: timeout,
|
||||
)
|
||||
// #43: exit 1 + "already exists" on stdout = success (a
|
||||
// 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))
|
||||
}
|
||||
createdFresh = run.exitCode == 0
|
||||
}
|
||||
|
||||
// Phase 2 — model defaults via the engine's own CLI (#128/#132).
|
||||
// Marker-gated so a re-pass is a no-op and a user's later Settings
|
||||
// change survives: fresh creates configure, an unconfigured PASS
|
||||
// profile (interrupted before its marker landed) is healed, and
|
||||
// the adopted museion is never touched — its model is the user's.
|
||||
if createdFresh || (surface != .chat && !markerExists(at: profileDir)) {
|
||||
guard let binary = hermesBinary else {
|
||||
return .failed(profile: surface.profileName, phase: .configure, excerpt: "hermes binary not found")
|
||||
}
|
||||
if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: timeout) {
|
||||
return failure
|
||||
}
|
||||
// A marker we couldn't record = configure incomplete — surface it
|
||||
// (finish-audit: swallowing this re-armed the defaults stomp
|
||||
// against the user's later Settings change on every later pass).
|
||||
if let failure = markConfigured(profileDir, profile: surface.profileName) {
|
||||
return failure
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3 — per-profile skills: symlinks per allocation + the
|
||||
// copy-era → symlink migration (#133).
|
||||
let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: masterRoot, manifest: manifest)
|
||||
if case .failed = linked {
|
||||
return linked
|
||||
}
|
||||
|
||||
// Phase 4 — museion-tools registration per profile (ADR-0008
|
||||
// amendment). nil on either binary is the test-injection seam;
|
||||
// production always has both after a gate pass.
|
||||
guard let hermesBinary, let serverBinaryPath else {
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.info("museion-tools registration skipped: engine or server binary missing")
|
||||
return seeded
|
||||
return linked
|
||||
}
|
||||
return registerTools(seeded, hermesBinary: hermesBinary, serverBinaryPath: serverBinaryPath, timeout: timeout)
|
||||
if let failure = registerTools(
|
||||
profile: surface.profileName,
|
||||
hermesBinary: hermesBinary,
|
||||
serverBinaryPath: serverBinaryPath,
|
||||
timeout: timeout,
|
||||
) {
|
||||
return failure
|
||||
}
|
||||
return linked
|
||||
}
|
||||
|
||||
/// The bundled payload ships as a plain Resources directory (#46 map decision).
|
||||
@@ -82,51 +251,112 @@ nonisolated enum ProfileProvisioner {
|
||||
((Bundle.main.resourcePath ?? "") as NSString).appendingPathComponent("writing skills")
|
||||
}
|
||||
|
||||
private static let subsystem = "com.babylondreams.Museion"
|
||||
|
||||
/// ponytail: whole-string character class, not a regex — `allSatisfy` reads
|
||||
/// as intent and covers `.`/`..`/`/`-prefixed entries without a pattern.
|
||||
private static func isKebabCaseDirectoryName(_ name: String) -> Bool {
|
||||
!name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" }
|
||||
/// #133: the ONE master skills copy lives beside state.json and Backups
|
||||
/// — app-owned, consistent with the rest; never inside the app bundle
|
||||
/// (the bundle path moves on updates — the mcp-registration stale-path
|
||||
/// lesson).
|
||||
static func defaultMasterRoot() -> String {
|
||||
("~/Library/Application Support/Museion/skills" as NSString).expandingTildeInPath
|
||||
}
|
||||
|
||||
/// Copy every manifest-listed skill that's missing; never touch present ones (G3a).
|
||||
private static func seedSkills(payloadRoot: String, profileDir: String) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
let skillsDir = (profileDir as NSString).appendingPathComponent("skills")
|
||||
sweepOrphanedTemps(skillsDir)
|
||||
let manifestPath = (payloadRoot as NSString).appendingPathComponent("seed-manifest.txt")
|
||||
guard let manifest = try? String(contentsOfFile: manifestPath, encoding: .utf8) else {
|
||||
return logFailure(.failed(phase: .copy, excerpt: "seed-manifest.txt missing from payload"))
|
||||
}
|
||||
let names = manifest.split(separator: "\n")
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty && !$0.hasPrefix("#") }
|
||||
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"
|
||||
|
||||
private static func markerExists(at profileDir: String) -> Bool {
|
||||
FileManager.default.fileExists(atPath: (profileDir as NSString).appendingPathComponent(configuredMarker))
|
||||
}
|
||||
|
||||
/// 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)
|
||||
do {
|
||||
try Data().write(to: URL(fileURLWithPath: marker))
|
||||
return nil
|
||||
} catch {
|
||||
return .failed(profile: profile, phase: .configure, excerpt: "couldn't record the provisioning marker: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
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))
|
||||
}
|
||||
}
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.info("""
|
||||
set model defaults on \(profile, privacy: .public): \
|
||||
\(ProfileSurface.defaultModelID, privacy: .public), \
|
||||
budget \(ProfileSurface.outputBudgetTokens, privacy: .public)
|
||||
""")
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Seed the master copy: every manifest skill as a REAL dir, additively
|
||||
/// — present skills are never opened, never overwritten (G3a). Profiles
|
||||
/// symlink into this one tree.
|
||||
private static func seedMaster(manifest: [String], payloadRoot: String, masterRoot: String) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
sweepOrphanedTemps(masterRoot)
|
||||
var copied = 0
|
||||
var present = 0
|
||||
var versions: [String] = []
|
||||
for name in names {
|
||||
// Trust boundary: manifest entries become path components — kebab-case
|
||||
// only (the payload contract), so no `/`, `..`, or absolute escape.
|
||||
for name in manifest {
|
||||
// Trust boundary carried from the manifest parse: kebab-case
|
||||
// only, so no `/`, `..`, or absolute escape.
|
||||
guard isKebabCaseDirectoryName(name) else {
|
||||
return logFailure(.failed(phase: .copy, excerpt: "invalid manifest entry: \(name)"))
|
||||
return .failed(profile: nil, phase: .copy, excerpt: "invalid manifest entry: \(name)")
|
||||
}
|
||||
let source = (payloadRoot as NSString).appendingPathComponent(name)
|
||||
guard fileManager.fileExists(atPath: source) else {
|
||||
return logFailure(.failed(phase: .copy, excerpt: "manifest entry missing from payload: \(name)"))
|
||||
return .failed(profile: nil, phase: .copy, excerpt: "manifest entry missing from payload: \(name)")
|
||||
}
|
||||
versions.append("\(name) \(frontmatterVersion(source) ?? "?")")
|
||||
let destination = (skillsDir as NSString).appendingPathComponent(name)
|
||||
let destination = (masterRoot as NSString).appendingPathComponent(name)
|
||||
if fileManager.fileExists(atPath: destination) {
|
||||
present += 1 // present skills are never opened, never overwritten (G3a)
|
||||
present += 1
|
||||
continue
|
||||
}
|
||||
// Per-skill atomic: copy to a temp name, rename into place; an interrupted
|
||||
// copy is healed by the next launch's additive pass (#45 — no journal).
|
||||
let temp = (skillsDir as NSString).appendingPathComponent(".\(name)-\(UUID().uuidString)")
|
||||
// Per-skill atomic: copy to a temp name, rename into place; an
|
||||
// interrupted copy is healed by the next launch's additive pass
|
||||
// (#45 — no journal).
|
||||
let temp = (masterRoot as NSString).appendingPathComponent(".\(name)-\(UUID().uuidString)")
|
||||
do {
|
||||
try fileManager.createDirectory(atPath: skillsDir, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(atPath: masterRoot, withIntermediateDirectories: true)
|
||||
try fileManager.copyItem(atPath: source, toPath: temp)
|
||||
purgeDotDSStore(temp)
|
||||
try fileManager.moveItem(atPath: temp, toPath: destination) // lost race → present
|
||||
@@ -136,36 +366,99 @@ nonisolated enum ProfileProvisioner {
|
||||
if fileManager.fileExists(atPath: destination) {
|
||||
present += 1
|
||||
} else {
|
||||
return logFailure(.failed(phase: .copy, excerpt: "copy \(name): \(error.localizedDescription)"))
|
||||
return .failed(profile: nil, phase: .copy, excerpt: "copy \(name): \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let summary = versions.joined(separator: ", ")
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.info("seeded writing skills: \(summary, privacy: .public) (\(copied, privacy: .public) copied, \(present, privacy: .public) present)")
|
||||
.info("master writing skills: \(summary, privacy: .public) (\(copied, privacy: .public) copied, \(present, privacy: .public) present)")
|
||||
return .seeded(copied: copied, present: present)
|
||||
}
|
||||
|
||||
/// Per-profile skills (#133): create missing symlinks for the surface's
|
||||
/// allocation; migrate a manifest-tracked copy-era REAL dir to a master
|
||||
/// symlink only when it still byte-matches (a diverged dir stays a copy;
|
||||
/// untracked/user skills are never touched; existing links are never
|
||||
/// retargeted — additive-only, G3a).
|
||||
private static func linkSkills(
|
||||
surface: ProfileSurface,
|
||||
profileDir: String,
|
||||
masterRoot: String,
|
||||
manifest: [String],
|
||||
) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
let skillsDir = (profileDir as NSString).appendingPathComponent("skills")
|
||||
sweepOrphanedTemps(skillsDir)
|
||||
var linked = 0
|
||||
var present = 0
|
||||
for name in manifest {
|
||||
let destination = (skillsDir as NSString).appendingPathComponent(name)
|
||||
let masterSkill = (masterRoot as NSString).appendingPathComponent(name)
|
||||
// A link (live or dangling) is never touched — additive-only.
|
||||
if (try? fileManager.destinationOfSymbolicLink(atPath: destination)) != nil {
|
||||
present += 1
|
||||
continue
|
||||
}
|
||||
if fileManager.fileExists(atPath: destination) {
|
||||
// Copy-era dir: swap storage to a symlink only when the bytes
|
||||
// still match the master the link will resolve to — the swap
|
||||
// must be invisible. Never reached without the dir existing.
|
||||
if treesByteMatch(masterSkill, destination) {
|
||||
let aside = (skillsDir as NSString).appendingPathComponent(".\(name)-old-\(UUID().uuidString)")
|
||||
do {
|
||||
try fileManager.moveItem(atPath: destination, toPath: aside)
|
||||
try fileManager.createSymbolicLink(atPath: destination, withDestinationPath: masterSkill)
|
||||
try? fileManager.removeItem(atPath: aside)
|
||||
linked += 1
|
||||
} catch {
|
||||
try? fileManager.moveItem(atPath: aside, toPath: destination) // never lose the copy
|
||||
present += 1
|
||||
}
|
||||
} else {
|
||||
present += 1 // diverged: the writer's edits stay a real copy
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Nothing on disk: only the surface's allocation gets a link —
|
||||
// an unallocated skill (session-persona on a pass engine) never
|
||||
// lands (curation, #133).
|
||||
guard surface.allocatedSkills.contains(name) else { continue }
|
||||
do {
|
||||
try fileManager.createDirectory(atPath: skillsDir, withIntermediateDirectories: true)
|
||||
try fileManager.createSymbolicLink(atPath: destination, withDestinationPath: masterSkill)
|
||||
linked += 1
|
||||
} catch {
|
||||
if fileManager.fileExists(atPath: destination) {
|
||||
present += 1 // lost race — the link is there
|
||||
} else {
|
||||
return .failed(profile: surface.profileName, phase: .copy, excerpt: "copy \(name): \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
return .seeded(copied: linked, present: present)
|
||||
}
|
||||
|
||||
/// #23 slice 2: register museion-tools into the profile exactly once, via
|
||||
/// the hermes CLI only — the provisioner never writes mcp_servers YAML
|
||||
/// itself (#44). `mcp list` first: a re-add would prompt "Overwrite? [y/N]"
|
||||
/// interactively; the skip avoids that branch. ponytail: a stale command
|
||||
/// path after the app moves is refreshed manually via
|
||||
/// `hermes -p museion mcp remove museion-tools`.
|
||||
/// `hermes -p <profile> mcp remove museion-tools`.
|
||||
private static func registerTools(
|
||||
_ seeded: Outcome,
|
||||
profile: String,
|
||||
hermesBinary: String,
|
||||
serverBinaryPath: String,
|
||||
timeout: TimeInterval,
|
||||
) -> Outcome {
|
||||
let list = EngineProbe.execute([hermesBinary, "-p", "museion", "mcp", "list"], timeout: timeout)
|
||||
) -> Outcome? {
|
||||
let list = EngineProbe.execute([hermesBinary, "-p", profile, "mcp", "list"], timeout: timeout)
|
||||
if list.stdout.contains("museion-tools") {
|
||||
return seeded
|
||||
return nil
|
||||
}
|
||||
let add = EngineProbe.execute(
|
||||
[
|
||||
hermesBinary, "-p", "museion", "mcp", "add", "museion-tools",
|
||||
hermesBinary, "-p", profile, "mcp", "add", "museion-tools",
|
||||
"--command", serverBinaryPath, "--args", "--serve-mcp",
|
||||
],
|
||||
timeout: timeout,
|
||||
@@ -175,29 +468,25 @@ 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 logFailure(.failed(phase: .register, excerpt: excerpt(add)))
|
||||
return .failed(profile: profile, phase: .register, excerpt: excerpt(add))
|
||||
}
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.info("registered museion-tools via hermes CLI (command: \(serverBinaryPath, privacy: .public))")
|
||||
return seeded
|
||||
}
|
||||
|
||||
/// Sweep `.name-UUID` temp dirs left by an interrupted copy+rename; the next
|
||||
/// pass re-copies the skill, but the orphan would linger forever otherwise.
|
||||
private static func sweepOrphanedTemps(_ skillsDir: String) {
|
||||
let fileManager = FileManager.default
|
||||
guard let entries = try? fileManager.contentsOfDirectory(atPath: skillsDir) else { return }
|
||||
for entry in entries where entry.hasPrefix(".") {
|
||||
try? fileManager.removeItem(atPath: (skillsDir as NSString).appendingPathComponent(entry))
|
||||
}
|
||||
.info("""
|
||||
registered museion-tools via hermes CLI on \(profile, privacy: .public) \
|
||||
(command: \(serverBinaryPath, privacy: .public))
|
||||
""")
|
||||
return nil
|
||||
}
|
||||
|
||||
/// #45: at most one os_log line per failure, carrying the excerpt for Console.app.
|
||||
@discardableResult
|
||||
private static func logFailure(_ outcome: Outcome) -> Outcome {
|
||||
if case let .failed(phase, excerpt) = outcome {
|
||||
if case let .failed(profile, phase, excerpt) = outcome {
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.error("\(phase.rawValue, privacy: .public): \(String(excerpt.prefix(300)), privacy: .public)")
|
||||
.error("""
|
||||
\(phase.rawValue, privacy: .public) [\(profile ?? "payload", privacy: .public)]: \
|
||||
\(String(excerpt.prefix(300)), privacy: .public)
|
||||
""")
|
||||
}
|
||||
return outcome
|
||||
}
|
||||
@@ -207,6 +496,86 @@ nonisolated enum ProfileProvisioner {
|
||||
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
|
||||
/// provisioner enum stays under its type-body ceiling (MentorPaneView
|
||||
/// posture). `nonisolated` to match the enum under default-MainActor mode.
|
||||
nonisolated extension ProfileProvisioner {
|
||||
/// The manifest as the inclusion list (blank/`#` lines ignored, entries
|
||||
/// kebab-validated at the trust boundary in `seedMaster`). nil when
|
||||
/// unreadable.
|
||||
private static func loadManifest(payloadRoot: String) -> [String]? {
|
||||
let manifestPath = (payloadRoot as NSString).appendingPathComponent("seed-manifest.txt")
|
||||
guard let manifest = try? String(contentsOfFile: manifestPath, encoding: .utf8) else {
|
||||
return nil
|
||||
}
|
||||
return manifest.split(separator: "\n")
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty && !$0.hasPrefix("#") }
|
||||
}
|
||||
|
||||
/// ponytail: whole-string character class, not a regex — `allSatisfy` reads
|
||||
/// as intent and covers `.`/`..`/`/`-prefixed entries without a pattern.
|
||||
private static func isKebabCaseDirectoryName(_ name: String) -> Bool {
|
||||
!name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" }
|
||||
}
|
||||
|
||||
/// Recursive byte-comparison of two dir trees — same entry names, every
|
||||
/// file byte-identical. `.DS_Store` is filtered from BOTH listings before
|
||||
/// the name-equality check (Finder noise, not a user edit — a
|
||||
/// merely-browsed skill dir must still migrate; the master side is purged
|
||||
/// at seed time, so a browsed copy-era dir would otherwise never match).
|
||||
/// A symlinked entry refuses the match outright (finish-audit: the
|
||||
/// copy-era tree is untrusted — following a link there could open a FIFO
|
||||
/// or read unbounded bytes; no match simply keeps the dir as a copy).
|
||||
private static func treesByteMatch(_ lhs: String, _ rhs: String) -> Bool {
|
||||
let fileManager = FileManager.default
|
||||
guard let lhsAll = try? fileManager.contentsOfDirectory(atPath: lhs).sorted(),
|
||||
let rhsAll = try? fileManager.contentsOfDirectory(atPath: rhs).sorted()
|
||||
else { return false }
|
||||
let lhsEntries = lhsAll.filter { $0 != ".DS_Store" }
|
||||
let rhsEntries = rhsAll.filter { $0 != ".DS_Store" }
|
||||
guard lhsEntries == rhsEntries else { return false }
|
||||
for name in lhsEntries {
|
||||
let lhsPath = (lhs as NSString).appendingPathComponent(name)
|
||||
let rhsPath = (rhs as NSString).appendingPathComponent(name)
|
||||
// Neither side may carry a symlink at this entry (lstat-true,
|
||||
// before any open) — the payload never ships one.
|
||||
if (try? fileManager.destinationOfSymbolicLink(atPath: lhsPath)) != nil
|
||||
|| (try? fileManager.destinationOfSymbolicLink(atPath: rhsPath)) != nil
|
||||
{
|
||||
return false
|
||||
}
|
||||
var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false
|
||||
guard fileManager.fileExists(atPath: lhsPath, isDirectory: &lhsIsDirectory),
|
||||
fileManager.fileExists(atPath: rhsPath, isDirectory: &rhsIsDirectory),
|
||||
lhsIsDirectory.boolValue == rhsIsDirectory.boolValue
|
||||
else { return false }
|
||||
if lhsIsDirectory.boolValue {
|
||||
if !treesByteMatch(lhsPath, rhsPath) {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
guard let lhsData = try? Data(contentsOf: URL(fileURLWithPath: lhsPath)),
|
||||
let rhsData = try? Data(contentsOf: URL(fileURLWithPath: rhsPath)),
|
||||
lhsData == rhsData
|
||||
else { return false }
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Sweep `.name-UUID` temp entries left by an interrupted copy+rename;
|
||||
/// the next pass re-copies the skill, but the orphan would linger
|
||||
/// forever otherwise.
|
||||
private static func sweepOrphanedTemps(_ dir: String) {
|
||||
let fileManager = FileManager.default
|
||||
guard let entries = try? fileManager.contentsOfDirectory(atPath: dir) else { return }
|
||||
for entry in entries where entry.hasPrefix(".") {
|
||||
try? fileManager.removeItem(atPath: (dir as NSString).appendingPathComponent(entry))
|
||||
}
|
||||
}
|
||||
|
||||
/// ponytail: first `version:` line inside the frontmatter block wins — the
|
||||
/// only place it appears; full YAML parsing isn't worth it for a log line.
|
||||
@@ -271,6 +640,7 @@ final class ProvisioningModel {
|
||||
hermesBinary: String? = nil,
|
||||
profileRoot: String? = nil,
|
||||
payloadRoot: String? = nil,
|
||||
masterRoot: String? = nil,
|
||||
) async {
|
||||
guard !running else { return }
|
||||
running = true
|
||||
@@ -280,10 +650,11 @@ final class ProvisioningModel {
|
||||
hermesBinary: hermesBinary,
|
||||
profileRoot: profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath,
|
||||
payloadRoot: payloadRoot ?? ProfileProvisioner.defaultPayloadRoot(),
|
||||
masterRoot: masterRoot ?? ProfileProvisioner.defaultMasterRoot(),
|
||||
)
|
||||
}.value
|
||||
if case let .failed(phase, excerpt) = outcome {
|
||||
lastFailure = .failed(phase: phase, excerpt: excerpt)
|
||||
if case .failed = outcome {
|
||||
lastFailure = outcome // verbatim — the #48 card names the profile (#134)
|
||||
} else {
|
||||
lastFailure = nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user