From 610f8789bd7f1d675c7486ca36acb5fae1cb4637 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 27 Oct 2026 09:23:56 +0100 Subject: [PATCH] =?UTF-8?q?feat(profiles):=20registry=20+=20provisioning?= =?UTF-8?q?=20=C3=973?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- AGENTS.md | 7 +- CHANGELOG.md | 2 + Museion/AGENTS.md | 14 +- Museion/EngineGateView.swift | 11 +- Museion/ProfileBackup.swift | 65 ++- Museion/ProfileProvisioner.swift | 535 +++++++++++++++--- MuseionTests/AGENTS.md | 2 +- MuseionTests/ProfileBackupTests.swift | 71 ++- .../ProfileProvisionerFailureTests.swift | 54 +- MuseionTests/ProfileProvisionerTests.swift | 182 +++--- MuseionTests/ProfileSkillMigrationTests.swift | 137 +++++ MuseionTests/ProfileSurfaceTests.swift | 365 ++++++++++++ ...rofiles-s1-registry-provisioning-x3_log.md | 74 +++ docs/devlog/INDEX.md | 1 + ref/writing skills/AGENTS.md | 4 +- 15 files changed, 1292 insertions(+), 232 deletions(-) create mode 100644 MuseionTests/ProfileSkillMigrationTests.swift create mode 100644 MuseionTests/ProfileSurfaceTests.swift create mode 100644 docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md diff --git a/AGENTS.md b/AGENTS.md index 63f6858..51d2886 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (4372 symbols, 15690 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (4735 symbols, 16431 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -179,7 +179,8 @@ This project is indexed by GitNexus as **museion** (4372 symbols, 15690 relation ### Testing - Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) -- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31) +- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) +- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift ` check of the pure logic still verify honestly (#134) ## Session Logs @@ -188,6 +189,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | | 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md) | | 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | | 2026-10-22 | [20261022-issue29-research-library-light_log.md](docs/devlog/20261022-issue29-research-library-light_log.md) | @@ -197,5 +199,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) | | 2026-10-20 | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](docs/devlog/20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) | | 2026-10-20 | [20261020-issue24-pass-guard-matrix_log.md](docs/devlog/20261020-issue24-pass-guard-matrix_log.md) | -| 2026-10-20 | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](docs/devlog/20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 95cd2e7..8c1e8fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **profiles:** Profiles S1 — surface registry + provisioning ×3 (PRD #134, ADR-0014) — one gate pass now provisions ALL THREE Hermes profiles: `museion` is adopted in place (never re-created or reconfigured — its model stays the user's), `museion-pass1`/`museion-pass2` are created fresh with the #132 defaults (`claude-sonnet-5-5` on anthropic, reasoning effort unset, 24k output budget as a guardrail) written via the engine's own `hermes -p config set` rail — wire-verified, marker-gated so a re-pass is a no-op and Settings changes survive, and a failed provision names the profile on the #48 card. Writing skills move to ONE master copy at `~/Library/Application Support/Museion/skills/` symlinked into each profile per the #133 allocation (Pass 1: 9 · Pass 2: 8 · Chat: 10 — the persona pair never co-occurs); today's copy-era dirs migrate to symlinks only on byte-match, diverged dirs stay copies, user skills untouched. Daily backup widens to one stamp carrying all three profiles — any live engine skips the whole stamp; restore docs name the three folders (issue #134) + - **stats:** First-draft stats capture (PRD S5.1) — running Pass 1 or Pass 2 on an unaided draft (writer-origin, First Draft Pass State, post type) computes four style metrics natively in Swift at the invocation — before the mentor sees anything — and stamps `stats_captured` plus four `stats_*` values into the piece's frontmatter, so the coming trend view is a scan of `posts/`; a cancelled pass keeps its capture, re-runs while still First Draft overwrite (latest draft wins), and the frontmatter write paths (pass completion, editor save) now update their keys in place instead of rebuilding the block — captured stats and foreign YAML survive (issue #31) - **sessions:** New Post from Session & drill offers (PRD S2.7/S2.8) — a freeform Session births a Post: "New Post" in the Sessions pane opens an ask-before sheet prefilled with the session's last mentor reply (editable, G9), and ONE confirm materializes the piece under `projects/posts/` stamped `origin: ai` — immutable frontmatter, never stats-eligible — and opens it in Posts; a failed write keeps the sheet up with the reason inline and the draft intact. "New Brainstorm" is a session started with an opener prompt (session flavor, no new machinery). The freeform composer (input + liveness + Stop) moved into the shared `SessionTranscriptView`, so both session surfaces are conversations; session-born pieces and the resume rail are pinned (issue #30). Resume now speaks the REAL adapter wire: 0.21.5 answers `session/load` with `_meta.hermes.sessionProvenance.acpSessionId` and no top-level `sessionId` — resume accepts both shapes (live-probed; every prior real-engine resume misread as "unknown") (issue #30) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index f06a054..e63d655 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -48,19 +48,19 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` fires provisioning (#47) in parallel on pass. - Tests: `MuseionTests/EngineGateTests.swift` builds fake `hermes` shell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records. -## Profile provisioning (S2.1, tickets #43–#48) +## Profile provisioning (S2.1 #43–#48; #134 Profiles S1) -- `ProfileProvisioner.swift` — `ProfileProvisioner` (nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawn `hermes profile create museion --no-alias --no-skills` only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: `seed-manifest.txt` in the payload root is the inclusion list (blank/`#` lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping `skills/`); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned `.`-prefixed temp dirs from an interrupted copy are swept at pass start; `.DS_Store` purged from copies. One os_log line per pass (`seeded writing skills: , … (N copied, M present)`) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). `ProvisioningModel` (@MainActor @Observable): runs the pass off-main, guards stacking, records `lastFailure` (phase-named copy + excerpt); failure never re-raises the gate. **#23 register phase:** after a seeded pass (and only when BOTH `hermesBinary` and `serverBinaryPath` are non-nil — production always has both after a gate pass; nil = the test-injection seam, skipped with one os_log line), `registerTools` runs `hermes -p museion mcp list` — "museion-tools" present → idempotent skip (a stale binary path after an app move is refreshed manually via `hermes -p museion mcp remove museion-tools` — ponytail ceiling) — else `hermes -p museion mcp add museion-tools --command --args --serve-mcp` with stdin fed repeated "y" lines (the CLI's final "Enable all tools? [Y/n]" prompt cancels on EOF, and profile-startup stdin consumers can burn a line — observed live; one y cancelled the save). Success = exit 0 + stdout "Saved 'museion-tools'"; anything else → `.failed(phase: .register)` through the #48 rail. The add LIVE-PROBES the server (spawns the app binary `--serve-mcp` — the headless launcher branch). -- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented` = `hasFailure && gateDismissed`, where `gateDismissed` is set in the gate sheet's `onDismiss` — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into `@State` so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (`deferFailure`) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning never hand-writes the profile config — the ONLY writer of an `mcp_servers` entry is the `hermes mcp add` CLI rail (#44 invariant as amended by #23/ADR-0008: config.yaml stays byte-identical through provisioning passes; registration itself goes through the engine's own command, test-pinned). -- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills seeded; `ste-writing`/`writing-for-agents` ship but never seed. -- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `/profiles/`; **#23:** the fake also speaks `-p museion mcp list`/`mcp add` — marker file for "already registered", invocation log asserting the exact add command line, one stdin line read, `mcp-add-fails` reject knob), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload; registration tests: fresh pass adds via the CLI with the exact command line, already-registered skips, probe failure → `.failed(.register)`. +- `ProfileProvisioner.swift` — the #134 surface registry + the provisioner. **`ProfileSurface`** (nonisolated enum, chat/pass1/pass2; declaration order = provision order — chat first so the resident surface is healthy before any pass-profile failure stops the loop): `profileName` (museion adopted in place / museion-pass1 / museion-pass2, Sessions rides Chat per #126), `allocatedSkills` (#133 table: P1 9 · P2 8 · Chat 10, persona pair never co-occurring), `init?(passKind:)` (the PassKind→profile seam), and the #132 fresh-seed defaults as constants (`defaultModelProvider` anthropic, `defaultModelID` claude-sonnet-5-5, `outputBudgetTokens` 24000 — reasoning_effort never written). **`ProfileProvisioner.perform`** (nonisolated): one idempotent pass = master-seed + per-surface phases. Phase 0 master: every manifest skill seeded additively as REAL dirs into the ONE master copy at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable) — `seed-manifest.txt` is still the shipped-set list (kebab-validated at the trust boundary); temp+rename per skill, never touch present ones, orphaned `.`-temps swept, `.DS_Store` purged. Then per surface (first failure wins; the next pass heals): **create** — dir-check first, `hermes profile create --no-alias --no-skills` only when missing (#43 already-exists semantics); `museion` is adopted, never re-created (ADR-0014). **configure** — the #132 defaults written through the engine's own CLI (`hermes -p config set model.provider/model.default/model.extra_body.max_tokens 24000 --force`, provider first — switching providers clears a stale inherited base_url, live-probed; #128: never rely on create-time inheritance); success is WIRE-VERIFIED (`exit 0` + `✓ Set ` on stdout — not exit code alone, finish-audit) and a marker write that fails surfaces as a configure-phase failure (an unrecorded configure must not count as done). MARKER-GATED by `.museion-provisioned` in the profile dir so a re-pass is a no-op and a user's later Settings change survives: runs for fresh creates and for an unconfigured PASS profile (interrupted before its marker landed — Retry heals); the adopted museion is NEVER configured (its glm-5.3-max is the user's until Settings switches it). **skills** — per profile, symlink each manifest name into the master: an existing link (live or dangling) is never retargeted; a copy-era REAL dir swaps to a symlink only on `treesByteMatch` against the MASTER (the link's target — identical to the payload on first seed; `.DS_Store` filtered from both listings so a Finder-browsed dir still migrates) with move-aside → link → delete-aside, restored on failure; a diverged dir stays a copy, untracked/user skills never touched (G3a); a missing skill links only when the surface ALLOCATES it (curation). **register** — museion-tools per profile (ADR-0008 amendment): `-p mcp list` skip / `mcp add` with repeated-y stdin, both binaries required (nil = test seam). `Outcome.seeded(copied:present:)` aggregates master copies + links; `.failed(profile:phase:excerpt:)` names the profile (nil for payload-level failures) — phases create/copy/register/configure. `ProvisioningModel` unchanged in shape; `runPass` gained `masterRoot`. +- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented`); phase rawValue is the title with the failing profile name in mono beneath (#134 — with three profiles, "which one?" is the first question; nil profile hides the row), excerpt behind Technical details; card snapshots the failure into `@State`; Retry re-runs the whole idempotent pass, Not Now defers to next launch. Provisioning still never hand-writes profile config — mcp registration AND the model defaults both go through the engine's own `hermes` CLI (#44 as amended by #23/ADR-0008 and #134/ADR-0014: the provisioner writes no config.yaml bytes itself, but a FRESH pass profile's config.yaml IS legitimately written by `config set` — byte-identity now holds only for adopted/engine-owned configs, test-pinned). +- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills ship; the master seeds all 11, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed. +- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profiles at `/profiles/`, speaks `-p mcp list`/`mcp add` with per-profile marker/invocation files and `config set` with a per-profile argv log + `config-set-fails`/`mcp-add-fails` knobs, logs every `profile create`), injected profile/payload/master dirs, manifest ↔ payload correspondence. **#134:** `ProfileSurfaceTests.swift` (own file) pins the registry (names/order, PassKind mapping, allocation counts + persona split, defaults, allocation ⊆ bundled manifest), ×3 provisioning with exact config-set command lines, master-once + per-allocation symlinks, re-pass no-op (config-set log byte-stable, no re-creates), adopted-museion untouched, marker heal/no-stomp, failing provision names the profile, configure-phase failure. `ProfileSkillMigrationTests.swift` (own file) pins the byte-match migration (browsed dir with `.DS_Store` still migrates, content identical through the swap; diverged stays a copy; untracked untouched; a symlinked entry inside a copy-era dir refuses the match — never followed, finish-audit). Failure-path tests in `ProfileProvisionerFailureTests.swift` (config.yaml byte-identity through failed/nil-skip/CLI-registering passes, fresh-profile case in its own test, copy-phase catch, path traversal, orphan sweep). ## Profile backup (S2.6, #15 map / #50) -- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on gate pass **after** the provisioning pass finishes (await chain in `ContentView.onEnginePass` — a failed provision doesn't skip the backup). Liveness gate first: `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + `ps ax -o command=` scan for `profiles/museion` / `-p museion` (`psScan` injectable for tests); either live → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: recursive enumerator with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars. Directories are `createDirectory`d, files `copyItem`d (the enumerator re-yields children — whole-subtree copyItem would collide); a file vanishing mid-copy is skipped. Install: copy into `.-` temp dir, rename into `~/Library/Application Support/Museion/Backups//`, prune past 7 after a successful rename. `RESTORE.md` (manual Finder copy-back instructions) written once into the Backups root. Failure = one os_log line, never an alert (contrast #45's provisioning card); constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`). +- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on gate pass **after** the provisioning pass finishes (await chain in `ContentView.onEnginePass` — a failed provision doesn't skip the backup). **#134/#129 — one stamp, three subdirs:** the sources are the three surface profiles from `ProfileSurface.allCases`; a missing profile dir is simply absent from the stamp (only NO profile at all → `.skippedProfileMissing`); NEVER the profiles root (non-Museion profiles are not ours to back up). Any-live-skip-all: every existing profile dir must be idle or the WHOLE stamp skips (one stamp = one consistent point in time) — per-dir `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + the `ps ax -o command=` scan for `profiles/museion` / `-p museion` (already substring-matches the pass profiles; `psScan` injectable for tests) → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: per profile into `//`, recursive walk with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars; dir symlinks resolve (`fileExists(isDirectory:)` follows) so profile skill symlinks snapshot as content, keeping restores self-contained (#133 folded). A file vanishing mid-copy is skipped. Install: copy into `.-` temp dir, rename into `~/Library/Application Support/Museion/Backups//`, prune past 7 after a successful rename. `RESTORE.md` documents the three folders (written once into the Backups root). Failure = one os_log line, never an alert; constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`). - `BackupModel` (@MainActor @Observable): app-scoped (`AppGateState.backup`), runs the pass off-main, guards stacking, records `lastOutcome` (informational only — no UI). - UI: Help → **Open Backup Folder** (`OpenBackupFolderButton` in `MuseionApp.swift`) reveals the Backups root in Finder; restore docs live in `RESTORE.md` beside the snapshots. -- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan: liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept). +- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan (`makeProfileFixture(at:name:)` builds any profile): liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept). **#134:** one stamp carries all three profile dirs with RESTORE.md naming them, a live PASS-profile pid skips the whole stamp (nothing half-written), missing pass profiles snapshot the rest. ## museion-tools MCP server (S2.4, #23) diff --git a/Museion/EngineGateView.swift b/Museion/EngineGateView.swift index 7f1b721..fd35610 100644 --- a/Museion/EngineGateView.swift +++ b/Museion/EngineGateView.swift @@ -172,14 +172,21 @@ struct ProvisioningFailureCard: View { @State private var failure: ProfileProvisioner.Outcome? var body: some View { - if let failure, case let .failed(phase, excerpt) = failure { + if let failure, case let .failed(profile, phase, excerpt) = failure { VStack(spacing: 14) { Image(systemName: "exclamationmark.triangle.fill") .font(.system(size: 30)) .foregroundStyle(.orange) Text(phase.rawValue) .font(.title3) - Text("Museion couldn't finish setting up the mentor's writing profile. Nothing is lost — the setup is safe to run again.") + if let profile { + // #134: the card names the failing profile — with three + // surface profiles, "which one?" is the first question. + Text(profile) + .font(.system(size: 10, design: .monospaced)) + .foregroundStyle(.tertiary) + } + Text("Museion couldn't finish setting up the writing profiles. Nothing is lost — the setup is safe to run again.") .font(.callout) .foregroundStyle(.secondary) .multilineTextAlignment(.center) diff --git a/Museion/ProfileBackup.swift b/Museion/ProfileBackup.swift index ef349fd..f6d4a7d 100644 --- a/Museion/ProfileBackup.swift +++ b/Museion/ProfileBackup.swift @@ -4,6 +4,10 @@ // // S2.6 daily profile backup (#50): liveness-gated, once-a-day FileManager // copy of the museion profile into timestamped snapshots, last 7 kept. +// #134 (Profiles S1, #129): one stamp carries all three surface profiles +// as subdirs — museion, museion-pass1, museion-pass2. Any live engine +// skips the WHOLE stamp; never the profiles root (non-Museion profiles +// are not ours to back up). // import Foundation @@ -43,8 +47,12 @@ nonisolated enum ProfileBackup { case failed } - /// One backup pass. Runs on gate pass, sequenced after the provisioning - /// pass finishes (success or failure — a failed provision doesn't skip it). + /// One backup pass over the three surface profiles (#129/#134): one + /// stamp, three subdirs. Runs on gate pass, sequenced after the + /// provisioning pass finishes (success or failure — a failed provision + /// doesn't skip it). A profile dir that doesn't exist (provisioning + /// hasn't landed yet) is simply absent from the stamp; only NO profile + /// at all skips. /// - Parameters: /// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`). /// - backupsRoot: snapshots base dir (tests inject; default Museion's @@ -57,12 +65,19 @@ nonisolated enum ProfileBackup { psScan: () -> Bool = psContainsMuseion, ) -> Outcome { let fileManager = FileManager.default - let source = (profileRoot as NSString).appendingPathComponent("museion") - guard fileManager.fileExists(atPath: source) else { - logInfo("skipped — museion profile missing") + let sources = ProfileSurface.allCases + .map { (profileRoot as NSString).appendingPathComponent($0.profileName) } + .filter { fileManager.fileExists(atPath: $0) } + guard !sources.isEmpty else { + logInfo("skipped — no profile found") return .skippedProfileMissing } - guard engineIdle(profileDir: source, psScan: psScan) else { + // Any-live-skip-all (#129): one stamp = one consistent point in time. + // The ps scan already substring-matches the pass profiles + // (`profiles/museion` / `-p museion`), so ONE scan answers for all + // (finish-audit: hoisted — per-dir evaluation spawned it up to 3×); + // the pid check stays per dir. + guard !psScan(), sources.allSatisfy({ idleProfileDir($0) }) else { logInfo("skipped — engine running (liveness gate)") return .skippedEngineRunning } @@ -82,15 +97,18 @@ nonisolated enum ProfileBackup { try fileManager.createDirectory(atPath: backupsRoot, withIntermediateDirectories: true) writeRestoreDocIfMissing(into: backupsRoot) try fileManager.createDirectory(atPath: tempDir, withIntermediateDirectories: true) - // Snapshot layout: /museion/ — the folder - // name travels with the snapshot, so restore is one copy-back. - let payloadDir = (tempDir as NSString).appendingPathComponent("museion") - try fileManager.createDirectory(atPath: payloadDir, withIntermediateDirectories: true) - try copyTree(from: source, to: payloadDir) + // Snapshot layout (#129): /{museion, museion-pass1, + // museion-pass2}/ — the folder name travels with + // the snapshot, so restore is one copy-back. + for source in sources { + let payloadDir = (tempDir as NSString).appendingPathComponent((source as NSString).lastPathComponent) + try fileManager.createDirectory(atPath: payloadDir, withIntermediateDirectories: true) + try copyTree(from: source, to: payloadDir) + } // Atomic install (seed-phase pattern): rename into place, then prune. try fileManager.moveItem(atPath: tempDir, toPath: finalDir) prune(backupsRoot: backupsRoot) - logInfo("snapshot complete: \(stamp)") + logInfo("snapshot complete: \(stamp) (\(sources.count) profiles)") return .snapshotted(stamp: stamp) } catch { try? fileManager.removeItem(atPath: tempDir) @@ -112,19 +130,19 @@ nonisolated enum ProfileBackup { let path = (backupsRoot as NSString).appendingPathComponent("RESTORE.md") guard !FileManager.default.fileExists(atPath: path) else { return } let doc = """ - # Restoring the writing profile + # Restoring the writing profiles - Each folder here is a full snapshot of the writing profile \ - (`~/.hermes/profiles/museion`), taken once a day when Museion launches.\ - The 7 most recent are kept. + Each folder here is a full snapshot of Museion's writing profiles \ + (`~/.hermes/profiles/museion`, `museion-pass1`, and `museion-pass2`),\ + taken once a day when Museion launches. The 7 most recent are kept. ## Restore (manual, v1) 1. Quit Museion (and any running Hermes engine). 2. Pick the newest healthy snapshot folder. - 3. Copy the `museion` folder inside it back to `~/.hermes/profiles/`,\ - replacing the damaged one (rename the old one aside first if you want\ - it kept). + 3. Copy the profile folders inside it back to `~/.hermes/profiles/`,\ + replacing the damaged ones (rename the old ones aside first if you\ + want them kept). 4. Relaunch Museion. Note: logs, caches, and lock files are excluded from snapshots by\ @@ -149,11 +167,18 @@ nonisolated enum ProfileBackup { /// the file can be stale) + `ps ax -o command=` scan for `profiles/museion` /// or `-p museion`. Either signal live → the engine is running. static func engineIdle(profileDir: String, psScan: () -> Bool = psContainsMuseion) -> Bool { + idleProfileDir(profileDir) && !psScan() + } + + /// The per-dir half of the liveness gate: gateway.pid liveness only — + /// the ps scan is global (one scan answers for every surface profile), + /// so the caller evaluates it once. + private static func idleProfileDir(_ profileDir: String) -> Bool { let pidPath = (profileDir as NSString).appendingPathComponent("gateway.pid") if let pid = parsePID(fromFile: pidPath), kill(pid, 0) == 0 { return false } - return !psScan() + return true } /// The gateway's pid file is a JSON line (`{"pid":…, "hermes_home":"…"}` — diff --git a/Museion/ProfileProvisioner.swift b/Museion/ProfileProvisioner.swift index 13ae972..e21c3f3 100644 --- a/Museion/ProfileProvisioner.swift +++ b/Museion/ProfileProvisioner.swift @@ -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 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 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 = 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 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 } diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index ffe1710..d5783f1 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -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-` 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 `/profiles/` (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 `/profiles/` (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 mcp list`/`mcp add` (per-profile marker `mcp-registered-` = already registered, invocation log `mcp-add-invocation-` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p config set` (argv log `config-set-`, `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///` + `archive///` (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///` + #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///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. diff --git a/MuseionTests/ProfileBackupTests.swift b/MuseionTests/ProfileBackupTests.swift index 357c4af..60c189a 100644 --- a/MuseionTests/ProfileBackupTests.swift +++ b/MuseionTests/ProfileBackupTests.swift @@ -19,13 +19,14 @@ func backupTempDir(_ label: String) -> String { return dir } -/// Minimal profile fixture at `/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 `/` (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) diff --git a/MuseionTests/ProfileProvisionerFailureTests.swift b/MuseionTests/ProfileProvisionerFailureTests.swift index f7cd9b8..9ebb8c2 100644 --- a/MuseionTests/ProfileProvisionerFailureTests.swift +++ b/MuseionTests/ProfileProvisionerFailureTests.swift @@ -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 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:")) } diff --git a/MuseionTests/ProfileProvisionerTests.swift b/MuseionTests/ProfileProvisionerTests.swift index 1433ac8..7463c63 100644 --- a/MuseionTests/ProfileProvisionerTests.swift +++ b/MuseionTests/ProfileProvisionerTests.swift @@ -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 `/profiles/` +// Convention: the fake creates profiles at `/profiles/` // (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 `/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 `/mcp-add-invocation`, drops the -/// marker, prints "Saved 'museion-tools' to …" (verified wire strings). -/// `/mcp-add-fails` forces "Error: mcp add exploded", exit 1. +/// Also speaks `mcp` and `config set` behind the `-p ` global flag +/// (#23, #134): `mcp list` prints "museion-tools" iff +/// `/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 `/mcp-add-invocation-`, drops the +/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire +/// strings). `config set [--force]` appends the exact argv to +/// `/config-set-` and prints the verified "✓ Set …" line. +/// `/mcp-add-fails` / `config-set-fails` force the matching +/// failure. Every `profile create` name appends to +/// `/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) } diff --git a/MuseionTests/ProfileSkillMigrationTests.swift b/MuseionTests/ProfileSkillMigrationTests.swift new file mode 100644 index 0000000..4865358 --- /dev/null +++ b/MuseionTests/ProfileSkillMigrationTests.swift @@ -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") + } +} diff --git a/MuseionTests/ProfileSurfaceTests.swift b/MuseionTests/ProfileSurfaceTests.swift new file mode 100644 index 0000000..ce290fb --- /dev/null +++ b/MuseionTests/ProfileSurfaceTests.swift @@ -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 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")) + } +} diff --git a/docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md b/docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md new file mode 100644 index 0000000..0824234 --- /dev/null +++ b/docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md @@ -0,0 +1,74 @@ +# Profiles S1 — Profile registry + provisioning ×3 (#134) + +> **Date:** 2026-10-27 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/134 + +## Goal + +Implement ticket #134 (Profiles S1, ADR-0014): the static surface→profile map, the ×3 provisioner at the unchanged binary-gate onPass seam, the #133 skills master+symlink architecture with copy-era migration, the #129 three-profile backup widening, and the profile-named #48 failure card. Grounding: #126/#128/#129/#132/#133 all closed with recorded decisions; this is the build slice. + +## Verification + +- **Full suite (post-reboot, runner recovered): 412 passed / 414 total.** The two failures decompose honestly: `SessionLifecycleTests/fork activates a fresh transcript and refuses unknown honestly` passes in isolation (whole suite 16/16 green — the fake-ACP load-flake pattern of project learning #30), and `MuseionUITests.testAppLaunches` died at 0.000 s with "Lost connection to testmanagerd" — the same automation-infrastructure flake that failed identically in the pre-change baseline (2026-10-26 13:09, 396 passed / 1 UI-runner failure). Unit suite effectively 412/412. +- `xcodebuild build` and `build-for-testing` SUCCEEDED at every stage including all review fixes. +- `treesByteMatch` (the migration's pure logic) verified by direct execution — standalone Swift check, 6/6 cases including the .DS_Store-browsed and symlinked-entry refusals. + +## What Was Done + +- `Museion/ProfileProvisioner.swift` — new `ProfileSurface` registry (chat/pass1/pass2 → museion adopted / museion-pass1 / museion-pass2; #133 allocation table 9·8·10 with the persona pair never co-occurring; #132 defaults as constants: anthropic / claude-sonnet-5-5 / 24000 budget, reasoning_effort never written; `init?(passKind:)` seam). `perform` reworked: phase 0 seeds the ONE master copy at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable), then per surface — create/adopt (`museion` never re-created), marker-gated configure via `hermes -p config set` (provider→model→budget `--force`, live-probed wire), per-allocation skill symlinks + copy-era→symlink migration on `treesByteMatch` against the master, museion-tools registration per profile. `provisionSurface` extracted (complexity/length ceilings); pure FS helpers moved to a `nonisolated extension`. `Outcome.failed(profile:phase:excerpt:)` names the profile. +- `Museion/ProfileBackup.swift` — one stamp, three subdirs from `ProfileSurface.allCases`; any-live-skip-all (single hoisted ps scan + per-dir pid checks via extracted `idleProfileDir`); missing profiles absent from the stamp, never the profiles root; RESTORE.md documents three folders. +- `Museion/EngineGateView.swift` — the #48 failure card renders the failing profile name in mono under the phase title. +- Tests — `ProfileProvisionerTests.swift` reworked (fake hermes speaks `-p mcp` + `config set`, per-profile marker/invocation logs, create log); `ProfileSurfaceTests.swift` + `ProfileSkillMigrationTests.swift` (new files, scenario headers); `ProfileProvisionerFailureTests.swift` and `ProfileBackupTests.swift` updated (+3 new backup tests). 16 new tests total. +- DOX — `Museion/AGENTS.md` (provisioning + backup sections rewritten for ×3, the #44 config.yaml byte-identity sentence scoped to adopted configs), `MuseionTests/AGENTS.md`, `ref/writing skills/AGENTS.md` (master+symlink seeding contract). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Configure phase marker-gated by `.museion-provisioned`, not fresh-create-only | Fresh-only leaves a hole: configure fails → Retry sees the existing dir → config never re-written → profile silently stranded on inherited glm config. The marker makes re-pass a true no-op, heals interrupted provisions, and never stomps a user's later Settings change. The adopted museion is exempt (existing without marker = pre-S1 profile, never configured). | +| Migration byte-match compares against the MASTER, not the payload | The swap must be invisible through the link; on first seed master==payload so behavior matches #133's letter, and after an app update a lagging master keeps the copy rather than silently changing skill content. | +| Provision order chat → pass1 → pass2 | The resident surface gets every chance to be healthy before a pass-profile failure stops the loop (first failure wins). | +| `.seeded(copied:present:)` aggregates master copies + links | Kept the existing outcome shape; the log line says "linked/copied". Renaming labels across ~30 test sites buys nothing (declined in review). | +| `init?(passKind:)` kept though test-only today | It IS the registry-mapping acceptance criterion's seam — PassKind→profile is the mapping being pinned; the S2 engine-spawn slice consumes it next. | +| `ConfigWrite` struct over a labeled tuple | The 3-member tuple trips SwiftLint's enforced `large_tuple`; tooling overrides the ponytail smell baseline (declined in review). | +| Migration applies to all manifest-tracked dirs regardless of allocation | Migration is storage conversion (copy→link), not curation; curation only governs NEW links on fresh profiles (G3a additive-only keeps existing extras). | +| Two security Info findings deferred | `.public` logging of CLI-authored excerpts and the ×3 credentials fan-out in backup stamps are both documented #15/log posture on a single-user unsandboxed host — parked visibly, not silently dropped. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Test runner wedged mid-session ("Timed out while preparing IDE session" / "control session with daemon") | Machine-level Xcode test infrastructure degradation, pre-existing (baseline UI-runner failure was the first symptom); every reset short of reboot failed | User rebooted overnight — post-reboot full suite ran. Baseline-vs-after comparison kept honest by the pre-change 13:09 run | +| `treesByteMatch`'s `.DS_Store` leniency was dead code — a Finder-browsed copy-era dir would NEVER migrate and the pinning test shipped red | Strict entry-name equality ran BEFORE the filter; the master side is purged at seed so name lists differ | Filter `.DS_Store` from BOTH listings before equality (spec reviewer catch; verified by direct execution 6/6) | +| mcp-rail test's third perform pinned `(0,8)` but re-derives to `(2,6)` — guaranteed red | Each perform inlined a FRESH `masterRoot` (provTempDir per call) — my fixture sloppiness | Hoisted ONE shared master; second pin corrected to `(6,2)` (the failed pass pre-seeds it), third `(0,8)` now holds (general-reviewer catch, hand-re-derived) | +| `config set` trusted exit code alone; marker write swallowed failures | Both could silently mis-mark a profile configured (exit-0-writes-nothing CLI; disk-full marker) → defaults stomp on every later pass | Wire-verify `✓ Set ` on stdout (matches `mcp add`'s posture); `markConfigured` failure surfaces as a configure-phase failure — both pinned | +| `treesByteMatch` followed symlinks in the untrusted copy-era tree (FIFO hang / unbounded read) | fileExists/Data(contentsOf:) follow links | Symlinked entry on either side refuses the match before any open — pinned | +| Swift 6 default-MainActor: extension members became MainActor-isolated vs the nonisolated enum | Extensions don't inherit the enum's `nonisolated` | `nonisolated extension ProfileProvisioner` | +| Vacuous single-test `-only-testing` runs (exit 0, zero tests executed) | Swift Testing identifiers with spaces/backticks don't match the filter form | Learning #31 discipline: verify by the xcresult executed count; ran the whole suite instead | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/ProfileProvisioner.swift` | ProfileSurface registry + ×3 provisioner, master+symlinks+migration, marker-gated config set, nonisolated extension split | +| `Museion/ProfileBackup.swift` | Three-subdir stamps, any-live-skip-all (hoisted scan), RESTORE.md ×3 | +| `Museion/EngineGateView.swift` | Failure card names the failing profile | +| `MuseionTests/ProfileProvisionerTests.swift` | Fake hermes ×3-capable (config set, per-profile mcp), suites updated | +| `MuseionTests/ProfileSurfaceTests.swift` | NEW — registry, ×3 provisioning, config-set lines, symlinks, no-op, adoption, marker, failures | +| `MuseionTests/ProfileSkillMigrationTests.swift` | NEW — byte-match migration, diverged/untracked/symlink refusals | +| `MuseionTests/ProfileProvisionerFailureTests.swift` | ×3 expectations, shared master, fresh-profile case split out | +| `MuseionTests/ProfileBackupTests.swift` | Fixture name param + three-profile/any-live/partial tests | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `ref/writing skills/AGENTS.md` | DOX pass for the ×3 world | +| `.swiftlint.yml` | (reverted — an invalid `allowed_terms` key for this SwiftLint version) | + +## Open Items & Next Steps + +- [ ] Settings build slice (#130) — reads/writes the per-surface model blocks via the same `config set` rail; the registry and marker are its seam. +- [ ] Profiles S2 — pass engines spawn `hermes acp -p museion-passN` (consumes `ProfileSurface(passKind:)`); Chat auto-restart on model change per #129. +- [ ] Deferred security notes: `.public` CLI-excerpt logging; credentials fan-out ×3 in backup stamps (documented posture, revisit if multi-user context appears). +- [ ] `MuseionUITests.testAppLaunches` testmanagerd flake — environment-level, pre-dates this slice; consider `git retry`-style tolerance or a CI marker if it recurs. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 00c42b0..9d1308a 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-10-27 | issue | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | #134 Profiles S1: ×3 surface registry + provisioner, master-symlink skills with byte-match migration, three-profile backup; 412 tests | | 2026-10-22 | issue | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | #31 S5.1: Swift-native first-draft stats stamped in place at pass invocation; two frontmatter-erasure bugs fixed; finish-audit fanout — 396 tests | | 2026-10-22 | issue | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | #30 lands: session-born Posts stamp origin: ai, brainstorm flavor, shared composer, and the real-engine resume wire fix. | | 2026-10-22 | issue | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) | #29 research rail: submit_research_notes candidates in-session, ask-before keep into research/, resume replay pin, audit fixes — targeted suites green | diff --git a/ref/writing skills/AGENTS.md b/ref/writing skills/AGENTS.md index 00f68ee..5b31e3f 100644 --- a/ref/writing skills/AGENTS.md +++ b/ref/writing skills/AGENTS.md @@ -2,7 +2,7 @@ ## Purpose -The bundled writing-skill set — the mentor's mind as markdown skills. This is the G3a payload: shipped as app resources and seeded additively into `~/.hermes/profiles/museion/skills/` at first run. Spec and member list: PRD.md, "The bundled skill set". +The bundled writing-skill set — the mentor's mind as markdown skills. This is the G3a payload: shipped as app resources, seeded additively into the ONE master copy at `~/Library/Application Support/Museion/skills/` at first run, and symlinked from there into each surface profile per the #133 allocation (Pass 1: 9 · Pass 2: 8 · Chat: 10 — the persona pair never co-occurs). Spec and member list: PRD.md, "The bundled skill set". ## Ownership @@ -12,7 +12,7 @@ Owned by the root AGENTS.md contract. Vocabulary is bound by CONTEXT.md (Mentor, - One skill per kebab-case directory holding a `SKILL.md`. - Frontmatter: `name`, `description` (quoted string), `license: GNU GPLv3`, `metadata` (author, email, version). -- Seeding is additive-only: bundled skills land in the profile if absent; existing profile skills are never overwritten. +- Seeding is additive-only: bundled skills land in the master if absent; existing master skills and profile skills are never overwritten. Copy-era real dirs in a profile migrate to master symlinks only on byte-match (a diverged dir stays a copy); untracked/user skills are never touched. - `seed-manifest.txt` lists the shipped set — update it when adding or removing a mentor skill. `ste-writing` and `writing-for-agents` stay in ref/ as authoring tools, never seeded. - Deslop owns the single subtractive rule set; serif-writing owns the method. Other skills reference both; none restates them. - The persona pair shares three sections verbatim by design (Knife floor, silent learnings, voice anchor) — edit them together or not at all.