// // ProfileBackup.swift // Museion // // 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 import Observation import os /// One daily backup pass (#15 map, S2.6): liveness-gated FileManager copy of /// the museion profile into timestamped snapshots under Application Support. nonisolated enum ProfileBackup { /// Curated exclusions (#15 charting): logs and caches don't matter to a /// restore; stale locks would block a restored profile. Everything else /// copies — credentials and SQLite sidecars included (sidecar consistency /// comes from the liveness gate, not exclusion). private static let excludedDirectoryNames: Set = [ "logs", "cache", "audio_cache", "image_cache", ] private static let excludedFileNames: Set = [ ".DS_Store", "models_dev_cache.json", "models_dev_cache.json.etag", "provider_models_cache.json", "ollama_cloud_models_cache.json", "context_length_cache.yaml", ] private static let excludedFileNameSuffixes: [String] = [".pid", ".sock", ".lock"] /// Policy constants (#15): fixed in code, no settings surface in v1. /// ponytail: named constants, not a config type — a knob that never turns. static let retentionCount = 7 static let snapshotInterval: TimeInterval = 24 * 60 * 60 enum Outcome: Equatable, Sendable { case snapshotted(stamp: String) case skippedEngineRunning case skippedFresh case skippedProfileMissing /// Copy-phase failure — protection, not function (#15): retried at the /// next qualifying launch; never surfaces an alert. case failed } /// 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 /// Application Support / Backups). /// - now: clock injection for the age check (tests pass fixed dates). static func perform( profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath, backupsRoot: String = defaultBackupsRoot(), now: Date = Date(), psScan: () -> Bool = psContainsMuseion, ) -> Outcome { let fileManager = FileManager.default 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 } // 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 } // Age check against the newest existing snapshot (#15: skips record no // state; the normal age check governs retry). if let newest = sortedSnapshots(in: backupsRoot).first, now.timeIntervalSince(newest.timestamp) < snapshotInterval { return .skippedFresh } let stamp = Self.stamp(for: now) let finalDir = (backupsRoot as NSString).appendingPathComponent(stamp) let tempDir = (backupsRoot as NSString).appendingPathComponent(".\(stamp)-\(UUID().uuidString)") do { try fileManager.createDirectory(atPath: backupsRoot, withIntermediateDirectories: true) writeRestoreDocIfMissing(into: backupsRoot) try fileManager.createDirectory(atPath: tempDir, withIntermediateDirectories: true) // 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) (\(sources.count) profiles)") return .snapshotted(stamp: stamp) } catch { try? fileManager.removeItem(atPath: tempDir) logFailure(String(String(describing: error).prefix(300))) return .failed } } /// `~/Library/Application Support/Museion/Backups` (tests inject their own root). static func defaultBackupsRoot() -> String { ("~/Library/Application Support/Museion/Backups" as NSString).expandingTildeInPath } /// The restore help doc (#15: restore = manual Finder copy-back in v1), /// written once into the Backups root so it travels with the snapshots. /// ponytail: static text, not a bundled resource — it must land next to the /// snapshots it describes, even when the app that wrote them is gone. private static func writeRestoreDocIfMissing(into backupsRoot: String) { let path = (backupsRoot as NSString).appendingPathComponent("RESTORE.md") guard !FileManager.default.fileExists(atPath: path) else { return } let doc = """ # Restoring the writing profiles 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 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\ design; credentials are included. A snapshot is not a substitute for\ backing up your writing itself — posts live in your Museion Home,\ not here. [Museion — generated] """ try? doc.write(toFile: path, atomically: true, encoding: .utf8) } /// Timestamped dir name, lexicographically sortable (#15): YYYYMMDD-HHMMSS. private static func stamp(for date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd-HHmmss" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter.string(from: date) } /// Liveness gate (#15): gateway.pid liveness (parse pid, `kill(pid, 0)` — /// 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 true } /// The gateway's pid file is a JSON line (`{"pid":…, "hermes_home":"…"}` — /// verified against the real file). Only `pid` is read here; a gateway for /// another home leaves this profile's pid file absent or stale. private static func parsePID(fromFile path: String) -> pid_t? { guard let text = try? String(contentsOfFile: path, encoding: .utf8), let data = text.data(using: .utf8), let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let pid = (object["pid"] as? NSNumber)?.int32Value else { return nil } return pid > 0 ? pid : nil } /// `ps ax -o command=` scan — the gateway's argv carries no profile path; /// its pid file's hermes_home field is the only deterministic signal, and /// CLI/ACP children carry the flag (#15 charting). private static func psContainsMuseion() -> Bool { let run = EngineProbe.execute( ["/bin/sh", "-c", "ps ax -o command= | grep -F -e 'profiles/museion' -e '-p museion' | grep -v grep"], timeout: 5, ) return !run.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } /// Recursive curated copy: skip excluded entries in place, copy the rest. /// Plain `contentsOfDirectory` recursion — no enumerator, no path math /// (enumerator paths are fstab-resolved; substring rel-paths break across /// symlink boundaries like /var → /private/var), no skipDescendants traps. private static func copyTree(from source: String, to destination: String) throws { let fileManager = FileManager.default guard let entries = try? fileManager.contentsOfDirectory(atPath: source) else { throw CocoaError(.fileNoSuchFile) } for name in entries { if isExcluded(name: name) { continue } let src = (source as NSString).appendingPathComponent(name) let dest = (destination as NSString).appendingPathComponent(name) var isDirectory: ObjCBool = false guard fileManager.fileExists(atPath: src, isDirectory: &isDirectory) else { continue } if isDirectory.boolValue { try fileManager.createDirectory(atPath: dest, withIntermediateDirectories: true) try copyTree(from: src, to: dest) } else { do { try fileManager.copyItem(atPath: src, toPath: dest) } catch let err as NSError { // A file vanishing mid-copy (engine writes while we walk) is // skipped, not fatal — the snapshot stays usable. if err.code == NSFileReadNoSuchFileError || err.code == NSFileNoSuchFileError { continue } throw err } } } } /// Exclusion match on the entry's own name only: excluded dir names match /// at any depth (a `cache/` under sessions is cache too); file rules are /// name/suffix based. private static func isExcluded(name: String) -> Bool { excludedDirectoryNames.contains(name) || excludedFileNames.contains(name) || excludedFileNameSuffixes.contains { name.hasSuffix($0) } } /// Keep the newest `retentionCount` snapshots; pruned after a successful /// rename (#15). Lexicographic sort = newest first. private static func prune(backupsRoot: String) { let fileManager = FileManager.default let excess = Array(sortedSnapshots(in: backupsRoot).dropFirst(retentionCount)) for snapshot in excess { try? fileManager.removeItem(atPath: (backupsRoot as NSString).appendingPathComponent(snapshot.name)) } } /// Existing snapshots, newest first (stamp is lexicographically sortable). private static func sortedSnapshots(in backupsRoot: String) -> [(name: String, timestamp: Date)] { let fileManager = FileManager.default guard let entries = try? fileManager.contentsOfDirectory(atPath: backupsRoot) else { return [] } return entries .filter { !$0.hasPrefix(".") } // temp dirs during install .compactMap { name -> (String, Date)? in guard let date = date(fromStamp: name) else { return nil } return (name, date) } .sorted { $0.1 > $1.1 } } /// Parse YYYYMMDD-HHMMSS back to a Date for the age check. private static func date(fromStamp stamp: String) -> Date? { // ponytail: length+digit check instead of DateFormatter strict parsing — // same rejection set, no formatter to configure. guard stamp.count == 15, stamp.dropFirst(8).first == "-", stamp.replacingOccurrences(of: "-", with: "").allSatisfy(\.isNumber) else { return nil } let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd-HHmmss" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone.current return formatter.date(from: stamp) } private static let subsystem = "com.babylondreams.Museion" private static func logInfo(_ message: String) { Logger(subsystem: subsystem, category: "backup").info("\(message, privacy: .public)") } private static func logFailure(_ message: String) { Logger(subsystem: subsystem, category: "backup").error("\(message, privacy: .public)") } } /// App-scoped backup state; the pass runs after provisioning finishes, off-main. @MainActor @Observable final class BackupModel { private var running = false private(set) var lastOutcome: ProfileBackup.Outcome? /// One idempotent pass, off-main. Sequencing after provisioning is the /// caller's `await` chain (#15: backup runs when the provision pass has /// finished — success or failure; a failed provision doesn't skip it). func runPass(profileRoot: String? = nil, backupsRoot: String? = nil) async { guard !running else { return } running = true defer { running = false } let profileRoot = profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath let backupsRoot = backupsRoot ?? ProfileBackup.defaultBackupsRoot() lastOutcome = await Task.detached(priority: .utility) { ProfileBackup.perform(profileRoot: profileRoot, backupsRoot: backupsRoot) }.value } }