feat(backup): add S2.6 daily profile backup (fixes #50)

One liveness-gated snapshot pass per launch, chained after provisioning:
gateway.pid pid-liveness + ps scan (skip while the engine runs), 24 h
age check, curated recursive copy (credentials and SQLite sidecars in;
logs/caches/locks out), atomic temp+rename install, keep last 7.
Restore stays manual copy-back in v1 — Help > Open Backup Folder and
a RESTORE.md written beside the snapshots.

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-09-30 11:24:58 +02:00
1 parent f21d3a6844
commit e5b7203906
11 files changed
+593 -5

No files matched your search

+7
View File
@@ -32,6 +32,13 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- 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 `<binaryDir>/profiles/<name>`), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload.
## 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 `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, 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`).
- `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).
## ACP bridge (S2.2, #14 map)
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.20.6 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
+6 -1
View File
@@ -60,7 +60,12 @@ struct ContentView: View {
onEnginePass: {
// #47: provisioning runs in parallel on pass; idempotent, so re-fires
// are no-ops. Alert UX on failure is #48.
Task { await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath) }
// #50: backup runs after the provision pass finishes — success or
// failure; a failed provision doesn't skip the backup.
Task {
await gate.provisioning.runPass(hermesBinary: gate.gateModel.currentBinaryPath)
await gate.backup.runPass()
}
},
onDismiss: {
gate.gateRaised = false
+17
View File
@@ -18,6 +18,8 @@ final class AppGateState {
var gateDismissed = false
let gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
/// #50: daily backup pass, sequenced after provisioning finishes.
let backup = BackupModel()
/// #14: the app-scoped mentor bridge — the pane renders it; quit tears it down.
let mentor = MentorSessionModel()
}
@@ -47,6 +49,11 @@ struct MuseionApp: App {
CommandGroup(replacing: .appInfo) {
OpenAboutButton()
}
// #50: reveal the snapshots folder in Finder (restore = manual
// copy-back, documented in the bundled help doc).
CommandMenu("Help") {
OpenBackupFolderButton()
}
}
}
}
@@ -59,6 +66,16 @@ private struct OpenAboutButton: View {
}
}
/// #50: reveals `~/Library/Application Support/Museion/Backups` in Finder —
/// restore is manual Finder copy-back in v1 (help doc describes it).
private struct OpenBackupFolderButton: View {
var body: some View {
Button("Open Backup Folder") {
NSWorkspace.shared.open(URL(fileURLWithPath: ProfileBackup.defaultBackupsRoot()))
}
}
}
/// Read-only mirror of the last completed check's state.json record (ticket #39).
/// Reads the file when opened; never triggers a check; no re-check button.
struct AboutEngineView: View {
+294
View File
@@ -0,0 +1,294 @@
//
// 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
}
}