Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(store): stop settings wipes from silently-swallowed store.bin load failures

Louis Beaumont6ee57b2512dd
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index 795b36968..3ff0af8f7 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -49,22 +49,56 @@ const APP_ENTITLEMENT_CLOCK_SKEW_MINUTES: i64 = 5;
// Settings-loss recovery
//
// Goal: a user can never be silently reset to default settings on update.
-// 4 layers, defense in depth:
+//
+// THE TRAP everything below defends against: tauri-plugin-store SWALLOWS
+// deserialize errors on load (`let _ = store_inner.load()`), so any store.bin
+// it can't parse — still-encrypted ciphertext after a keychain failure, a
+// torn write — comes back as a *successfully built EMPTY store*. init_store
+// then sees no `settings` key, treats it as a fresh install, and saves
+// defaults over the user's file at boot. The frontend seeds default aiPresets
+// on top, which makes the wiped state pass the "has presets" health check and
+// freeze itself into `.last-good`. (Verified root cause for the 2026-06-11
+// Windows "update deleted all my AI models" report.)
+//
+// Layers, defense in depth:
// L1: snapshot `store.bin.last-good` after every successful save (only if
-// the snapshot has aiPresets — never freeze a degraded state).
+// the snapshot has aiPresets — never freeze a degraded state). The
+// previous, differing snapshot is rotated to `.last-good.prev` so one
+// bad freeze can't destroy the only recovery source.
// L2: at boot, before the Tauri store plugin opens the file, auto-restore
-// from `.last-good` IFF the current file is degraded (parses but no
-// aiPresets) AND last-good is healthy. The bad file is moved to
-// `store.bin.pre-restore-<ts>` for forensics.
+// from `.last-good` (or `.prev`) IFF the current file is degraded
+// (parses but no aiPresets) AND the snapshot is healthy. The bad file
+// is kept as `store.bin.pre-restore-<ts>` for forensics.
+// L2b: same restore when store.bin is encrypted but UNREADABLE (keychain
+// key denied/missing after retries, or decrypt failed). Without this,
+// the plugin silently builds an empty store from the ciphertext and
+// init_store commits the wipe. The ciphertext is preserved as
+// `store.bin.encrypted.bak` first.
// L3: refuse `create_new()` over a healthy on-disk file (would otherwise
// create a fresh in-memory store that overwrites disk on next save).
-// L4: stop writing `b"{}"` on encryption-key failures — keep the encrypted
-// file in place and let the load fail loudly instead.
+// An encrypted-at-rest file counts as healthy — ciphertext is user
+// data, not an empty store.
+// L4: never write over the encrypted file on key failures — back it up and
+// leave it in place.
+// L5: after the plugin builds, if the disk file has a `settings` key but
+// the loaded store doesn't, the load silently failed — refuse to hand
+// out the wipe-primed handle.
// ---------------------------------------------------------------------------
/// Suffix for the most-recent known-healthy snapshot.
const LAST_GOOD_SUFFIX: &str = "bin.last-good";
+/// Suffix for the rotated previous snapshot (one generation back). Protects
+/// against the freeze-over case: a wipe that re-seeded default presets looks
+/// "healthy" and replaces `.last-good` on its first save — the user's real
+/// state survives here.
+const LAST_GOOD_PREV_SUFFIX: &str = "bin.last-good.prev";
+
+/// Is this byte buffer an encrypted store.bin (SPSTORE1 magic)?
+fn is_encrypted_bytes(data: &[u8]) -> bool {
+ data.len() >= 8 && &data[..8] == STORE_MAGIC
+}
+
/// Did this store JSON parse and contain a non-empty `settings.aiPresets`?
/// Used as the "is this a real user state" signal — empty presets means the
/// migration in use-settings.tsx will seed defaults, which is the wipe trigger.
@@ -82,6 +116,10 @@ fn store_json_has_presets(data: &[u8]) -> bool {
/// L1 — copy `store.bin` → `store.bin.last-good` if the current file parses
/// and has aiPresets. Skipped silently otherwise so we never freeze a wiped
/// state as the recovery source. Called after every successful save.
+///
+/// The outgoing snapshot is rotated to `.last-good.prev` when it differs, so
+/// a post-wipe state that re-seeded default presets (and therefore looks
+/// healthy) can't destroy the only copy of the user's real settings.
pub fn snapshot_last_good(store_path: &Path) {
let data = match std::fs::read(store_path) {
Ok(d) => d,
@@ -91,6 +129,23 @@ pub fn snapshot_last_good(store_path: &Path) {
return;
}
let last_good = store_path.with_extension(LAST_GOOD_SUFFIX);
+ if let Ok(existing) = std::fs::read(&last_good) {
+ if existing != data && store_json_has_presets(&existing) {
+ let prev = store_path.with_extension(LAST_GOOD_PREV_SUFFIX);
+ if let Err(e) = std::fs::write(&prev, &existing) {
+ tracing::warn!(
+ "snapshot_last_good: failed to rotate {}: {}",
+ prev.display(),
+ e
+ );
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&prev, std::fs::Permissions::from_mode(0o600));
+ }
+ }
+ }
if let Err(e) = std::fs::write(&last_good, &data) {
tracing::warn!(
"snapshot_last_good: failed to write {}: {}",
@@ -105,52 +160,55 @@ pub fn snapshot_last_good(store_path: &Path) {
}
}
-/// L2 — if `store.bin` is degraded (parses but missing aiPresets) and
-/// `.last-good` is healthy, restore it before anything else touches the file.
-/// The bad current file is preserved as `.pre-restore-<UTC ts>` so we have
-/// forensics if a user reports the restore was wrong.
-///
-/// Returns `true` when a restore happened (telemetry hook). Logged loudly so
-/// it shows up in screenpipe-app.YYYY-MM-DD.log.
-pub fn auto_restore_if_wiped(store_path: &Path) -> bool {
- // Only act on plain-JSON files. Encrypted files are handled by the
- // decrypt path; we don't want to restore over a still-encrypted blob.
- let cur = match std::fs::read(store_path) {
- Ok(d) => d,
- Err(_) => return false,
- };
- if cur.len() >= 8 && &cur[..8] == STORE_MAGIC {
- return false;
- }
- if store_json_has_presets(&cur) {
- return false; // current state is healthy, nothing to do
+/// Pick the newest healthy snapshot: `.last-good`, falling back to
+/// `.last-good.prev`. Returns the source path (for logging) and its bytes.
+fn read_healthy_snapshot(store_path: &Path) -> Option<(std::path::PathBuf, Vec<u8>)> {
+ for suffix in [LAST_GOOD_SUFFIX, LAST_GOOD_PREV_SUFFIX] {
+ let p = store_path.with_extension(suffix);
+ if let Ok(data) = std::fs::read(&p) {
+ if store_json_has_presets(&data) {
+ return Some((p, data));
+ }
+ }
}
- let last_good = store_path.with_extension(LAST_GOOD_SUFFIX);
- let Ok(lg) = std::fs::read(&last_good) else {
+ None
+}
+
+/// Restore the newest healthy snapshot over `store_path`. The current file is
+/// kept as `store.bin.pre-restore-<UTC ts>` for forensics; the restore aborts
+/// if that backup can't be written. Returns `true` when a restore happened
+/// (telemetry hook). Logged loudly so it shows up in
+/// screenpipe-app.YYYY-MM-DD.log.
+fn restore_snapshot_over(store_path: &Path, why: &str) -> bool {
+ let Some((src, data)) = read_healthy_snapshot(store_path) else {
+ tracing::error!(
+ "settings recovery: {} but no healthy snapshot exists next to {} — nothing restored",
+ why,
+ store_path.display()
+ );
return false;
};
- if !store_json_has_presets(&lg) {
- return false; // last-good is also wiped (shouldn't happen — L1 guards this)
- }
- // Move the bad file aside before overwriting it
+ // Keep the bad file for forensics before overwriting it
let ts = chrono::Utc::now().format("%Y%m%d-%H%M%S");
let pre_restore = store_path.with_extension(format!("bin.pre-restore-{}", ts));
- if let Err(e) = std::fs::copy(store_path, &pre_restore) {
- tracing::warn!(
- "auto_restore_if_wiped: failed to back up {} to {}: {} — aborting restore",
- store_path.display(),
- pre_restore.display(),
- e
- );
- return false;
+ if store_path.exists() {
+ if let Err(e) = std::fs::copy(store_path, &pre_restore) {
+ tracing::warn!(
+ "settings recovery: failed to back up {} to {}: {} — aborting restore",
+ store_path.display(),
+ pre_restore.display(),
+ e
+ );
+ return false;
+ }
}
- if let Err(e) = std::fs::write(store_path, &lg) {
+ if let Err(e) = std::fs::write(store_path, &data) {
tracing::error!(
- "auto_restore_if_wiped: failed to restore {} from {}: {}",
+ "settings recovery: failed to restore {} from {}: {}",
store_path.display(),
- last_good.display(),
+ src.display(),
e
);
return false;
@@ -161,77 +219,138 @@ pub fn auto_restore_if_wiped(store_path: &Path) -> bool {
let _ = std::fs::set_permissions(store_path, std::fs::Permissions::from_mode(0o600));
}
tracing::warn!(
- "auto_restore_if_wiped: restored {} from {} (was missing aiPresets); \
- pre-restore copy at {}",
+ "settings recovery: {} — restored {} from {}; pre-restore copy at {}",
+ why,
store_path.display(),
- last_good.display(),
+ src.display(),
pre_restore.display()
);
true
}
+/// L2 — if `store.bin` is degraded (parses but missing aiPresets) and a
+/// snapshot is healthy, restore it before anything else touches the file.
+/// The bad current file is preserved as `.pre-restore-<UTC ts>` so we have
+/// forensics if a user reports the restore was wrong.
+///
+/// Returns `true` when a restore happened (telemetry hook).
+pub fn auto_restore_if_wiped(store_path: &Path) -> bool {
+ // Only act on plain-JSON files. Encrypted files are handled by the
+ // decrypt path (L2b); we don't want to restore over a blob that the
+ // keychain key could still open.
+ let cur = match std::fs::read(store_path) {
+ Ok(d) => d,
+ Err(_) => return false,
+ };
+ if is_encrypted_bytes(&cur) {
+ return false;
+ }
+ if store_json_has_presets(&cur) {
+ return false; // current state is healthy, nothing to do
+ }
+ restore_snapshot_over(
+ store_path,
+ "store.bin is degraded (parses but has no aiPresets)",
+ )
+}
+
+/// Result of the pre-load decrypt pass over store.bin.
+#[derive(PartialEq)]
+enum DecryptOutcome {
+ /// File is plain JSON, empty, or missing — nothing to decrypt.
+ PlainOrMissing,
+ /// File was encrypted and is now plain JSON on disk.
+ Decrypted,
+ /// File is encrypted and CANNOT be read (key denied/missing after
+ /// retries, or decryption failed). A copy was saved as
+ /// `store.bin.encrypted.bak`. Left as-is the store plugin would silently
+ /// build an EMPTY store from it and init_store would save defaults over
+ /// the user's data — the caller must run snapshot recovery (L2b).
+ Locked,
+}
+
/// Decrypt store.bin in place if it's encrypted and keychain key is available.
/// No-op if the file is already plain JSON or keychain is unavailable.
-fn decrypt_store_file(path: &Path) {
+fn decrypt_store_file(path: &Path) -> DecryptOutcome {
let data = match std::fs::read(path) {
Ok(d) => d,
- Err(_) => return,
+ Err(_) => return DecryptOutcome::PlainOrMissing,
};
- if data.len() < 8 || &data[..8] != STORE_MAGIC {
- return; // already plain JSON (or empty)
+ if !is_encrypted_bytes(&data) {
+ return DecryptOutcome::PlainOrMissing; // already plain JSON (or empty)
}
// File is encrypted, so user must have encryption enabled
// Use get_key_if_encryption_enabled to prevent prompts if encryption is somehow disabled
- let key = match secrets::get_key_if_encryption_enabled() {
+ let mut key_result = secrets::get_key_if_encryption_enabled();
+ // Transient credential-store hiccups right after boot/update are a known
+ // wipe trigger (Windows Credential Manager especially). Retry briefly
+ // before declaring the file locked. AccessDenied is a deliberate user
+ // answer to a prompt — don't re-prompt.
+ for attempt in 1..3u32 {
+ match key_result {
+ secrets::KeyResult::NotFound | secrets::KeyResult::Unavailable => {
+ std::thread::sleep(std::time::Duration::from_millis(250 * attempt as u64));
+ key_result = secrets::get_key_if_encryption_enabled();
+ }
+ _ => break,
+ }
+ }
+ let key = match key_result {
secrets::KeyResult::Found(k) => k,
secrets::KeyResult::AccessDenied => {
- tracing::warn!(
+ // L4 — DO NOT wipe. Keep a ciphertext backup; the caller restores
+ // the plain .last-good snapshot so the app still boots with the
+ // user's settings instead of silently resetting them.
+ let backup = path.with_extension("bin.encrypted.bak");
+ let _ = std::fs::copy(path, &backup);
+ tracing::error!(
"store.bin is encrypted but keychain access was denied — \
- please grant keychain access and restart. \
- Your settings are preserved in the encrypted file."
+ ciphertext preserved at {}. Grant keychain access and \
+ restart to use it.",
+ backup.display()
);
- // Don't overwrite — the file is still valid, user just needs to grant access
- return;
+ return DecryptOutcome::Locked;
}
secrets::KeyResult::NotFound | secrets::KeyResult::Unavailable => {
// L4 — DO NOT wipe. Previously this branch wrote `b"{}"` over
// store.bin and lost the user's settings on every signed update
// (macOS code-signing identity changes can evict keychain keys).
- // The encrypted file still has the user's data; leave it in
- // place and let the load fall through to L2 auto_restore from
- // store.bin.last-good. Manual recovery: re-grant keychain
- // access in System Settings → Privacy & Security → Keychain.
+ // The encrypted file still has the user's data; back it up and
+ // report Locked so the caller restores from store.bin.last-good.
let backup = path.with_extension("bin.encrypted.bak");
let _ = std::fs::copy(path, &backup);
tracing::error!(
"store.bin is encrypted but keychain key not found — \
- leaving the encrypted file in place ({}). Restore from \
- store.bin.last-good or grant keychain access and restart.",
+ ciphertext preserved at {}. Restore from store.bin.last-good \
+ or grant keychain access and restart.",
backup.display()
);
- return;
+ return DecryptOutcome::Locked;
}
};
match screenpipe_vault::crypto::decrypt_small(&data[8..], &key) {
Ok(plaintext) => {
let tmp = path.with_extension("bin.dec.tmp");
- if std::fs::write(&tmp, &plaintext).is_ok() {
- let _ = std::fs::rename(&tmp, path);
+ if std::fs::write(&tmp, &plaintext).is_ok() && std::fs::rename(&tmp, path).is_ok() {
+ DecryptOutcome::Decrypted
+ } else {
+ tracing::error!("failed to write decrypted store.bin to disk");
+ DecryptOutcome::Locked
}
}
Err(e) => {
// L4 — DO NOT wipe. Same rationale as the missing-key branch
- // above: keep the encrypted file (now backed up under .encrypted.bak)
- // so the user has a recovery path, and let the load fall
- // through to L2 auto_restore.
+ // above: keep the encrypted file (backed up under .encrypted.bak)
+ // and report Locked so the caller restores from a snapshot.
let backup = path.with_extension("bin.encrypted.bak");
let _ = std::fs::copy(path, &backup);
tracing::error!(
- "failed to decrypt store.bin: {} — backed up as {}, leaving \
- in place. Restore from store.bin.last-good if available.",
+ "failed to decrypt store.bin: {} — backed up as {}. \
+ Restoring from store.bin.last-good if available.",
e,
backup.display()
);
+ DecryptOutcome::Locked
}
}
}
@@ -360,8 +479,35 @@ fn build_store(app: &AppHandle) -> anyhow::Result<Arc<tauri_plugin_store::Store<
let store_path = base_dir.join("store.bin");
// Decrypt store.bin before the plugin reads it (no-op if plain JSON or keychain unavailable)
- if store_path.exists() {
- decrypt_store_file(&store_path);
+ if store_path.exists() && decrypt_store_file(&store_path) == DecryptOutcome::Locked {
+ // L2b — the encrypted blob is unreadable (key denied/missing or
+ // decrypt failed). The plugin would silently build an EMPTY store
+ // from it (it ignores deserialize errors) and init_store would then
+ // save defaults over the user's data. Restore the newest healthy
+ // plain snapshot instead; the ciphertext was already preserved.
+ let restored = restore_snapshot_over(
+ &store_path,
+ "store.bin is encrypted and the keychain key is unavailable",
+ );
+ if !restored {
+ // No snapshot to restore. init_store will treat the empty store
+ // as a fresh install and save defaults at boot — move the blob
+ // aside (in addition to .encrypted.bak) so that save lands on a
+ // genuinely fresh file instead of overwriting ciphertext.
+ let ts = chrono::Utc::now().format("%Y%m%d-%H%M%S");
+ let aside = store_path.with_extension(format!("bin.locked-{}", ts));
+ match std::fs::rename(&store_path, &aside) {
+ Ok(()) => tracing::error!(
+ "settings recovery: no healthy snapshot — moved unreadable \
+ encrypted store.bin to {}; starting fresh",
+ aside.display()
+ ),
+ Err(e) => tracing::error!(
+ "settings recovery: failed to move locked store.bin aside: {}",
+ e
+ ),
+ }
+ }
}
// L2 — if the file is degraded (parses but has no aiPresets), restore
@@ -372,6 +518,15 @@ fn build_store(app: &AppHandle) -> anyhow::Result<Arc<tauri_plugin_store::Store<
let _ = auto_restore_if_wiped(&store_path);
}
+ // L5 precondition — note whether the disk file holds a parseable
+ // `settings` key right before the plugin reads it. Compared against the
+ // loaded store after build to detect silently-swallowed load failures.
+ let disk_has_settings = std::fs::read(&store_path)
+ .ok()
+ .and_then(|d| serde_json::from_slice::<Value>(&d).ok())
+ .map(|v| v.get("settings").is_some())
+ .unwrap_or(false);
+
let mut last_err = None;
// Ensure store.bin has restrictive permissions (contains API keys)
#[cfg(unix)]
@@ -383,6 +538,25 @@ fn build_store(app: &AppHandle) -> anyhow::Result<Arc<tauri_plugin_store::Store<
for attempt in 0..3u32 {
match StoreBuilder::new(app, store_path.clone()).build() {
Ok(s) => {
+ // L5 — tauri-plugin-store swallows deserialize errors on load
+ // (`let _ = store_inner.load()`), handing back a successfully
+ // built EMPTY store while the disk still holds the user's
+ // data. init_store treats a missing `settings` key as a fresh
+ // install and saves defaults, committing the wipe. Refuse the
+ // handle instead: no handle means no save can clobber disk.
+ if disk_has_settings && s.get("settings").is_none() {
+ tracing::error!(
+ "store loaded empty but {} has a settings key \
+ (attempt {}) — refusing the wipe-primed store",
+ store_path.display(),
+ attempt + 1
+ );
+ last_err = None;
+ std::thread::sleep(std::time::Duration::from_millis(
+ 100 * (attempt as u64 + 1),
+ ));
+ continue;
+ }
// Re-encrypt immediately after the plugin loaded the file
encrypt_store_file(&store_path);
return Ok(s);
@@ -409,16 +583,18 @@ fn build_store(app: &AppHandle) -> anyhow::Result<Arc<tauri_plugin_store::Store<
// file. The fresh in-memory store would later flush
// empty defaults to disk and silently overwrite the
// user's settings (verified root cause for Louis's
- // 2026-05-09 wipe). If the file has aiPresets, surface
- // the error so the retry loop runs again instead.
+ // 2026-05-09 wipe). If the file has aiPresets — or is
+ // encrypted at rest, which is user data we just can't
+ // parse here — surface the error so the retry loop runs
+ // again instead.
let disk_healthy = std::fs::read(&store_path)
- .map(|d| store_json_has_presets(&d))
+ .map(|d| store_json_has_presets(&d) || is_encrypted_bytes(&d))
.unwrap_or(false);
if disk_healthy {
tracing::error!(
"store resource stale (attempt {}): {}, but disk \
- has aiPresets — refusing create_new() to avoid \
- overwriting user data; will retry .build()",
+ has user data — refusing create_new() to avoid \
+ overwriting it; will retry .build()",
attempt + 1,
msg
);
@@ -453,7 +629,14 @@ fn build_store(app: &AppHandle) -> anyhow::Result<Arc<tauri_plugin_store::Store<
}
}
}
- Err(anyhow::anyhow!(last_err.unwrap()))
+ Err(match last_err {
+ Some(e) => anyhow::anyhow!(e),
+ // Only reachable via the L5 branch exhausting its retries.
+ None => anyhow::anyhow!(
+ "store loaded empty while {} has a settings key — refused the wipe-primed store",
+ store_path.display()
+ ),
+ })
}
pub fn get_store(
@@ -670,7 +853,6 @@ pub struct SettingsStore {
// (`RecordingSettings::disable_timeline`) so the engine can read it too. The
// frontend JSON key stays `disableTimeline` at the top level via serde
// flatten — do not add a second field here or serde will conflict.
-
/// When true, the chat window stays above all other windows (default: true).
#[serde(rename = "chatAlwaysOnTop", default = "default_true")]
pub chat_always_on_top: bool,
@@ -1876,7 +2058,7 @@ mod tests {
#[test]
fn auto_restore_skips_encrypted_files() {
// L2 must not try to "restore" over a still-encrypted blob — the
- // decrypt path owns that case.
+ // decrypt path owns that case (and runs L2b itself when locked).
let tmp = tempfile::tempdir().unwrap();
let store_path = tmp.path().join("store.bin");
let mut blob = STORE_MAGIC.to_vec();
@@ -1896,6 +2078,144 @@ mod tests {
assert_eq!(std::fs::read(&store_path).unwrap(), blob);
}
+ fn write_prev(dir: &Path, contents: &Value) -> std::path::PathBuf {
+ let p = dir.join("store.bin.last-good.prev");
+ std::fs::write(&p, serde_json::to_vec_pretty(contents).unwrap()).unwrap();
+ p
+ }
+
+ #[test]
+ fn snapshot_last_good_rotates_previous_to_prev() {
+ // L1 rotation: a healthy .last-good about to be replaced by different
+ // content must survive one generation as .last-good.prev — this is
+ // what saves the user when a wiped state re-seeds default presets and
+ // "healthily" freezes itself into .last-good.
+ let tmp = tempfile::tempdir().unwrap();
+ let v1 = json!({"settings": {"aiPresets": presets_n(5)}});
+ let v2 = json!({"settings": {"aiPresets": presets_n(1)}});
+
+ let store_path = write_store(tmp.path(), &v1);
+ snapshot_last_good(&store_path);
+ write_store(tmp.path(), &v2);
+ snapshot_last_good(&store_path);
+
+ let lg: Value = serde_json::from_slice(
+ &std::fs::read(store_path.with_extension(LAST_GOOD_SUFFIX)).unwrap(),
+ )
+ .unwrap();
+ let prev: Value = serde_json::from_slice(
+ &std::fs::read(store_path.with_extension(LAST_GOOD_PREV_SUFFIX)).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(
+ lg.pointer("/settings/aiPresets")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ prev.pointer("/settings/aiPresets")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .len(),
+ 5
+ );
+ }
+
+ #[test]
+ fn snapshot_last_good_no_rotation_when_unchanged() {
+ let tmp = tempfile::tempdir().unwrap();
+ let v1 = json!({"settings": {"aiPresets": presets_n(2)}});
+ let store_path = write_store(tmp.path(), &v1);
+ snapshot_last_good(&store_path);
+ snapshot_last_good(&store_path);
+ assert!(
+ !store_path.with_extension(LAST_GOOD_PREV_SUFFIX).exists(),
+ "identical snapshot must not churn .prev"
+ );
+ }
+
+ #[test]
+ fn auto_restore_falls_back_to_prev_snapshot() {
+ // .last-good is degraded (e.g. frozen by a wipe before the rotation
+ // fix) but .prev still holds the user's real state.
+ let tmp = tempfile::tempdir().unwrap();
+ let store_path = write_store(tmp.path(), &json!({"settings": {"aiPresets": []}}));
+ write_last_good(tmp.path(), &json!({"settings": {"aiPresets": []}}));
+ write_prev(
+ tmp.path(),
+ &json!({"settings": {"aiPresets": presets_n(4)}}),
+ );
+
+ let restored = auto_restore_if_wiped(&store_path);
+ assert!(restored, "should fall back to .last-good.prev");
+
+ let now: Value = serde_json::from_slice(&std::fs::read(&store_path).unwrap()).unwrap();
+ assert_eq!(
+ now.pointer("/settings/aiPresets")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .len(),
+ 4
+ );
+ }
+
+ #[test]
+ fn restore_snapshot_over_replaces_locked_blob() {
+ // L2b: an encrypted store.bin whose key is gone gets replaced by the
+ // plain .last-good snapshot; the ciphertext is kept for forensics.
+ let tmp = tempfile::tempdir().unwrap();
+ let store_path = tmp.path().join("store.bin");
+ let mut blob = STORE_MAGIC.to_vec();
+ blob.extend_from_slice(b"<<encrypted ciphertext>>");
+ std::fs::write(&store_path, &blob).unwrap();
+ assert!(is_encrypted_bytes(&blob));
+ write_last_good(
+ tmp.path(),
+ &json!({"settings": {"aiPresets": presets_n(3)}}),
+ );
+
+ let restored = restore_snapshot_over(&store_path, "test: locked blob");
+ assert!(restored);
+
+ let now = std::fs::read(&store_path).unwrap();
+ assert!(
+ store_json_has_presets(&now),
+ "store must be plain + healthy"
+ );
+
+ let pre_restore: Vec<_> = std::fs::read_dir(tmp.path())
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.file_name().into_string().unwrap_or_default())
+ .filter(|n| n.contains("pre-restore-"))
+ .collect();
+ assert_eq!(pre_restore.len(), 1, "ciphertext forensic copy expected");
+ let kept = std::fs::read(tmp.path().join(&pre_restore[0])).unwrap();
+ assert_eq!(kept, blob, "forensic copy must be the original ciphertext");
+ }
+
+ #[test]
+ fn restore_snapshot_over_noop_without_snapshots() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store_path = tmp.path().join("store.bin");
+ let mut blob = STORE_MAGIC.to_vec();
+ blob.extend_from_slice(b"<<encrypted ciphertext>>");
+ std::fs::write(&store_path, &blob).unwrap();
+
+ let restored = restore_snapshot_over(&store_path, "test: no snapshots");
+ assert!(!restored);
+ assert_eq!(
+ std::fs::read(&store_path).unwrap(),
+ blob,
+ "file must be untouched when there is nothing to restore from"
+ );
+ }
+
// ---- Existing tests ----
#[test]