Files
museion/Museion/ProfileBackup.swift
T
AlexKucera d722820fc8 chore: swiftformat drift + xcode 27 settings leftovers
Format-only pass over spikes, the gate prototype, and three app
files (brace style, wrapping — no semantic change), plus the 4-line
pbxproj alignment finishing the Xcode 27 settings pass (test-target
deployment target parity with 8e70f69).

[Generated by AI]
2026-10-16 14:49:26 +02:00

296 lines
12 KiB
Swift

//
// 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.
//
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<String> = [
"logs", "cache", "audio_cache", "image_cache",
]
private static let excludedFileNames: Set<String> = [
".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. Runs on gate pass, sequenced after the provisioning
/// pass finishes (success or failure — a failed provision doesn't skip it).
/// - 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 source = (profileRoot as NSString).appendingPathComponent("museion")
guard fileManager.fileExists(atPath: source) else {
logInfo("skipped — museion profile missing")
return .skippedProfileMissing
}
guard engineIdle(profileDir: source, psScan: psScan) 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: <stamp>/museion/<profile contents> — 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)
// Atomic install (seed-phase pattern): rename into place, then prune.
try fileManager.moveItem(atPath: tempDir, toPath: finalDir)
prune(backupsRoot: backupsRoot)
logInfo("snapshot complete: \(stamp)")
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 profile
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.
## 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).
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 {
let pidPath = (profileDir as NSString).appendingPathComponent("gateway.pid")
if let pid = parsePID(fromFile: pidPath), kill(pid, 0) == 0 {
return false
}
return !psScan()
}
/// 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
}
}