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
@@ -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