feat(profiles): registry + provisioning ×3
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:
AlexKucera committed 2026-10-27 09:23:56 +01:00
1 parent 2032534305
commit 610f8789bd
15 files changed
+1292 -232

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ Owned by the root AGENTS.md contract.
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
+66 -5
View File
@@ -19,13 +19,14 @@ func backupTempDir(_ label: String) -> String {
return dir
}
/// Minimal profile fixture at `<root>/museion`: state that matters to a
/// restore (auth.json, .env, state.db + sidecars, a skill) plus excluded
/// entries (logs/, cache/, gateway.pid, .DS_Store, caches, locks).
/// Minimal profile fixture at `<root>/<name>` (default the chat profile):
/// state that matters to a restore (auth.json, .env, state.db + sidecars, a
/// skill) plus excluded entries (logs/, cache/, gateway.pid, .DS_Store,
/// caches, locks). #134: name parameterized for the pass profiles.
@discardableResult
func makeProfileFixture(at root: String) -> String {
func makeProfileFixture(at root: String, name: String = "museion") -> String {
let fileManager = FileManager.default
let profile = (root as NSString).appendingPathComponent("museion")
let profile = (root as NSString).appendingPathComponent(name)
for dir in ["skills/serif-writing", "logs", "cache", "sessions/xyz/cache"] {
try? fileManager.createDirectory(
atPath: (profile as NSString).appendingPathComponent(dir),
@@ -180,6 +181,66 @@ struct ProfileBackupTests {
#expect(outcome == .skippedProfileMissing)
}
// Scenario: One backup stamp covers three profiles (#129/#134) — Given
// the daily backup with all three profile dirs on disk, when the pass
// runs while every engine is idle, then one timestamped stamp carries
// museion/, museion-pass1/, museion-pass2/ as siblings — and any live
// engine (even a pass engine's) skips the whole stamp.
@Test func `snapshot carries all three profile dirs`() {
let root = backupTempDir("three")
for name in ["museion", "museion-pass1", "museion-pass2"] {
makeProfileFixture(at: root, name: name)
}
let backups = (root as NSString).appendingPathComponent("backups")
guard case let .snapshotted(stamp) = perform(profileRoot: root, backupsRoot: backups) else {
Issue.record("expected snapshot")
return
}
let snap = backups as NSString
let entries = (try? FileManager.default.contentsOfDirectory(atPath: (snap as NSString).appendingPathComponent(stamp))) ?? []
#expect(Set(entries) == Set(["museion", "museion-pass1", "museion-pass2"]))
for name in ["museion", "museion-pass1", "museion-pass2"] {
let auth = (((snap as NSString).appendingPathComponent(stamp) as NSString).appendingPathComponent(name) as NSString)
.appendingPathComponent("auth.json")
#expect(FileManager.default.fileExists(atPath: auth), "\(name) payload missing")
}
// RESTORE.md names the three folders.
let restoreDoc = (try? String(contentsOfFile: (snap as NSString).appendingPathComponent("RESTORE.md"), encoding: .utf8)) ?? ""
#expect(restoreDoc.contains("museion-pass1"))
#expect(restoreDoc.contains("museion-pass2"))
}
@Test func `live pass engine skips the whole stamp`() {
let root = backupTempDir("passlive")
for name in ["museion", "museion-pass1", "museion-pass2"] {
makeProfileFixture(at: root, name: name)
}
// A live gateway pid inside a PASS profile — chat is idle, the stamp
// still skips: one stamp = one consistent point in time (#129).
try? "{\"pid\": \(ProcessInfo.processInfo.processIdentifier)}".write(
toFile: ((root as NSString).appendingPathComponent("museion-pass1") as NSString).appendingPathComponent("gateway.pid"),
atomically: true,
encoding: .utf8,
)
let outcome = perform(profileRoot: root, backupsRoot: (root as NSString).appendingPathComponent("backups"))
#expect(outcome == .skippedEngineRunning)
let backups = (root as NSString).appendingPathComponent("backups")
let stamps = ((try? FileManager.default.contentsOfDirectory(atPath: backups)) ?? []).filter { $0 != "RESTORE.md" }
#expect(stamps.isEmpty) // nothing half-written
}
@Test func `missing pass profiles snapshot the rest`() {
let root = backupTempDir("partial")
makeProfileFixture(at: root) // only the chat profile exists
let backups = (root as NSString).appendingPathComponent("backups")
guard case let .snapshotted(stamp) = perform(profileRoot: root, backupsRoot: backups) else {
Issue.record("expected snapshot over the existing profile")
return
}
let entries = (try? FileManager.default.contentsOfDirectory(atPath: (backups as NSString).appendingPathComponent(stamp))) ?? []
#expect(Set(entries) == Set(["museion"]))
}
@Test func `copy failure returns failed and leaves no temp dir`() {
let root = backupTempDir("fail")
let profile = makeProfileFixture(at: root)
@@ -22,25 +22,29 @@ struct ProfileProvisionerFailureTests {
let payload = makePayload(at: provTempDir("payload"), skills: skills)
let failing = makeFakeHermes(at: binDir, name: "hermes-fail", mode: "fail")
let model = ProvisioningModel()
await model.runPass(hermesBinary: failing, profileRoot: profileRoot, payloadRoot: payload)
await model.runPass(hermesBinary: failing, profileRoot: profileRoot, payloadRoot: payload, masterRoot: provTempDir("master"))
#expect(model.hasFailure)
model.deferFailure() // Not Now (#48)
#expect(!model.hasFailure)
#expect(model.lastFailure == nil)
// Next launch's silent retry fails again — the card may show again.
await model.runPass(hermesBinary: failing, profileRoot: profileRoot, payloadRoot: payload)
await model.runPass(hermesBinary: failing, profileRoot: profileRoot, payloadRoot: payload, masterRoot: provTempDir("master"))
#expect(model.hasFailure)
}
@Test func `registration only via the mcp add cli rail never hand-written yaml`() {
// #44 invariant, slice-2 form: museion-tools registration happens ONLY
// through the `hermes -p museion mcp add` CLI rail — the provisioner
// through the `hermes -p <profile> mcp add` CLI rail — the provisioner
// never writes mcp_servers YAML itself. A pre-existing engine-owned
// config.yaml stays byte-identical through a failed pass, a skipped
// (nil server) pass, AND a pass that registers via the CLI.
// (nil server) pass, AND a pass that registers via the CLI. #134: the
// config-set defaults ride the same CLI rail (ADR-0014) — the adopted
// museion is never configured, so its config.yaml is never even a
// CLI target here.
let binDir = provTempDir("mcp")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master") // ONE master across all three passes — a fresh one per pass would re-seed and skew the counts
let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
let configPath = (profileDir as NSString).appendingPathComponent("config.yaml")
let config = "model: glm-5.3\nmcp_servers:\n weather: {}\n"
@@ -59,7 +63,12 @@ struct ProfileProvisionerFailureTests {
}
// Failed pass: registration never reached, config untouched.
let failed = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: badPayload)
let failed = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: badPayload,
masterRoot: master,
)
guard case .failed = failed else {
Issue.record("expected copy failure, got \(failed)")
return
@@ -67,44 +76,52 @@ struct ProfileProvisionerFailureTests {
#expect(configUntouched())
// Skipped pass: nil serverBinaryPath is the test seam — nothing
// registers, config untouched.
// registers, config untouched. (The failed pass already seeded the
// shared master — 2 present there, only the 6 profile links copy.)
let skipped = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
masterRoot: master,
serverBinaryPath: nil,
)
#expect(skipped == .seeded(copied: 0, present: 2))
#expect(skipped == .seeded(copied: 6, present: 2))
#expect(configUntouched())
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation")))
for profile in ["museion", "museion-pass1", "museion-pass2"] {
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile)")))
}
// Registering pass: the CLI rail ran (marker + invocation recorded) and
// still not one byte of config.yaml is written by the provisioner — the
// entry lands through the CLI, or not at all.
// Registering pass: the CLI rail ran (markers + invocations per
// profile) and still not one byte of config.yaml is written by the
// provisioner — the entry lands through the CLI, or not at all.
let registered = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
masterRoot: master,
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
)
#expect(registered == .seeded(copied: 0, present: 2))
#expect(registered == .seeded(copied: 0, present: 8))
#expect(configUntouched())
#expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered")))
#expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered-museion")))
let invocation = (try? String(
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation"),
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation-museion"),
encoding: .utf8,
)) ?? ""
#expect(invocation.contains("mcp add museion-tools"))
}
@Test func `fresh-profile registering pass writes no config yaml`() {
// #44, fresh-profile case (own binary dir so the add truly runs): a
// registering pass still writes no config.yaml — the CLI owns that
// file, not us.
// file, not us (the fake records invocations, writes nothing).
let freshBinDir = provTempDir("fresh-mcp")
let freshRoot = (freshBinDir as NSString).appendingPathComponent("profiles")
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: freshBinDir, mode: "ok"),
profileRoot: freshRoot,
payloadRoot: goodPayload,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
)
let freshConfig = ((freshRoot as NSString).appendingPathComponent("museion") as NSString)
@@ -120,6 +137,7 @@ struct ProfileProvisionerFailureTests {
hermesBinary: makeFakeHermes(at: binDir, mode: "fail"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
)
guard case .failed = outcome else {
Issue.record("expected create failure, got \(outcome)")
@@ -148,11 +166,13 @@ struct ProfileProvisionerFailureTests {
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
)
guard case let .failed(phase, excerpt) = outcome else {
guard case let .failed(profile, phase, excerpt) = outcome else {
Issue.record("expected copy failure, got \(outcome)")
return
}
#expect(profile == "museion") // chat provisions first — its skills dir is the blocker
#expect(phase == .copy)
#expect(excerpt.hasPrefix("copy serif-writing:"))
}
+89 -93
View File
@@ -3,9 +3,9 @@
// MuseionTests
//
// Exercises the real Process path with a fake hermes binary and injected
// profile/payload dirs (#47) — same pattern as EngineGateTests.
// profile/payload/master dirs (#47, #134) — same pattern as EngineGateTests.
//
// Convention: the fake creates the profile at `<binaryDir>/profiles/<name>`
// Convention: the fake creates profiles at `<binaryDir>/profiles/<name>`
// (derived from its own path — race-free under parallel tests), so each test
// passes `profileRoot = binaryDir + "/profiles"`.
//
@@ -26,13 +26,18 @@ struct SeedSkill {
/// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1.
/// stderr-only: error on stderr with empty stdout (#48 fallback).
///
/// Also speaks `mcp` behind the `-p museion` global flag (#23): `mcp list`
/// prints "museion-tools" iff `<binaryDir>/mcp-registered` exists, else
/// "No MCP servers configured."; `mcp add` verifies its argv, reads ONE "y"
/// line from stdin (mismatch/EOF → "Cancelled.", exit 1 — nothing saved),
/// records the exact invocation in `<binaryDir>/mcp-add-invocation`, drops the
/// marker, prints "Saved 'museion-tools' to …" (verified wire strings).
/// `<binaryDir>/mcp-add-fails` forces "Error: mcp add exploded", exit 1.
/// Also speaks `mcp` and `config set` behind the `-p <profile>` global flag
/// (#23, #134): `mcp list` prints "museion-tools" iff
/// `<binaryDir>/mcp-registered-<profile>` exists, else "No MCP servers
/// configured."; `mcp add` verifies its argv, reads ONE "y" line from stdin
/// (mismatch/EOF → "Cancelled.", exit 1 — nothing saved), records the exact
/// invocation in `<binaryDir>/mcp-add-invocation-<profile>`, drops the
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
/// strings). `config set <key> <value> [--force]` appends the exact argv to
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …" line.
/// `<binaryDir>/mcp-add-fails` / `config-set-fails` force the matching
/// failure. Every `profile create` name appends to
/// `<binaryDir>/profile-create-log`.
func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
let path = (dir as NSString).appendingPathComponent(name)
let createBlock = switch mode {
@@ -63,11 +68,13 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
#!/bin/zsh
if [[ "$1" == "profile" && "$2" == "create" ]]; then
NAME="$3"
print -r -- "$NAME" >> "${0:h}/profile-create-log"
\(createBlock)
fi
if [[ "$1" == "-p" && "$2" == "museion" && "$3" == "mcp" ]]; then
if [[ "$1" == "-p" && "$3" == "mcp" ]]; then
PROFILE="$2"
if [[ "$4" == "list" ]]; then
if [[ -f "${0:h}/mcp-registered" ]]; then
if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then
print "museion-tools enabled"
exit 0
fi
@@ -88,12 +95,22 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
print "Cancelled."
exit 1
fi
print -r -- "$*" > "${0:h}/mcp-add-invocation"
touch "${0:h}/mcp-registered"
print "Saved 'museion-tools' to ${0:h}/profiles/museion/config.yaml"
print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE"
touch "${0:h}/mcp-registered-$PROFILE"
print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
fi
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then
PROFILE="$2"
if [[ -f "${0:h}/config-set-fails" ]]; then
print "Error: config set exploded"
exit 1
fi
print -r -- "$*" >> "${0:h}/config-set-$PROFILE"
print "✓ Set $5 = $6 in ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
exit 97
"""
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
@@ -125,7 +142,8 @@ func makePayload(at dir: String, skills: [SeedSkill]) -> String {
"""
try? skillMarkdown.write(
toFile: (skillDir as NSString).appendingPathComponent("SKILL.md"),
atomically: true, encoding: .utf8,
atomically: true,
encoding: .utf8,
)
}
// Non-skill extras that must never seed (the repo's AGENTS.md, the manifest).
@@ -140,8 +158,8 @@ func provTempDir(_ label: String) -> String {
return dir
}
func skillPath(_ profileRoot: String, _ name: String) -> String {
((profileRoot as NSString).appendingPathComponent("museion/skills") as NSString).appendingPathComponent(name)
func skillPath(_ profileRoot: String, _ profile: String, _ name: String) -> String {
((profileRoot as NSString).appendingPathComponent("\(profile)/skills") as NSString).appendingPathComponent(name)
}
func readSkillBody(_ path: String) -> String {
@@ -162,45 +180,57 @@ struct ProfileProvisionerTests {
let binDir = provTempDir("fresh")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: master,
)
#expect(outcome == .seeded(copied: 2, present: 0))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "serif-writing")))
#expect(readSkillBody(skillPath(profileRoot, "deslop")).contains("tell catalog"))
// #134: 2 master copies + one symlink per skill per profile (×3).
#expect(outcome == .seeded(copied: 8, present: 0))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "museion", "serif-writing")))
#expect(readSkillBody(skillPath(profileRoot, "museion-pass1", "deslop")).contains("tell catalog"))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "museion-pass2", "serif-writing")))
}
@Test func `already-exists exit 1 is success and profile is left intact`() {
let binDir = provTempDir("exists")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "exists")
let master = provTempDir("master")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
// Writer-modified skill in place — second pass must never overwrite it.
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
// Writer-modified skill in place — the next pass must never overwrite
// it (G3a: through a linked skill the edit lands in the shared
// master, which seeding never touches).
try? "mentor's own edits".write(
toFile: (skillPath(profileRoot, "serif-writing") as NSString).appendingPathComponent("SKILL.md"),
atomically: true, encoding: .utf8,
toFile: (skillPath(profileRoot, "museion", "serif-writing") as NSString).appendingPathComponent("SKILL.md"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
#expect(outcome == .seeded(copied: 0, present: 2))
#expect(readSkillBody(skillPath(profileRoot, "serif-writing")) == "mentor's own edits")
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
// Master 2 present; museion 2 links; pass profiles 2 links each —
// nothing new, nothing overwritten.
#expect(outcome == .seeded(copied: 0, present: 8))
#expect(readSkillBody(skillPath(profileRoot, "museion", "serif-writing")) == "mentor's own edits")
}
@Test func `later app version adds new skill without touching old ones`() {
let binDir = provTempDir("upgrade")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let master = provTempDir("master")
let payloadV1 = makePayload(at: provTempDir("p1"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV1)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV1, masterRoot: master)
let payloadV2 = makePayload(
at: provTempDir("p2"),
skills: skills + [SeedSkill(name: "rhetoric", version: "1.0", body: "persuasion")],
)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV2)
#expect(outcome == .seeded(copied: 1, present: 2))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "rhetoric")))
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payloadV2, masterRoot: master)
// rhetoric joins the master (1 copy) and every profile's links (3).
#expect(outcome == .seeded(copied: 4, present: 8))
#expect(FileManager.default.fileExists(atPath: skillPath(profileRoot, "museion", "rhetoric")))
}
@Test func `create failure reports phase-named excerpt`() {
@@ -210,8 +240,10 @@ struct ProfileProvisionerTests {
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
)
#expect(outcome == .failed(phase: .create, excerpt: "Error: create exploded"))
// Chat provisions first (#134 loop order) — its create failed.
#expect(outcome == .failed(profile: "museion", phase: .create, excerpt: "Error: create exploded"))
}
@Test func `create failure with empty stdout falls back to stderr`() {
@@ -222,8 +254,9 @@ struct ProfileProvisionerTests {
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: provTempDir("master"),
)
#expect(outcome == .failed(phase: .create, excerpt: "Error: stderr-only boom"))
#expect(outcome == .failed(profile: "museion", phase: .create, excerpt: "Error: stderr-only boom"))
}
@Test func `manifest entry missing from payload is a copy failure`() {
@@ -233,17 +266,21 @@ struct ProfileProvisionerTests {
// Manifest names a dir the payload doesn't carry.
try? "serif-writing\ndeslop\nrhetoric\n".write(
toFile: (payload as NSString).appendingPathComponent("seed-manifest.txt"),
atomically: true, encoding: .utf8,
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
guard case let .failed(phase, excerpt) = outcome else {
// Master-level failure — before any profile, so no profile named.
guard case let .failed(profile, phase, excerpt) = outcome else {
Issue.record("expected copy failure, got \(outcome)")
return
}
#expect(profile == nil)
#expect(phase == .copy)
#expect(excerpt.contains("rhetoric"))
}
@@ -257,17 +294,20 @@ struct ProfileProvisionerTests {
for bad in ["../escape", "/tmp/evil", ".", ".."] {
try? "serif-writing\n\(bad)\n".write(
toFile: (payload as NSString).appendingPathComponent("seed-manifest.txt"),
atomically: true, encoding: .utf8,
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
guard case let .failed(phase, excerpt) = outcome else {
guard case let .failed(profile, phase, excerpt) = outcome else {
Issue.record("'\(bad)' must fail the pass, got \(outcome)")
continue
}
#expect(profile == nil)
#expect(phase == .copy)
#expect(excerpt.contains(bad))
}
@@ -281,91 +321,45 @@ struct ProfileProvisionerTests {
hermesBinary: binary,
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
#expect(outcome == .failed(phase: .copy, excerpt: "seed-manifest.txt missing from payload"))
#expect(outcome == .failed(profile: nil, phase: .copy, excerpt: "seed-manifest.txt missing from payload"))
}
@Test func `non-manifest payload files never seed`() {
let binDir = provTempDir("extras")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let master = provTempDir("master")
_ = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
masterRoot: master,
)
let seededRoot = (profileRoot as NSString).appendingPathComponent("museion/skills")
let seeded = (try? FileManager.default.contentsOfDirectory(atPath: seededRoot)) ?? []
#expect(Set(seeded) == Set(["serif-writing", "deslop"]))
let masterEntries = (try? FileManager.default.contentsOfDirectory(atPath: master)) ?? []
#expect(Set(masterEntries) == Set(["serif-writing", "deslop"]))
}
@Test func `orphaned temp dirs from an interrupted copy are swept`() {
let binDir = provTempDir("orphan")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let master = provTempDir("master")
let payload = makePayload(at: provTempDir("payload"), skills: skills)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
// Simulate an interrupted pass: the temp dir landed, the rename never ran.
let skillsDir = (profileRoot as NSString).appendingPathComponent("museion/skills")
let orphan = (skillsDir as NSString).appendingPathComponent(".serif-writing-DEADBEEF")
try? FileManager.default.createDirectory(atPath: orphan, withIntermediateDirectories: true)
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload)
#expect(outcome == .seeded(copied: 0, present: 2))
let outcome = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, masterRoot: master)
#expect(outcome == .seeded(copied: 0, present: 8))
#expect(!FileManager.default.fileExists(atPath: orphan))
}
@Test func `fresh pass registers museion-tools via the cli with the exact command line`() {
let binDir = provTempDir("mcp-add")
let serverPath = (provTempDir("server") as NSString).appendingPathComponent("Museion")
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
serverBinaryPath: serverPath,
)
#expect(outcome == .seeded(copied: 2, present: 0))
let invocation = ((try? String(
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation"),
encoding: .utf8,
)) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
#expect(invocation == "-p museion mcp add museion-tools --command \(serverPath) --args --serve-mcp")
}
@Test func `already-registered profile skips the add`() {
let binDir = provTempDir("mcp-skip")
// Pre-existing registration → `mcp list` reports it → no add: a re-add
// would prompt "Overwrite? [y/N]" — the skip avoids that branch.
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("mcp-registered"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
serverBinaryPath: "/fake/Museon",
)
#expect(outcome == .seeded(copied: 2, present: 0))
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation")))
}
@Test func `rejected add fails the register phase with the cli excerpt`() {
let binDir = provTempDir("mcp-reject")
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("mcp-add-fails"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
serverBinaryPath: "/fake/Museion",
)
#expect(outcome == .failed(phase: .register, excerpt: "Error: mcp add exploded"))
}
@Test func `bundled manifest matches bundled payload`() {
// url(forResource:) doesn't resolve folder references — use the same path
// the provisioner itself builds.
@@ -405,12 +399,14 @@ struct ProfileProvisionerTests {
hermesBinary: makeFakeHermes(at: binDir, name: "hermes-fail", mode: "fail"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
#expect(model.lastFailure != nil)
await model.runPass(
hermesBinary: makeFakeHermes(at: binDir, name: "hermes-ok", mode: "ok"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: provTempDir("master"),
)
#expect(model.lastFailure == nil)
}
@@ -0,0 +1,137 @@
//
// ProfileSkillMigrationTests.swift
// MuseionTests
//
// Scenario: Copy-era dirs migrate to master symlinks on byte-match (#134/
// #133) — Given today's museion profile whose skills landed as real
// directory copies, when the provisioner passes, then a dir still
// byte-matching the payload swaps to a symlink into the master (content
// identical through the swap); a diverged dir stays a copy; untracked user
// skills are never touched. Own file — ProfileSurfaceTests crossed its
// type-body ceiling (MCPToolsPromoteTests precedent); shares the harness.
//
import Foundation
@testable import Museion
import Testing
@Suite("ProfileSkillMigrationTests")
struct ProfileSkillMigrationTests {
@Test func `copy-era dir byte-matching the shipped set migrates to a master symlink`() {
let binDir = provTempDir("migrate")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let payload = makeShippedPayload(at: provTempDir("payload"))
let fileManager = FileManager.default
// Today's museion: copy-era REAL dirs from the old seeding — one
// pristine, one carrying Finder's .DS_Store noise (not a user edit).
let museionSkills = (profileRoot as NSString).appendingPathComponent("museion/skills")
for name in ["serif-writing", "deslop"] {
try? fileManager.createDirectory(atPath: museionSkills, withIntermediateDirectories: true)
try? fileManager.copyItem(
atPath: (payload as NSString).appendingPathComponent(name),
toPath: (museionSkills as NSString).appendingPathComponent(name),
)
}
try? "junk".write(
toFile: ((museionSkills as NSString).appendingPathComponent("deslop") as NSString).appendingPathComponent(".DS_Store"),
atomically: true,
encoding: .utf8,
)
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
for name in ["serif-writing", "deslop"] {
let link = (museionSkills as NSString).appendingPathComponent(name)
let target = try? fileManager.destinationOfSymbolicLink(atPath: link)
#expect(target == (master as NSString).appendingPathComponent(name), "\(name) migrated")
// Content identical through the swap.
#expect(readSkillBody(link).contains("\(name) body"))
}
}
@Test func `diverged dir stays a copy and untracked skills stay untouched`() {
let binDir = provTempDir("diverged")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let payload = makeShippedPayload(at: provTempDir("payload"))
let fileManager = FileManager.default
// A writer-modified copy-era dir and a user skill the manifest never
// tracked — neither may be touched (G3a).
let museionSkills = (profileRoot as NSString).appendingPathComponent("museion/skills")
try? fileManager.createDirectory(atPath: museionSkills, withIntermediateDirectories: true)
try? fileManager.copyItem(
atPath: (payload as NSString).appendingPathComponent("serif-writing"),
toPath: (museionSkills as NSString).appendingPathComponent("serif-writing"),
)
try? "the writer's own version".write(
toFile: ((museionSkills as NSString).appendingPathComponent("serif-writing") as NSString).appendingPathComponent("SKILL.md"),
atomically: true,
encoding: .utf8,
)
let userSkill = (museionSkills as NSString).appendingPathComponent("my-own-skill")
try? fileManager.createDirectory(atPath: userSkill, withIntermediateDirectories: true)
try? "precious".write(
toFile: (userSkill as NSString).appendingPathComponent("SKILL.md"),
atomically: true,
encoding: .utf8,
)
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
// Diverged: still a REAL dir, edits intact.
let diverged = (museionSkills as NSString).appendingPathComponent("serif-writing")
#expect((try? fileManager.destinationOfSymbolicLink(atPath: diverged)) == nil)
#expect(readSkillBody(diverged) == "the writer's own version")
// Untracked: never linked, never altered.
#expect((try? fileManager.destinationOfSymbolicLink(atPath: userSkill)) == nil)
#expect(readSkillBody(userSkill) == "precious")
}
@Test func `symlinked entry inside a copy-era dir refuses the migration`() {
// Finish-audit: the copy-era tree is untrusted — a symlinked SKILL.md
// must fail the byte-match (never be followed) and the dir stays a
// copy, the planted link untouched.
let binDir = provTempDir("symlinkrefuse")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let payload = makeShippedPayload(at: provTempDir("payload"))
let fileManager = FileManager.default
let museionSkills = (profileRoot as NSString).appendingPathComponent("museion/skills")
try? fileManager.createDirectory(atPath: museionSkills, withIntermediateDirectories: true)
try? fileManager.copyItem(
atPath: (payload as NSString).appendingPathComponent("serif-writing"),
toPath: (museionSkills as NSString).appendingPathComponent("serif-writing"),
)
let skillDir = (museionSkills as NSString).appendingPathComponent("serif-writing")
let elsewhere = provTempDir("elsewhere")
try? "elsewhere".write(
toFile: (elsewhere as NSString).appendingPathComponent("SKILL.md"),
atomically: true,
encoding: .utf8,
)
try? fileManager.removeItem(atPath: (skillDir as NSString).appendingPathComponent("SKILL.md"))
try? fileManager.createSymbolicLink(
atPath: (skillDir as NSString).appendingPathComponent("SKILL.md"),
withDestinationPath: (elsewhere as NSString).appendingPathComponent("SKILL.md"),
)
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
// The dir is still a REAL dir (no migration), the planted link intact.
#expect((try? fileManager.destinationOfSymbolicLink(atPath: skillDir)) == nil)
#expect(readSkillBody(skillDir) == "elsewhere")
}
}
+365
View File
@@ -0,0 +1,365 @@
//
// ProfileSurfaceTests.swift
// MuseionTests
//
// #134 (Profiles S1) — the per-surface topology over the fake-binary
// harness shared with ProfileProvisionerTests.swift.
//
// Scenario: Surface→profile registry — Given the app's three LLM surfaces
// (Pass 1, Pass 2, Chat; Sessions rides Chat), when code asks which Hermes
// profile a surface runs on, then it answers museion-pass1 / museion-pass2 /
// museion (adopted in place), with the #133 per-surface skill allocation and
// the #132 sonnet defaults + 24k budget as constants.
//
// Scenario: First-run provisions all three idempotently — Given a machine
// with hermes + keys that passes the binary-only gate, when the onPass
// provisioner runs, then museion is adopted (never re-created, config
// untouched), museion-pass1/2 are created fresh with the sonnet model block
// and 24k budget written via `hermes -p <profile> config set`, the skills
// master is seeded once and symlinked into each profile per allocation,
// museion-tools registers per profile — and a re-pass changes nothing.
//
// Scenario: A failing provision names its profile (#48 pattern) — the
// failure outcome and card carry the failing profile's name.
//
import Foundation
@testable import Museion
import Testing
/// The full 11-skill shipped set as fixtures (names + minimal bodies).
let shippedSkillNames = [
"serif-writing", "deslop", "demonstrator", "rhetoric", "prose-craft",
"micro-drill", "pass-persona", "session-persona", "fiction-craft",
"reader-psychology", "titles-and-hooks",
]
func makeShippedPayload(at dir: String) -> String {
makePayload(at: dir, skills: shippedSkillNames.map { SeedSkill(name: $0, version: "1.0", body: "\($0) body") })
}
/// Reads a fake-hermes log file as trimmed lines.
func fakeHermesLog(_ binDir: String, _ file: String) -> [String] {
((try? String(contentsOfFile: (binDir as NSString).appendingPathComponent(file), encoding: .utf8)) ?? "")
.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
}
@Suite("ProfileSurfaceTests")
struct ProfileSurfaceTests {
@Test func `registry maps surfaces to profiles with allocation and defaults`() {
// Chat first — the resident surface provisions before any
// pass-profile failure can stop the loop.
#expect(ProfileSurface.allCases.map(\.profileName) == ["museion", "museion-pass1", "museion-pass2"])
#expect(ProfileSurface(passKind: .pass1) == .pass1)
#expect(ProfileSurface(passKind: .pass2) == .pass2)
// #133 allocation table: P1 9 · P2 8 · Chat 10.
#expect(ProfileSurface.pass1.allocatedSkills.count == 9)
#expect(ProfileSurface.pass2.allocatedSkills.count == 8)
#expect(ProfileSurface.chat.allocatedSkills.count == 10)
// The persona pair never co-occurs (the manner co-trigger conflict).
#expect(!ProfileSurface.chat.allocatedSkills.contains("pass-persona"))
#expect(!ProfileSurface.pass1.allocatedSkills.contains("session-persona"))
#expect(!ProfileSurface.pass2.allocatedSkills.contains("session-persona"))
// #132 defaults: sonnet on all three, effort unset, 24k budget.
#expect(ProfileSurface.defaultModelProvider == "anthropic")
#expect(ProfileSurface.defaultModelID == "claude-sonnet-5-5")
#expect(ProfileSurface.outputBudgetTokens == 24000)
}
@Test func `every allocated skill ships in the bundled payload`() {
let payload = ProfileProvisioner.defaultPayloadRoot()
guard FileManager.default.fileExists(atPath: payload) else {
Issue.record("bundled writing-skills payload missing from app resources")
return
}
let manifest = (try? String(
contentsOfFile: (payload as NSString).appendingPathComponent("seed-manifest.txt"),
encoding: .utf8,
)) ?? ""
let listed = Set(manifest.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) })
for surface in ProfileSurface.allCases {
for skill in surface.allocatedSkills where !listed.contains(skill) {
Issue.record("\(surface.profileName) allocates '\(skill)' — not in the bundled manifest")
}
}
}
@Test func `fresh pass provisions all three profiles and config-sets defaults on each`() {
let binDir = provTempDir("x3")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
// 11 master copies + 27 allocation links (10 + 9 + 8).
#expect(outcome == .seeded(copied: 11 + 10 + 9 + 8, present: 0))
for name in ["museion", "museion-pass1", "museion-pass2"] {
#expect(FileManager.default.fileExists(atPath: (profileRoot as NSString).appendingPathComponent(name)))
}
// Exact config-set command lines per profile (#132 defaults via the
// #128 CLI rail — provider first, model, then the budget --force).
for profile in ["museion", "museion-pass1", "museion-pass2"] {
#expect(fakeHermesLog(binDir, "config-set-\(profile)") == [
"-p \(profile) config set model.provider anthropic",
"-p \(profile) config set model.default claude-sonnet-5-5",
"-p \(profile) config set model.extra_body.max_tokens 24000 --force",
])
}
}
@Test func `master holds the shipped set once and each profile symlinks its allocation`() {
let binDir = provTempDir("alloc")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
let fileManager = FileManager.default
// ONE master copy: every shipped skill as a real dir, nothing else.
let masterEntries = (try? fileManager.contentsOfDirectory(atPath: master)) ?? []
#expect(Set(masterEntries) == Set(shippedSkillNames))
// Each profile's skills dir is exactly its allocation, every entry a
// symlink resolving into the master.
for surface in ProfileSurface.allCases {
let skillsDir = (profileRoot as NSString)
.appendingPathComponent("\(surface.profileName)/skills")
let entries = Set((try? fileManager.contentsOfDirectory(atPath: skillsDir)) ?? [])
#expect(entries == Set(surface.allocatedSkills), "\(surface.profileName) allocation")
for name in surface.allocatedSkills {
let link = (skillsDir as NSString).appendingPathComponent(name)
let target = try? fileManager.destinationOfSymbolicLink(atPath: link)
#expect(target == (master as NSString).appendingPathComponent(name), "\(surface.profileName)/\(name)")
}
}
}
@Test func `re-pass is a no-op`() {
let binDir = provTempDir("noop")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let payload = makeShippedPayload(at: provTempDir("payload"))
let binary = makeFakeHermes(at: binDir, mode: "ok")
func runPass() -> ProfileProvisioner.Outcome {
ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: payload,
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
}
_ = runPass()
let configSetsBefore = fakeHermesLog(binDir, "config-set-museion-pass1")
let outcome = runPass()
// Everything present, nothing created — a user's later Settings
// change (config set through the same rail) is never stomped.
#expect(outcome == .seeded(copied: 0, present: 11 + 10 + 9 + 8))
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == configSetsBefore)
#expect(fakeHermesLog(binDir, "profile-create-log") == ["museion", "museion-pass1", "museion-pass2"])
}
@Test func `adopted museion is neither created nor configured`() {
let binDir = provTempDir("adopt")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
let museion = (profileRoot as NSString).appendingPathComponent("museion")
try? FileManager.default.createDirectory(atPath: museion, withIntermediateDirectories: true)
// Engine-owned state the adoption must leave byte-identical.
try? "sessions survive".write(
toFile: (museion as NSString).appendingPathComponent("state.db"),
atomically: true,
encoding: .utf8,
)
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
// Only the pass profiles were created; the live museion's model
// block (glm-5.3-max until Settings switches it — #132) is never
// touched: no create spawn, no config set.
#expect(fakeHermesLog(binDir, "profile-create-log") == ["museion-pass1", "museion-pass2"])
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("config-set-museion")))
let sentinel = ((try? String(
contentsOfFile: (museion as NSString).appendingPathComponent("state.db"),
encoding: .utf8,
)) ?? "")
#expect(sentinel == "sessions survive")
}
@Test func `unconfigured pass profile is healed and configured one is never stomped`() {
let binDir = provTempDir("heal")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let master = provTempDir("master")
// museion adopted; museion-pass1 exists WITHOUT its marker (a pass
// interrupted between create and configure); museion-pass2 exists
// WITH the marker (configured — e.g. the user changed the model in
// Settings through the same rail).
for profile in ["museion", "museion-pass1", "museion-pass2"] {
try? FileManager.default.createDirectory(
atPath: (profileRoot as NSString).appendingPathComponent(profile),
withIntermediateDirectories: true,
)
}
try? Data().write(
to: URL(fileURLWithPath: (profileRoot as NSString).appendingPathComponent("museion-pass2/.museion-provisioned")),
)
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: master,
serverBinaryPath: "/fake/Museion",
)
#expect(fakeHermesLog(binDir, "config-set-museion-pass1").count == 3) // healed
#expect(fakeHermesLog(binDir, "config-set-museion-pass2").isEmpty) // never stomped
#expect(fakeHermesLog(binDir, "config-set-museion").isEmpty) // adopted
}
@Test func `failing provision surfaces the profile by name`() {
let binDir = provTempDir("name")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
// museion adopted — the next profile in the loop is the one that fails.
try? FileManager.default.createDirectory(
atPath: (profileRoot as NSString).appendingPathComponent("museion"),
withIntermediateDirectories: true,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "fail"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: provTempDir("master"),
)
#expect(outcome == .failed(profile: "museion-pass1", phase: .create, excerpt: "Error: create exploded"))
}
@Test func `config set failure fails the configure phase`() {
let binDir = provTempDir("cfgfail")
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("config-set-fails"),
atomically: true,
encoding: .utf8,
)
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: provTempDir("master"),
)
// Fresh chat created first → its configure failed; no marker landed,
// so the Retry from the #48 card configures it.
#expect(outcome == .failed(profile: "museion", phase: .configure, excerpt: "Error: config set exploded"))
#expect(!FileManager.default.fileExists(
atPath: (profileRoot as NSString).appendingPathComponent("museion/.museion-provisioned"),
))
}
@Test func `marker write failure fails the configure phase`() {
// Finish-audit: a marker that couldn't be recorded must surface —
// swallowing it left the profile unmarked, and every later pass
// re-ran config set, stomping a user's Settings change.
let binDir = provTempDir("markerfail")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let fileManager = FileManager.default
// museion adopted; museion-pass1 unconfigured AND read-only (r-x) —
// the CLI rail succeeds (the fake writes nothing into the profile),
// then the marker write is the first write the dir refuses.
for profile in ["museion", "museion-pass1"] {
try? fileManager.createDirectory(
atPath: (profileRoot as NSString).appendingPathComponent(profile),
withIntermediateDirectories: true,
)
}
let pass1 = (profileRoot as NSString).appendingPathComponent("museion-pass1")
defer { try? fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: pass1) }
try? fileManager.setAttributes([.posixPermissions: 0o555], ofItemAtPath: pass1)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: profileRoot,
payloadRoot: makeShippedPayload(at: provTempDir("payload")),
masterRoot: provTempDir("master"),
)
guard case let .failed(profile, phase, excerpt) = outcome else {
Issue.record("expected configure failure, got \(outcome)")
return
}
#expect(profile == "museion-pass1")
#expect(phase == .configure)
#expect(excerpt.contains("marker"))
// No marker landed → Retry from the #48 card heals it.
#expect(!fileManager.fileExists(atPath: (pass1 as NSString).appendingPathComponent(".museion-provisioned")))
}
@Test func `fresh pass registers museion-tools per profile with the exact command line`() {
let binDir = provTempDir("mcp-add")
let serverPath = (provTempDir("server") as NSString).appendingPathComponent("Museion")
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: defaultSkills),
masterRoot: provTempDir("master"),
serverBinaryPath: serverPath,
)
#expect(outcome == .seeded(copied: 8, present: 0))
// #134: registration per profile — chat and one pass pinned exactly.
for profile in ["museion", "museion-pass1"] {
let invocation = ((try? String(
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile)"),
encoding: .utf8,
)) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
#expect(invocation == "-p \(profile) mcp add museion-tools --command \(serverPath) --args --serve-mcp")
}
}
@Test func `already-registered profile skips the add`() {
let binDir = provTempDir("mcp-skip")
// Pre-existing registration → `mcp list` reports it → no add: a re-add
// would prompt "Overwrite? [y/N]" — the skip avoids that branch.
for profile in ProfileSurface.allCases {
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("mcp-registered-\(profile.profileName)"),
atomically: true,
encoding: .utf8,
)
}
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: defaultSkills),
masterRoot: provTempDir("master"),
serverBinaryPath: "/fake/Museion",
)
#expect(outcome == .seeded(copied: 8, present: 0))
for profile in ProfileSurface.allCases {
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)")))
}
}
@Test func `rejected add fails the register phase with the cli excerpt`() {
let binDir = provTempDir("mcp-reject")
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("mcp-add-fails"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: defaultSkills),
masterRoot: provTempDir("master"),
serverBinaryPath: "/fake/Museion",
)
#expect(outcome == .failed(profile: "museion", phase: .register, excerpt: "Error: mcp add exploded"))
}
}