Files
museion/MuseionTests/ProfileBackupTests.swift
AlexKucera 610f8789bd
CI / ci (push) Canceled after 0s
feat(profiles): registry + provisioning ×3
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
2026-10-27 09:23:56 +01:00

263 lines
11 KiB
Swift

//
// ProfileBackupTests.swift
// MuseionTests
//
// Exercises the backup pass end-to-end on injected dirs (#50): liveness
// branches, exclusion list, credentials & sidecars, age check, retention,
// atomic install, failure path. `psScan` is injected (a dev machine may run
// the real engine); the clock is injected for the age check.
//
import Foundation
@testable import Museion
import Testing
/// Backup-test temp dir (distinct name from the other suites).
func backupTempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-backup-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir
}
/// Minimal profile fixture at `<root>/<name>` (default the chat profile):
/// state that matters to a restore (auth.json, .env, state.db + sidecars, a
/// skill) plus excluded entries (logs/, cache/, gateway.pid, .DS_Store,
/// caches, locks). #134: name parameterized for the pass profiles.
@discardableResult
func makeProfileFixture(at root: String, name: String = "museion") -> String {
let fileManager = FileManager.default
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),
withIntermediateDirectories: true,
)
}
func write(_ text: String, _ rel: String) {
try? text.write(
toFile: (profile as NSString).appendingPathComponent(rel),
atomically: true, encoding: .utf8,
)
}
write("{\"token\": \"secret\"}", "auth.json")
write("KEY=1", ".env")
write("db", "state.db")
write("wal", "state.db-wal")
write("shm", "state.db-shm")
write("skill body", "skills/serif-writing/SKILL.md")
write("log", "logs/app.log")
write("{}", "gateway.pid")
write("junk", ".DS_Store")
write("{}", "models_dev_cache.json")
write("{}", "provider_models_cache.json")
write("{}", "context_length_cache.yaml")
write("lock", "auth.lock")
return profile
}
private func snapshotDirs(_ backupsRoot: String) -> [String] {
(try? FileManager.default.contentsOfDirectory(atPath: backupsRoot))?.sorted() ?? []
}
private func epoch(_ year: Int, _ month: Int, _ day: Int, _ hour: Int = 0, _ minute: Int = 0) -> Date {
var comps = DateComponents()
comps.year = year
comps.month = month
comps.day = day
comps.hour = hour
comps.minute = minute
comps.timeZone = .current
return Calendar(identifier: .gregorian).date(from: comps) ?? Date()
}
@Suite("ProfileBackupTests")
struct ProfileBackupTests {
private func perform(
profileRoot: String,
backupsRoot: String,
now: Date = epoch(2026, 9, 25, 10, 0),
psScan: @escaping () -> Bool = { false },
) -> ProfileBackup.Outcome {
ProfileBackup.perform(profileRoot: profileRoot, backupsRoot: backupsRoot, now: now, psScan: psScan)
}
@Test func `fresh pass snapshots with credentials and sidecars, exclusions applied`() {
let root = backupTempDir("fresh")
makeProfileFixture(at: root)
let backups = (root as NSString).appendingPathComponent("backups")
let outcome = perform(profileRoot: root, backupsRoot: backups)
guard case let .snapshotted(stamp) = outcome else {
Issue.record("expected snapshot, got \(outcome)")
return
}
let snap = ((backups as NSString).appendingPathComponent(stamp) as NSString).appendingPathComponent("museion")
let fileManager = FileManager.default
// Credentials + SQLite sidecars present (G4).
for rel in ["auth.json", ".env", "state.db", "state.db-wal", "state.db-shm", "skills/serif-writing/SKILL.md"] {
#expect(fileManager.fileExists(atPath: (snap as NSString).appendingPathComponent(rel)), "missing \(rel)")
}
// Exclusions: top-level and nested cache, locks, pid, .DS_Store, caches.
let excluded = ["logs", "cache", "sessions/xyz/cache", "gateway.pid", ".DS_Store",
"models_dev_cache.json", "provider_models_cache.json", "context_length_cache.yaml", "auth.lock"]
for rel in excluded {
#expect(!fileManager.fileExists(atPath: (snap as NSString).appendingPathComponent(rel)), "excluded \(rel) leaked")
}
}
@Test func `live gateway pid skips the pass`() {
let root = backupTempDir("pidlive")
let profile = makeProfileFixture(at: root)
// gateway.pid naming our own test process = a live pid.
try? "{\"pid\": \(ProcessInfo.processInfo.processIdentifier)}".write(
toFile: (profile as NSString).appendingPathComponent("gateway.pid"),
atomically: true, encoding: .utf8,
)
let outcome = perform(profileRoot: root, backupsRoot: (root as NSString).appendingPathComponent("backups"))
#expect(outcome == .skippedEngineRunning)
}
@Test func `stale pid falls through to ps scan and snapshots when idle`() {
let root = backupTempDir("pidstale")
let profile = makeProfileFixture(at: root)
try? "{\"pid\": 9999999}".write( // recorded but dead (verified pattern).
toFile: (profile as NSString).appendingPathComponent("gateway.pid"),
atomically: true, encoding: .utf8,
)
let outcome = perform(profileRoot: root, backupsRoot: (root as NSString).appendingPathComponent("backups"))
#expect(outcome != .skippedEngineRunning)
guard case .snapshotted = outcome else {
Issue.record("expected snapshot, got \(outcome)")
return
}
}
@Test func `ps match skips the pass`() {
let root = backupTempDir("pslive")
makeProfileFixture(at: root)
let outcome = perform(
profileRoot: root,
backupsRoot: (root as NSString).appendingPathComponent("backups"),
psScan: { true },
)
#expect(outcome == .skippedEngineRunning)
}
@Test func `fresh snapshot skips when newest is under 24h`() {
let root = backupTempDir("age")
makeProfileFixture(at: root)
let backups = (root as NSString).appendingPathComponent("backups")
let now = epoch(2026, 9, 25, 10, 0)
guard case .snapshotted = perform(profileRoot: root, backupsRoot: backups, now: now) else {
Issue.record("first snapshot failed")
return
}
#expect(perform(profileRoot: root, backupsRoot: backups, now: now.addingTimeInterval(23 * 3600)) == .skippedFresh)
#expect(perform(profileRoot: root, backupsRoot: backups, now: now.addingTimeInterval(25 * 3600)) != .skippedFresh)
}
@Test func `only the last 7 snapshots are kept`() {
let root = backupTempDir("retention")
makeProfileFixture(at: root)
let backups = (root as NSString).appendingPathComponent("backups")
for day in 0 ... 8 { // 9 daily passes
guard case .snapshotted = perform(
profileRoot: root, backupsRoot: backups,
now: epoch(2026, 9, 1 + day, 10, 0),
) else {
Issue.record("day \(day) snapshot failed")
return
}
}
let kept = snapshotDirs(backups).filter { $0 != "RESTORE.md" }
#expect(kept.count == 7)
#expect(!kept.contains("20260901-100000")) // oldest two pruned
#expect(!kept.contains("20260902-100000"))
#expect(kept.contains("20260909-100000")) // newest kept
}
@Test func `missing profile skips cleanly`() {
let root = backupTempDir("missing")
let outcome = perform(profileRoot: root, backupsRoot: (root as NSString).appendingPathComponent("backups"))
#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)
// Unreadable file mid-tree: copy throws; the pass must fail cleanly.
let unreadable = (profile as NSString).appendingPathComponent("skills/locked/SKILL.md")
try? FileManager.default.createDirectory(
atPath: (profile as NSString).appendingPathComponent("skills/locked"),
withIntermediateDirectories: true,
)
try? "x".write(toFile: unreadable, atomically: true, encoding: .utf8)
try? FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: unreadable)
let backups = (root as NSString).appendingPathComponent("backups")
let outcome = perform(profileRoot: root, backupsRoot: backups)
#expect(outcome == .failed)
#expect(snapshotDirs(backups).allSatisfy { !$0.hasPrefix(".") }) // temp swept
// Clean up the 000-mode file so the temp dir prunes.
try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: unreadable)
}
}