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

+2 -1
View File
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (963 symbols, 1674 relationships, 31 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (965 symbols, 1676 relationships, 31 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).
@@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-09-25 | [20260925-issue50-profile-backup-s2-6_log.md](docs/devlog/20260925-issue50-profile-backup-s2-6_log.md) |
| 2026-09-16 | [20260916-issue14-acp-bridge-s2-2_log.md](docs/devlog/20260916-issue14-acp-bridge-s2-2_log.md) |
| 2026-09-05 | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](docs/devlog/20260905-issue48-provisioning-failure-alert-retry-ux_log.md) |
| 2026-09-03 | [20260903-issue42-engine-gate-s2-1_log.md](docs/devlog/20260903-issue42-engine-gate-s2-1_log.md) |
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format
### Added
- **backup:** S2.6 daily profile backup — on launch, once per 24 h and only while the engine is idle (gateway.pid liveness + `ps` scan), Museion snapshots `~/.hermes/profiles/museion/` into a timestamped folder under `~/Library/Application Support/Museion/Backups/` (credentials included, logs/caches/locks excluded, last 7 kept); restore is manual Finder copy-back — Help → Open Backup Folder, `RESTORE.md` beside the snapshots (issue #50)
- **acp:** M0 ACP bridge (PRD S2.2) — the app spawns the Hermes engine (`hermes acp -p museion`) as a child process via a hand-rolled NDJSON JSON-RPC stdio client, opens a Session, streams mentor replies live in a debug pane, renders fix-card tool calls as structured cards, cancels turns via Stop, tears the child down on quit, and surfaces an in-pane restart prompt on engine crash — never data loss (issue #14)
- **provisioning:** S2.1 profile provisioning — idempotent per-gate pass creates the `museion` Hermes profile (`hermes profile create --no-alias --no-skills`) and additively seeds the bundled writing skills via `seed-manifest.txt`; existing skills are never overwritten (issue #47)
- **provisioning:** Failure alert & retry UX — provisioning failures show a separate phase-named alert (never re-raising the gate) with the error excerpt behind Technical details; Retry re-runs the whole pass, Not Now defers to the next launch's silent retry (issue #48)
+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
}
}
+1 -1
View File
@@ -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`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash).
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), 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`.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), 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.
## Verification
+201
View File
@@ -0,0 +1,201 @@
//
// 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>/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).
@discardableResult
func makeProfileFixture(at root: String) -> String {
let fileManager = FileManager.default
let profile = (root as NSString).appendingPathComponent("museion")
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)
}
@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)
}
}
+2 -2
View File
@@ -16,7 +16,7 @@
- **Engine (G1, resolved):** Museion is the shell; Hermes (Python, NousResearch, MIT) is the engine, driven over **ACP** — spawned as a child process `hermes acp -p museion` (stdio JSON-RPC). **User-installed Hermes** — no app-managed install, no bundled Python. First run gates on `hermes acp --check`.
- **Profile isolation (G3, this session):** Museion always runs Hermes under the dedicated `museion` profile (`~/.hermes/profiles/museion/` — isolated config, memory, skills, credentials, chat history). Coding learnings and writing learnings never mix. Not configurable in v1.
- **Provisioning (G3a):** first run creates the `museion` profile if missing, then seeds the writing skills bundled in the app (Serif stack, merged deslop, container personas, demonstrator doctrine, distilled craft canon, drill packs — spec: *The bundled skill set*) into `~/.hermes/profiles/museion/skills/`. Seeding is **additive only** — a bundled skill absent from the profile is copied; an existing one is never overwritten, because the mentor's self-improving skills live there.
- **Profile backup (G4):** Museion snapshots `~/.hermes/profiles/museion/` to `~/Library/Application Support/Museion/Backups/` — timestamped, at most once per day on launch, keeping the last 7. Snapshot is a complete copy (credentials included) so restore is one Finder copy-back; backups stay user-local, never in the project or git.
- **Profile backup (G4, amended #15):** Museion snapshots `~/.hermes/profiles/museion/` to `~/Library/Application Support/Museion/Backups/` — timestamped, at most once per day on launch, keeping the last 7, and only when the engine isn't running (liveness gate). The snapshot is a complete copy of what matters (credentials and SQLite sidecars included) with curated exclusions — `logs/`, `cache/`, `audio_cache/`, `image_cache/`, `*.pid`/`*.sock`/`*.lock`, `.DS_Store`, model-cache files — so restore is one Finder copy-back; backups stay user-local, never in the project or git.
- **Content layout (G5, merged):** one Museion Home; a post is a folder `posts/<post id>/` holding `post.md`, `research/`, `assets/` — created lazily on first write. Further writing types (`essays/`, `stories/`) get the same shape when they arrive; v1 ships `posts/` only. Post id = slug of the draft's first line, computed at first save; explicit Rename moves the folder (the file is always `post.md`); external markdown edits as-is, Import (copy, never move) makes it a Post. ADR-0004.
- **Writing tools (G6, merged; ADR-0008 + ADR-0006):** the Museion binary doubles as the stdio MCP server `museion-tools`, registered into the profile via `hermes mcp add` once the mode exists (#23) — provisioning never writes `mcp_servers` (#44) — any MCP-capable engine registers it as a client (engine-swap seam — Hermes today, Pi the identified fallback, ADR-0007). Tool surface: `query_learnings`, `submit_fix_cards` — the fix-card tool's argument schema is the fix-card schema; anchors are quote-based (exact substring + occurrence + context), so edits between issue and accept degrade to a loud no-match, never a wrong-span patch. Research stays engine-native; draft stats are computed natively in Swift at capture time — not an agent tool. Pass prompts are Museion-sent minimal stubs (pass name, piece path, tool reminders) — all methodology lives in the profile's skills. The Serif methodology (SKILL.md files, agentskills.io-standard) stays the mentor's operating system. Fallbacks if ACP ever falls short: Hermes gateway JSON-RPC (every feature), HTTP+SSE API server.
- **Critique memory home (ADR-0005):** writer learnings live in the Home's `learnings/` (no dot — hand-editable, git-diffable), scoped per content type (`learnings/posts/`, …), one markdown file per learning with decay state in frontmatter. The mentor's own automated memory stays in the profile; Museion never reads or writes it. Fresh start in v1 — verified: the hand-maintained MEMORY.md carries agent-tooling notes, no writing learnings to import.
@@ -91,7 +91,7 @@ From the 2026-08-28 sessions (Sudowrite/Muse learnings; issues #9, #10). None of
- **S2.3 — Session lifecycle.** As the writer, each session is a conversation with the standard affordances. *AC:* new/cancel/fork/resume/compact; every pass auto-creates its session; freeform sessions always allowed, free-floating or Piece-associated; sessions are engine-owned — Museion only UIs them (swap the engine, transcripts stay behind); cancel mid-pass stops the agent; streamed output renders live.
- **S2.4 — Writing tools, Museion-hosted.** As the mentor, I have purpose-built tools. *AC:* the Museion binary serves them over stdio MCP (`museion-tools`), registered into the `museion` profile via `hermes mcp add` once the mode exists (#23); provisioning never writes `mcp_servers` (#44); surface = `query_learnings` + `submit_fix_cards`, typed and quote-anchored (ADR-0006); callable mid-pass; outputs land in Museion's UI; passes are Museion-driven over ACP; research stays engine-native; draft stats are computed natively in Swift at capture time — not an agent tool; `query_learnings` returns only the visible set — Decay filtering happens inside `museion-tools`, the mentor never sees the mechanics.
- **S2.5 — Trust model.** As the writer, the mentor acts only within trust levels: auto-act / inform-after / ask-before / never-do. *AC:* trust level maps to UI (dimmed inline edits vs blocking asks); never-do actions never auto-apply. Defaults, not configurable in v1: research fetch = auto-act; candidate source-note = inform-after; apply any fix, promote, keep note, publish = ask-before; delete files, touch anything outside Home and profile, shell, git = never-do.
- **S2.6 — The engine is backed up.** As the writer, the mentor's accumulated state (memory, skills, history) survives profile corruption or a bad update. *AC:* on launch, if the last snapshot is older than a day, Museion copies `~/.hermes/profiles/museion/` to a timestamped snapshot under `~/Library/Application Support/Museion/Backups/`, keeping the last 7 (G4); complete copy, credentials included; restore is manual copy-back in v1; snapshots never land in the project or git.
- **S2.6 — The engine is backed up.** As the writer, the mentor's accumulated state (memory, skills, history) survives profile corruption or a bad update. *AC:* on launch, if the last snapshot is older than a day and the engine isn't running (liveness gate: gateway.pid pid-liveness + `ps` scan), Museion copies `~/.hermes/profiles/museion/` to a timestamped snapshot under `~/Library/Application Support/Museion/Backups/`, keeping the last 7 (G4); complete copy of what matters — credentials included, logs/caches/locks excluded; a failed backup is one log line, never an alert; restore is manual copy-back in v1 (Help → Open Backup Folder; `RESTORE.md` beside the snapshots); snapshots never land in the project or git.
- **S2.7 — Draft from session.** As the writer, a freeform session can birth a Post. *AC:* "New Post from Session" creates the piece folder, writes the draft, stamps `origin: ai` (immutable — never stats-eligible); brainstorming is a session started with a brainstorm prompt — no separate machinery; session↔Post association stays by name/convention.
- **S2.8 — Drill offers at the motivation moment.** As the writer, when a pass exposes a weakness, the mentor may offer a micro-drill targeting exactly that weakness. *AC:* drills are session flavor (bundled prompt-pack skill — see *The bundled skill set*), no machinery beyond S2.3; ≤2 minutes, offered right after the pass finding that motivates it; single-dimension rule — a drill targets exactly one weakness shelf, the pattern the pass just exposed, nothing else; never homework, queues, or streaks; a declined drill vanishes; drills never edit the draft.
@@ -0,0 +1,61 @@
# M0: Profile backup — daily snapshot pass (S2.6)
> **Date:** 2026-09-25
> **Type:** issue
> **Reference:** [#50 Build: implement daily profile backup pass](https://git.babylondreams.de/AlexKucera/museion/issues/50) (map [#15](https://git.babylondreams.de/AlexKucera/museion/issues/15))
## Goal
Land the #15 map's build ticket: the mentor's accumulated state survives profile corruption or a bad update. On qualifying launches Museion copies the whole museion profile to a timestamped snapshot under `~/Library/Application Support/Museion/Backups/`, keeping the last 7 — liveness-gated, credentials included, restore = manual Finder copy-back in v1.
## What Was Done
- `Museion/ProfileBackup.swift` (new) — `ProfileBackup` (nonisolated enum, EngineProbe/Provisioner pattern): one pass = liveness gate → age check → curated recursive copy → temp+rename atomic install → prune past 7. `BackupModel` (@MainActor @Observable) app-scoped via `AppGateState.backup`, runs off-main, guards stacking.
- `Museion/ContentView.swift` — `onEnginePass` chains `provisioning.runPass` then `backup.runPass` (a failed provision doesn't skip the backup; sequencing avoids racing the per-skill seed renames).
- `Museion/MuseionApp.swift` — `AppGateState.backup`; Help menu → Open Backup Folder (`NSWorkspace.open` on the Backups root).
- `RESTORE.md` written once into the Backups root at first snapshot — manual copy-back instructions travel with the snapshots.
- `MuseionTests/ProfileBackupTests.swift` (new) — 8 tests, injected roots/clock/psScan.
- `PRD.md` G4 + S2.6 amended (curated-exclusions wording per the map's charting decision); `Museion/AGENTS.md` backup section; `MuseionTests/AGENTS.md` test-pattern note.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Plain `contentsOfDirectory` recursion for the copy, not `FileManager.enumerator` | Enumerator yields fstab-resolved paths (/var → /private/var), so substring rel-path arithmetic silently produced garbage; `skipDescendants()` on a file entry also eats following siblings. The plain walk has no path math and no traps — smaller and correct. |
| `psScan` injectable, default real `ps ax` pipeline via `EngineProbe.execute` | Tests must not depend on whether a dev machine happens to run the real engine (`hermes acp -p museion` would make every CI/dev run skip). Map decision preserved in production default. |
| Snapshot layout `<stamp>/museion/<contents>` | The folder name travels with the snapshot so restore is literally one Finder copy-back — `RESTORE.md` documents exactly that shape. |
| `RESTORE.md` as static text written into the Backups root, not a bundled help-book resource | It must sit beside the snapshots it describes even when the app that wrote them is gone (corruption scenario = the app may be reinstalling). |
| Sequencing as caller's await chain, not a polling wait inside BackupModel | `await provisioning.runPass(); await backup.runPass()` — one line, no timer hack, failure-independent (#15 decision). |
| gateway.pid parsed as JSON (`pid` key), not bare integer | Probed the real file: it's a JSON line `{"pid":…, "hermes_home":"…"}`. The map's "parse pid" assumed integer; JSON parse is the verified reality. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Snapshot's `museion/` dir empty — all credential assertions failed | `skipDescendants()` called on excluded *file* entries skipped subsequent siblings; separately, enumerator's resolved paths broke `dropFirst(source.count)` rel-path math across the /var symlink | Replaced the whole enumerator approach with plain recursive `contentsOfDirectory` + name-based exclusion |
| Tests failed on missing `state.db` at snapshot root | Copy landed profile contents directly at `<stamp>/`, not `<stamp>/museion/` | Create `museion/` payload dir inside the temp snapshot before copying |
| Test-target build error "Argument 'timeZone' must precede 'year'" | `DateComponents` memberwise init has a fixed argument order | Built components via property assignment |
| SwiftFormat reformatted `prototypes/GateUIPrototype.swift` (untouched file) | Blanket `swiftformat .` | Reverted via git checkout — drive-by formatting isn't part of this ticket |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ProfileBackup.swift` | New — backup pass, liveness gate, curated copy, retention, RESTORE.md |
| `Museion/ContentView.swift` | onEnginePass chains backup after provisioning |
| `Museion/MuseionApp.swift` | AppGateState.backup; Help → Open Backup Folder |
| `MuseionTests/ProfileBackupTests.swift` | New — 8 tests: liveness branches, exclusions, credentials, age, retention, failure |
| `PRD.md` | G4 + S2.6 amended to curated-exclusions wording |
| `Museion/AGENTS.md` | New "Profile backup" section (DOX) |
| `MuseionTests/AGENTS.md` | ProfileBackupTests pattern note |
| `AGENTS.md` | GitNexus counter refresh (965 symbols) + this log's window row |
## Open Items & Next Steps
- [x] All four #15 acceptance criteria test-pinned (daily cadence, complete-of-what-matters copy, last-7 retention, manual-restore docs; snapshots user-local by construction — Backups root is in Application Support, never the project).
- [ ] First real snapshot happens at next qualifying launch (engine idle, newest >24 h) — verify `~/Library/Application Support/Museion/Backups/` then.
- [ ] Map #15 closeout: resolution comment + Decisions-so-far pointer (blocked on forge-write authorization).
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-09-25 | issue | [20260925-issue50-profile-backup-s2-6_log.md](20260925-issue50-profile-backup-s2-6_log.md) | #50 S2.6 daily profile backup: liveness gate, curated copy, retention 7, RESTORE.md — 8 tests green |
| 2026-09-16 | issue | [20260916-issue14-acp-bridge-s2-2_log.md](20260916-issue14-acp-bridge-s2-2_log.md) | #14 M0 ACP bridge: NDJSON JSON-RPC client, mentor pane, fix-card round-trip, crash restart — 37 tests green |
| 2026-09-05 | issue | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](20260905-issue48-provisioning-failure-alert-retry-ux_log.md) | #48 shipped: failure card with retry/Not-Now, traversal guard, temp sweep — 30 tests green |
| 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green |