Modern Apps git

← Modern-Apps.git

everysync+passwords: zero-data-loss sync hardening

Commit
94e0783d41c7f48fcc8ed523a088563dac033ff7
Author
vayun-mathur <[email protected]>
When
2026-10-14 23:21 UTC (1 month ago)
Parents
5daedbc

Diff

everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt b/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.ktindex c690b0c135..5b1f469d0e 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt@@ -1,10 +1,15 @@ package com.vayunmathur.everysync  import android.app.Application+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.sync.SnapshotWorker import com.vayunmathur.everysync.sync.SyncScheduler import com.vayunmathur.library.log.Log import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.GlobalScope+import kotlinx.coroutines.launch  /**  * Ensures the periodic background sync is scheduled whenever the process starts —@@ -18,5 +23,11 @@ class EverySyncApplication : Application() {         // FIRST_PARTY covers the relay host (same bundle the office twin uses).         NetworkClient.init(this, TrustBundle.FIRST_PARTY)         SyncScheduler.schedulePeriodic(this)+        SnapshotWorker.scheduleDaily(this)+        // One-time: seal any plaintext vault keys stored before the Keystore+        // migration. Idempotent; runs on every process start, cheap when done.+        GlobalScope.launch(Dispatchers.IO) {+            runCatching { VaultStore.migrateKeysToKeystore(this@EverySyncApplication) }+        }     } }
everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.ktindex 5da86f6447..9b0dc9c9e3 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt@@ -11,8 +11,10 @@ import kotlinx.serialization.json.Json  * sync its record log and to invite others, without ever holding another  * device's secrets.  *- * Key material ([keyB64]) is the AES vault key; for joined vaults it arrives- * sealed in a [RelaySync.Invite](com.vayunmathur.everysync.network.remote.RelaySync.Invite).+ * Key material ([keyB64]) is the AES vault key, Keystore-encrypted at rest+ * (see `readKey`/`writeKey` below — never the raw base64 in DataStore);+ * for joined vaults it arrives sealed in a+ * [RelaySync.Invite](com.vayunmathur.everysync.network.remote.RelaySync.Invite).  * [ownerKeyB64] is the owner's PQC public bundle, used to verify roster, key  * epoch, ownership and title signatures client-side — the relay is a pure log.  */@@ -45,8 +47,15 @@ object VaultStore {         getAll(context).firstOrNull { it.vaultId == vaultId }      suspend fun upsert(context: Context, meta: VaultMeta) {-        val current = getAll(context).filterNot { it.vaultId == meta.vaultId }-        DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(current + meta))+        // Never persist a raw vault key: re-wrap through the Keystore store so+        // even a programming slip that passes plaintext cannot land it in JSON.+        val safe = if (meta.keyB64.isNotBlank() && !VaultKeyStore.looksSealed(meta.keyB64)) {+            meta.copy(keyB64 = VaultKeyStore.seal(context, meta.keyB64) ?: return)+        } else {+            meta+        }+        val current = getAll(context).filterNot { it.vaultId == safe.vaultId }+        DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(current + safe))     }      suspend fun remove(context: Context, vaultId: String) {@@ -57,4 +66,129 @@ object VaultStore {     suspend fun saveAll(context: Context, vaults: List<VaultMeta>) {         DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(vaults))     }++    /**+     * One-time migration: seals any plaintext `keyB64` values already stored+     * (written before the Keystore migration) in place. Idempotent — sealed+     * values are left alone. Called from `EverySyncApplication.onCreate`.+     */+    suspend fun migrateKeysToKeystore(context: Context) {+        val all = getAll(context)+        if (all.isEmpty()) return+        var migrated = 0+        val sealed = all.map { meta ->+            if (meta.keyB64.isNotBlank() && !VaultKeyStore.looksSealed(meta.keyB64)) {+                val wrapped = VaultKeyStore.seal(context, meta.keyB64) ?: return@map meta+                migrated+++                meta.copy(keyB64 = wrapped)+            } else {+                meta+            }+        }+        if (migrated > 0) {+            DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(sealed))+        }+    }+}++/**+ * Reads the plaintext AES vault key for [meta], unsealing the Keystore-wrapped+ * value stored in [VaultMeta.keyB64]. Returns null when the key is missing or+ * cannot be unsealed (fail closed — the vault is skipped, never merged).+ */+fun VaultMeta.readKey(context: Context): ByteArray? =+    VaultKeyStore.unseal(context, keyB64)?.let { b64 ->+        runCatching { kotlin.io.encoding.Base64.decode(b64) }.getOrNull()+            ?.takeIf { it.isNotEmpty() }+    }++/**+ * Keystore-encrypted storage for AES vault keys (same AES-GCM pattern as+ * `TokenStore`: a non-exportable Keystore key wraps a per-value random+ * content key; the sealed blob is base64 for the `keyB64` field).+ *+ * Sealed values carry the `v1:` prefix so `looksSealed` can tell them apart+ * from legacy plaintext base64 for the one-time migration.+ */+object VaultKeyStore {+    private const val PREFIX = "v1:"+    private const val ANDROID_KEYSTORE = "AndroidKeyStore"+    private const val KEY_ALIAS = "everysync_vault_keystore"+    private const val TRANSFORMATION = "AES/GCM/NoPadding"+    private const val GCM_TAG_BITS = 128++    fun looksSealed(keyB64: String): Boolean = keyB64.startsWith(PREFIX)++    fun seal(context: Context, plainB64: String): String? = runCatching {+        val contentKey = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }+        val cipher = javax.crypto.Cipher.getInstance(TRANSFORMATION)+        cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, javax.crypto.spec.SecretKeySpec(contentKey, "AES"))+        val iv = cipher.iv+        val ct = cipher.doFinal(plainB64.encodeToByteArray())+        val wrapCipher = javax.crypto.Cipher.getInstance(TRANSFORMATION)+        wrapCipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKey())+        val wrapIv = wrapCipher.iv+        val wrappedKey = wrapCipher.doFinal(contentKey)+        PREFIX + kotlin.io.encoding.Base64.encode(+            wrapIv.size.toBytes() + wrapIv + wrappedKey.size.toBytes() + wrappedKey ++                iv.size.toBytes() + iv + ct,+        )+    }.getOrNull()++    fun unseal(context: Context, sealedB64: String): String? = runCatching {+        if (!looksSealed(sealedB64)) return@runCatching null+        val sealed = kotlin.io.encoding.Base64.decode(sealedB64.removePrefix(PREFIX))+        var off = 0+        fun readChunk(): ByteArray {+            val len = sealed.copyOfRange(off, off + 4).toInt()+            off += 4+            val chunk = sealed.copyOfRange(off, off + len)+            off += len+            return chunk+        }+        val wrapIv = readChunk()+        val wrappedKey = readChunk()+        val iv = readChunk()+        val ct = sealed.copyOfRange(off, sealed.size)+        val unwrapCipher = javax.crypto.Cipher.getInstance(TRANSFORMATION)+        unwrapCipher.init(+            javax.crypto.Cipher.DECRYPT_MODE, secretKey(),+            javax.crypto.spec.GCMParameterSpec(GCM_TAG_BITS, wrapIv),+        )+        val contentKey = unwrapCipher.doFinal(wrappedKey)+        val cipher = javax.crypto.Cipher.getInstance(TRANSFORMATION)+        cipher.init(+            javax.crypto.Cipher.DECRYPT_MODE,+            javax.crypto.spec.SecretKeySpec(contentKey, "AES"),+            javax.crypto.spec.GCMParameterSpec(GCM_TAG_BITS, iv),+        )+        cipher.doFinal(ct).decodeToString()+    }.getOrNull()++    private fun secretKey(): javax.crypto.SecretKey {+        val ks = java.security.KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (ks.getEntry(KEY_ALIAS, null) as? java.security.KeyStore.SecretKeyEntry)?.let { return it.secretKey }+        val generator = javax.crypto.KeyGenerator.getInstance(+            android.security.keystore.KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE,+        )+        generator.init(+            android.security.keystore.KeyGenParameterSpec.Builder(+                KEY_ALIAS,+                android.security.keystore.KeyProperties.PURPOSE_ENCRYPT or+                    android.security.keystore.KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(android.security.keystore.KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(android.security.keystore.KeyProperties.ENCRYPTION_PADDING_NONE)+                .build(),+        )+        return generator.generateKey()+    }++    private fun Int.toBytes(): ByteArray = byteArrayOf(+        (this shr 24).toByte(), (this shr 16).toByte(), (this shr 8).toByte(), this.toByte(),+    )++    private fun ByteArray.toInt(): Int =+        ((this[0].toInt() and 0xFF) shl 24) or ((this[1].toInt() and 0xFF) shl 16) or+            ((this[2].toInt() and 0xFF) shl 8) or (this[3].toInt() and 0xFF) }
everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.ktindex bf29f4657b..9b389e91b1 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt@@ -26,6 +26,13 @@ data class LocalEventChange(  */ object CalendarSink {     private const val TAG = "CalendarSink"++    /**+     * Health of the last [listLocal] read: false when the query failed or+     * returned a null cursor. Consulted by `CalendarRelayStore.listLocalOk`.+     */+    @Volatile var lastListLocalOk: Boolean = true+        private set     private val ACCOUNT_TYPE = AccountStore.ACCOUNT_TYPE     private const val DEFAULT_CALENDAR_COLOR = 0xFF3F51B5.toInt()     private const val MILLIS_PER_SECOND = 1000L@@ -157,8 +164,9 @@ object CalendarSink {         val colAllDay = 7         val colTz = 8         val colRrule = 9+        var failed = false         try {-            context.contentResolver.query(+            val cursor = context.contentResolver.query(                 CalendarContract.Events.CONTENT_URI,                 arrayOf(                     CalendarContract.Events._SYNC_ID,@@ -175,28 +183,36 @@ object CalendarSink {                 "${CalendarContract.Events.CALENDAR_ID} = ? AND ${CalendarContract.Events.DELETED} = 0",                 arrayOf(localCalendarId.toString()),                 null,-            )?.use { c ->-                while (c.moveToNext()) {-                    val uid = c.getStringOrNull(colUid).orEmpty()-                    out += RemoteEvent(-                        uid = uid,-                        etag = c.getStringOrNull(colStamp),-                        calendarId = localCalendarId.toString(),-                        summary = c.getStringOrNull(colTitle) ?: "",-                        description = c.getStringOrNull(colDesc) ?: "",-                        location = c.getStringOrNull(colLoc) ?: "",-                        startMillis = c.getLong(colStart),-                        endMillis = c.getLong(colEnd),-                        allDay = c.getInt(colAllDay) == 1,-                        timezone = c.getStringOrNull(colTz) ?: "UTC",-                        rrule = c.getStringOrNull(colRrule),-                        updatedAt = c.getStringOrNull(colStamp)?.toLongOrNull() ?: 0L,-                    )+            )+            if (cursor == null) {+                // Null cursor = provider cannot serve: failure, not empty.+                failed = true+            } else {+                cursor.use { c ->+                    while (c.moveToNext()) {+                        val uid = c.getStringOrNull(colUid).orEmpty()+                        out += RemoteEvent(+                            uid = uid,+                            etag = c.getStringOrNull(colStamp),+                            calendarId = localCalendarId.toString(),+                            summary = c.getStringOrNull(colTitle) ?: "",+                            description = c.getStringOrNull(colDesc) ?: "",+                            location = c.getStringOrNull(colLoc) ?: "",+                            startMillis = c.getLong(colStart),+                            endMillis = c.getLong(colEnd),+                            allDay = c.getInt(colAllDay) == 1,+                            timezone = c.getStringOrNull(colTz) ?: "UTC",+                            rrule = c.getStringOrNull(colRrule),+                            updatedAt = c.getStringOrNull(colStamp)?.toLongOrNull() ?: 0L,+                        )+                    }                 }             }         } catch (expected: Exception) {             Log.error(TAG, "listLocal failed", expected)+            failed = true         }+        lastListLocalOk = !failed         return out     } 
everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.ktindex e6febcfccf..1afefb13cb 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt@@ -35,6 +35,13 @@ data class LocalContactChange(  */ object ContactsSink {     private const val TAG = "ContactsSink"++    /**+     * Health of the last [listLocal] read: false when the query failed or+     * returned a null cursor. Consulted by `ContactRelayStore.listLocalOk`.+     */+    @Volatile var lastListLocalOk: Boolean = true+        private set     private val ACCOUNT_TYPE = AccountStore.ACCOUNT_TYPE     private const val CURSOR_UID = 0     private const val CURSOR_ETAG = 1@@ -87,8 +94,9 @@ object ContactsSink {      */     fun listLocal(context: Context, accountName: String): List<RemoteContact> {         val out = mutableListOf<RemoteContact>()+        var failed = false         try {-            context.contentResolver.query(+            val cursor = context.contentResolver.query(                 ContactsContract.RawContacts.CONTENT_URI,                 arrayOf(                     ContactsContract.RawContacts._ID,@@ -100,18 +108,26 @@ object ContactsSink {                     "${ContactsContract.RawContacts.DELETED} = 0",                 arrayOf(accountName, ACCOUNT_TYPE),                 null,-            )?.use { c ->-                while (c.moveToNext()) {-                    val rawId = c.getLong(CURSOR_RAW_ID)-                    val uid = c.getStringOrNull(CURSOR_SOURCE_ID).orEmpty()-                    val stamp = c.getStringOrNull(CURSOR_SYNC1)?.toLongOrNull() ?: 0L-                    val contact = readContact(context, rawId, uid.ifBlank { null })-                    out += contact.copy(uid = uid, updatedAt = stamp)+            )+            if (cursor == null) {+                // Null cursor = provider cannot serve: failure, not empty.+                failed = true+            } else {+                cursor.use { c ->+                    while (c.moveToNext()) {+                        val rawId = c.getLong(CURSOR_RAW_ID)+                        val uid = c.getStringOrNull(CURSOR_SOURCE_ID).orEmpty()+                        val stamp = c.getStringOrNull(CURSOR_SYNC1)?.toLongOrNull() ?: 0L+                        val contact = readContact(context, rawId, uid.ifBlank { null })+                        out += contact.copy(uid = uid, updatedAt = stamp)+                    }                 }             }         } catch (expected: Exception) {             Log.error(TAG, "listLocal failed", expected)+            failed = true         }+        lastListLocalOk = !failed         return out     } 
everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.ktindex ffe816320b..98535736a1 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt@@ -52,6 +52,13 @@ data class LocalNoteChange( object NoteSink {     private const val TAG = "NoteSink" +    /**+     * Health of the last [listLocal] read: false when the query failed or+     * returned a null cursor. Consulted by `NoteRelayStore.listLocalOk`.+     */+    @Volatile var lastListLocalOk: Boolean = true+        private set+     const val AUTHORITY = "com.vayunmathur.notes.relay"     const val PATH_NOTES = "notes"     const val PATH_SNAPSHOTS = "snapshots"@@ -157,25 +164,34 @@ object NoteSink {     /** All local rows in relay form, tombstones included (notes soft-delete). */     fun listLocal(context: Context, vaultId: String): List<RemoteNote> {         val out = mutableListOf<RemoteNote>()+        var failed = false         try {-            context.contentResolver.query(+            val cursor = context.contentResolver.query(                 notesUri(vaultId),                 arrayOf(COL_PAYLOAD_JSON),                 null,                 null,                 null,-            )?.use { c ->-                val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)-                while (c.moveToNext()) {-                    val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null-                    if (!payload.isNullOrBlank()) {-                        fromPayload(payload)?.let { out += it }+            )+            if (cursor == null) {+                // Null cursor = provider cannot serve: failure, not empty.+                failed = true+            } else {+                cursor.use { c ->+                    val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                    while (c.moveToNext()) {+                        val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                        if (!payload.isNullOrBlank()) {+                            fromPayload(payload)?.let { out += it }+                        }                     }                 }             }         } catch (expected: Exception) {             Log.error(TAG, "listLocal failed", expected)+            failed = true         }+        lastListLocalOk = !failed         return out     } 
everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.ktindex 9c70d25f6f..91dfeded43 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt@@ -6,6 +6,7 @@ import android.net.Uri import androidx.core.database.getLongOrNull import androidx.core.database.getStringOrNull import com.vayunmathur.everysync.data.RemotePassword+import com.vayunmathur.everysync.sync.LocalReadException import com.vayunmathur.everysync.sync.adapters.PasswordKind import com.vayunmathur.library.log.Log import kotlinx.serialization.Serializable@@ -70,7 +71,10 @@ internal data class PasskeyPayload(  *   (snapshot retained app-side so the merge reads it as a deletion).  * - delete: a `syncId = ?` selection hard-deletes one row (snapshot kept);  *   `deleteByVault` (or selection-less base delete) purges the whole table- *   *and* its snapshots.+ *   *and* its snapshots. NOTE: this path is merge-EXTERNAL (user toggling sync+ *   off, explicit purge). Merge-driven deletes ALWAYS arrive as `deleted`+ *   tombstone envelopes via upsert, never as raw deletes — raw deletes carry+ *   no proof of intent and the merge must never infer deletion from absence.  * - columns: `syncId`, `updatedAt`, `deleted`, `payloadJson`, `contentHash`  *   (payload SHA-256 hex; the merge driver recomputes canonical hashes  *   itself via [PasswordKind] and ignores this column on read).@@ -84,6 +88,14 @@ internal data class PasskeyPayload( object PasswordSink {     private const val TAG = "PasswordSink" +    /**+     * Health of the last [listLocalOrThrow]/[listLocal] read: false when any+     * table query failed or returned a null cursor. Consulted by+     * `PasswordRelayStore.listLocalOk` so the driver can abort before merging.+     */+    @Volatile var lastListLocalOk: Boolean = true+        private set+     const val AUTHORITY = "com.vayunmathur.passwords.relay"     const val PATH_PASSWORDS = "passwords"     const val PATH_PASSKEYS = "passkeys"@@ -242,17 +254,33 @@ object PasswordSink {     }      /** All local rows in relay form (tombstones never occur locally — hard deletes). */-    fun listLocal(context: Context, vaultId: String): List<RemotePassword> {+    fun listLocal(context: Context, vaultId: String): List<RemotePassword> =+        runCatching { listLocalOrThrow(context, vaultId) }.getOrDefault(emptyList())++    /**+     * All local rows in relay form, throwing [LocalReadException] when the+     * provider cannot be read. The merge driver MUST use this variant: a+     * failed read merged as empty would delete every baseline-present relay+     * record.+     */+    fun listLocalOrThrow(context: Context, vaultId: String): List<RemotePassword> {         val out = mutableListOf<RemotePassword>()+        var failed = false         for ((uri, isPasskey) in listOf(passwordsUri(vaultId) to false, passkeysUri(vaultId) to true)) {             try {-                context.contentResolver.query(+                val cursor = context.contentResolver.query(                     uri,                     arrayOf(COL_PAYLOAD_JSON),                     null,                     null,                     null,-                )?.use { c ->+                ) ?: run {+                    // Null cursor = provider cannot serve (locked DB, crash):+                    // failure, not an empty table.+                    failed = true+                    continue+                }+                cursor.use { c ->                     val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)                     while (c.moveToNext()) {                         val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null@@ -263,8 +291,14 @@ object PasswordSink {                 }             } catch (expected: Exception) {                 Log.error(TAG, "listLocal failed for $uri", expected)+                failed = true             }         }+        if (failed) {+            lastListLocalOk = false+            throw LocalReadException("password provider read failed for vault $vaultId")+        }+        lastListLocalOk = true         return out     } 
everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoIpcSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoIpcSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoIpcSink.ktindex 1aa2b9fd33..a5f5c13817 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoIpcSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoIpcSink.kt@@ -49,6 +49,13 @@ data class LocalTodoChange( object TodoIpcSink {     private const val TAG = "TodoIpcSink" +    /**+     * Health of the last [listLocal] read: false when the query failed or+     * returned a null cursor. Consulted by `TodoRelayStore.listLocalOk`.+     */+    @Volatile var lastListLocalOk: Boolean = true+        private set+     const val AUTHORITY = "com.vayunmathur.todo.relay"     const val PATH_TODOS = "todos"     const val PATH_SNAPSHOTS = "snapshots"@@ -114,25 +121,34 @@ object TodoIpcSink {     /** All local rows in relay form, tombstones included (todos soft-delete). */     fun listLocal(context: Context, vaultId: String): List<RemoteTodo> {         val out = mutableListOf<RemoteTodo>()+        var failed = false         try {-            context.contentResolver.query(+            val cursor = context.contentResolver.query(                 todosUri(vaultId),                 arrayOf(COL_PAYLOAD_JSON),                 null,                 null,                 null,-            )?.use { c ->-                val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)-                while (c.moveToNext()) {-                    val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null-                    if (!payload.isNullOrBlank()) {-                        fromRelayJson(payload)?.let { out += it }+            )+            if (cursor == null) {+                // Null cursor = provider cannot serve: failure, not empty.+                failed = true+            } else {+                cursor.use { c ->+                    val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                    while (c.moveToNext()) {+                        val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                        if (!payload.isNullOrBlank()) {+                            fromRelayJson(payload)?.let { out += it }+                        }                     }                 }             }         } catch (expected: Exception) {             Log.error(TAG, "listLocal failed", expected)+            failed = true         }+        lastListLocalOk = !failed         return out     } 
everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt b/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.ktindex 28ccc17d9a..dabb0d4352 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt@@ -47,6 +47,19 @@ import kotlin.io.encoding.Base64  *  * Presence is not used here (unlike office/voxels): vault sync is WorkManager-driven  * with push-on-edit, so there is no ephemeral live channel to keep open.+ *+ * Key hygiene invariant: vault keys are never user-visible. Share links carry+ * only vault/owner ids; keys move exclusively via PQC-sealed inbox invites, and+ * rest encrypted at rest (see `TokenStore` / `VaultStore`). Roster, key epochs,+ * ownership and titles are owner-signed; record envelopes are encryption-only.+ * TRIGGER: if any future feature surfaces a vault key to the user (export, QR,+ * manual entry), record envelopes must gain a findfamily `PairAuth`-style+ * per-sender secret id (pinned trust-on-first-use, directional, never logged)+ * before that feature ships.+ *+ * Loss-prevention invariant: a failed pull is NEVER an empty log. `pullRecords`+ * and `pullRaw` return null on transport failure so the merge driver can abort+ * the cycle instead of reading absence as deletion (see `RelayMerge`).  */ // Transport surface: one function per endpoint/operation by design. @Suppress("TooManyFunctions")@@ -112,13 +125,22 @@ object RelaySync {         return append(channel, blobs)     } -    /** Pulls + decrypts a vault's record log from [since]; undecryptable entries are skipped. */-    suspend fun pullRecords(channel: String, key: ByteArray, since: Int): RecordsResult {-        val p = pull(channel, since) ?: return RecordsResult(emptyList(), since)+    /** Pulls + decrypts a vault's record log from [since]; null on transport failure.+     *+     * A null return is NOT an empty log: the caller must abort the cycle. Folding+     * a failure as empty would read every baseline-present id as deleted (see+     * `RelayMerge`). [rawCount] is how many envelopes the relay holds;+     * [items.size] is how many decrypted under [key] — a large gap means a+     * key/epoch problem, not an empty vault.+     */+    suspend fun pullRecords(channel: String, key: ByteArray, since: Int): RecordsResult? {+        val p = pull(channel, since) ?: return null+        var undecryptable = 0         val items = p.actions.mapNotNull { b ->             runCatching { E2ee.aesDecrypt(key, Base64.decode(b)).decodeToString() }.getOrNull()+                ?: run { undecryptable++; null }         }-        return RecordsResult(items, p.seq)+        return RecordsResult(items, p.seq, rawCount = p.actions.size, undecryptable = undecryptable)     }      // --- Invites (PQC-sealed to the recipient's inbox) ---@@ -207,7 +229,8 @@ object RelaySync {     suspend fun seal(bundle: ByteArray, data: ByteArray): ByteArray = Pqc.encryptTo(bundle, data)     suspend fun unseal(data: ByteArray): ByteArray = identity.decrypt(data)     suspend fun appendRaw(channel: String, items: List<String>): Int? = append(channel, items)-    suspend fun pullRaw(channel: String, since: Int): List<String> = pull(channel, since)?.actions ?: emptyList()+    /** Raw pull; null on transport failure (NOT an empty channel — abort, don't merge). */+    suspend fun pullRaw(channel: String, since: Int): List<String>? = pull(channel, since)?.actions     fun decrypt(key: ByteArray, b64: String): String? =         runCatching { E2ee.aesDecrypt(key, Base64.decode(b64)).decodeToString() }.getOrNull() @@ -366,7 +389,22 @@ object RelaySync {      class InvitesResult(val invites: List<Invite>, val seq: Int)     class InboxResult(val invites: List<Invite>, val requests: List<JoinRequest>, val seq: Int)-    class RecordsResult(val items: List<String>, val seq: Int)++    /**+     * One decrypted record-log pull. [rawCount] is the envelope count on the+     * relay; [undecryptable] is how many failed to decrypt under the vault key.+     * When most records fail to decrypt the key/epoch is suspect — the caller+     * must treat that as a failure (abort), not as an empty vault.+     */+    class RecordsResult(+        val items: List<String>,+        val seq: Int,+        val rawCount: Int = items.size,+        val undecryptable: Int = 0,+    ) {+        /** True when decryption failed for every record that exists: key suspect, abort. */+        val fullyUndecryptable: Boolean get() = rawCount > 0 && items.isEmpty()+    }      @Serializable private data class SubMsg(val t: String, val channel: String)     @Serializable private data class AppendMsg(val t: String, val channel: String, val actions: List<String>)
everysync/src/main/java/com/vayunmathur/everysync/platform/BootReceiver.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/platform/BootReceiver.kt b/everysync/src/main/java/com/vayunmathur/everysync/platform/BootReceiver.ktindex ed2c150a47..5c516e88d8 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/platform/BootReceiver.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/platform/BootReceiver.kt@@ -3,6 +3,7 @@ package com.vayunmathur.everysync.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent+import com.vayunmathur.everysync.sync.SnapshotWorker import com.vayunmathur.everysync.sync.SyncScheduler  /**@@ -15,7 +16,10 @@ class BootReceiver : BroadcastReceiver() {         when (intent.action) {             Intent.ACTION_BOOT_COMPLETED,             Intent.ACTION_MY_PACKAGE_REPLACED,-            -> SyncScheduler.schedulePeriodic(context.applicationContext)+            -> {+                SyncScheduler.schedulePeriodic(context.applicationContext)+                SnapshotWorker.scheduleDaily(context.applicationContext)+            }         }     } }
everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncUiContract.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncUiContract.kt b/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncUiContract.ktindex fee1aa755f..6965332eaf 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncUiContract.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncUiContract.kt@@ -1,6 +1,7 @@ package com.vayunmathur.everysync.platform  import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.sync.SnapshotStore.SnapshotMeta  /**  * The UI contract between the screens and whatever drives them.@@ -45,6 +46,12 @@ data class AccountDetailUiState(     val deviceId: String = "",     val safetyCode: String? = null,     val computingCode: Boolean = false,+    /** Human-readable sync failure explanation, or null when healthy. */+    val syncErrorText: String? = null,+    /** Daily encrypted snapshots for this account's vaults, newest first. */+    val snapshots: List<SnapshotMeta> = emptyList(),+    /** True while a snapshot restore is running. */+    val restoring: Boolean = false, )  /** Everything the settings screen draws. */@@ -85,6 +92,10 @@ interface AccountDetailActions {     fun syncNow(accountName: String) {}     fun removeAccount(accountName: String) {}     fun back() {}+    /** Restores a daily snapshot (replays its records through the sinks). */+    fun restoreSnapshot(snapshot: SnapshotMeta) {}+    /** Takes today's snapshots now (idempotent — same-day vaults are skipped). */+    fun snapshotNow() {}      /** Creates a new owned personal vault for [dataType] (`contacts`/`calendar`) with [title]. */     fun createVault(dataType: String, title: String) {}
everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncVaults.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncVaults.kt b/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncVaults.ktindex 5d1a05bb18..385f938c3d 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncVaults.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncVaults.kt@@ -4,6 +4,7 @@ import android.app.Application import androidx.lifecycle.viewModelScope import com.vayunmathur.everysync.data.VaultMeta import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.readKey import com.vayunmathur.everysync.network.remote.RelayLinks import com.vayunmathur.everysync.network.remote.RelayRoles import com.vayunmathur.everysync.network.remote.RelaySync@@ -74,6 +75,7 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {     /** Creates a new owned vault for [dataType] with [title] and publishes its signed title. */     fun createVault(dataType: String, title: String, onResult: (Boolean) -> Unit = {}) {         viewModel.viewModelScope.launch(Dispatchers.IO) {+            // upsert seals keyB64 at rest.             val ok = runCatching {                 if (!RelaySync.init(app)) return@runCatching false                 val vaultId = RelaySync.newVaultId()@@ -104,11 +106,12 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {             val ok = runCatching {                 val meta = VaultStore.get(app, vaultId) ?: return@runCatching false                 if (!meta.isOwner) return@runCatching false+                val key = meta.readKey(app) ?: return@runCatching false                 RelaySync.sendInvite(                     recipientId = recipientId,                     vaultId = vaultId,                     dataType = meta.dataType,-                    key = Base64.decode(meta.keyB64),+                    key = key,                     title = meta.title,                     role = role,                     ownerKeyB64 = meta.ownerKeyB64,@@ -126,7 +129,7 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {             val ok = runCatching {                 val meta = VaultStore.get(app, vaultId) ?: return@runCatching false                 if (!meta.isOwner) return@runCatching false-                val key = Base64.decode(meta.keyB64)+                val key = meta.readKey(app) ?: return@runCatching false                 writeMembers(vaultId, listOf(RelaySync.Member(requesterId, name, role)))                 RelaySync.sendInvite(                     recipientId = requesterId,@@ -172,6 +175,7 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {                 ds.setLong(KEY_INBOX_CURSOR, inbox.seq.toLong())                 for (invite in inbox.invites) {                     if (VaultStore.get(app, invite.vaultId) == null) {+                        // upsert seals the plaintext invite key at rest.                         VaultStore.upsert(                             app,                             VaultMeta(@@ -218,7 +222,8 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {      private suspend fun refreshVault(vaultId: String) {         val meta = VaultStore.get(app, vaultId) ?: return-        if ((runCatching { Base64.decode(meta.keyB64) }.getOrNull()?.size ?: 0) == 0) return+        // Fail closed when the key cannot be unsealed: skip, never merge.+        if ((meta.readKey(app)?.size ?: 0) == 0) return         val members = readMembers(vaultId).map { VaultMemberUi(it.id, it.name, it.role) }         val requests = loadRequests(vaultId).map { VaultRequestUi(it.requesterId, it.name) }         // Joined vaults follow the owner-signed title; owned vaults keep the local one.@@ -246,8 +251,11 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {     private suspend fun readMembers(vaultId: String): List<RelaySync.Member> {         val ownerKey = runCatching { Base64.decode(VaultStore.get(app, vaultId)?.ownerKeyB64.orEmpty()) }             .getOrNull() ?: return emptyList()-        return RelaySync.pullRaw("members:$vaultId", 0).mapNotNull { raw ->-            val envelope = runCatching { inboxJson.decodeFromString<RelaySync.SignedEnvelope>(raw) }.getOrNull()+        // A failed pull keeps the last-known roster: no verified data means no+        // roster change, never an emptied roster.+        val raw = RelaySync.pullRaw("members:$vaultId", 0) ?: return emptyList()+        return raw.mapNotNull { r ->+            val envelope = runCatching { inboxJson.decodeFromString<RelaySync.SignedEnvelope>(r) }.getOrNull()                 ?: return@mapNotNull null             val valid = RelaySync.verify(ownerKey, envelope.payload.encodeToByteArray(), Base64.decode(envelope.sig))             if (!valid) return@mapNotNull null@@ -265,8 +273,11 @@ class EverySyncVaults(private val viewModel: EverySyncViewModel) {     private suspend fun readTitle(vaultId: String): String? {         val ownerKey = runCatching { Base64.decode(VaultStore.get(app, vaultId)?.ownerKeyB64.orEmpty()) }             .getOrNull() ?: return null-        return RelaySync.pullRaw("title:$vaultId", 0).mapNotNull { raw ->-            val envelope = runCatching { inboxJson.decodeFromString<RelaySync.SignedEnvelope>(raw) }.getOrNull()+        // A failed pull keeps the last-known title: no verified data means no+        // title change.+        val raw = RelaySync.pullRaw("title:$vaultId", 0) ?: return null+        return raw.mapNotNull { r ->+            val envelope = runCatching { inboxJson.decodeFromString<RelaySync.SignedEnvelope>(r) }.getOrNull()                 ?: return@mapNotNull null             val valid = RelaySync.verify(ownerKey, envelope.payload.encodeToByteArray(), Base64.decode(envelope.sig))             if (!valid) return@mapNotNull null
everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncViewModel.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncViewModel.kt b/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncViewModel.ktindex b2c362dbfd..2eb4dadf91 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncViewModel.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/platform/EverySyncViewModel.kt@@ -7,12 +7,19 @@ import com.vayunmathur.everysync.data.Settings import com.vayunmathur.everysync.R import com.vayunmathur.everysync.auth.AccountConfig import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.sink.CalendarSink+import com.vayunmathur.everysync.data.sink.ContactsSink import com.vayunmathur.everysync.network.remote.RelayRoles import com.vayunmathur.everysync.provider.DataType import com.vayunmathur.everysync.provider.ProviderRegistry-import com.vayunmathur.everysync.data.sink.CalendarSink-import com.vayunmathur.everysync.data.sink.ContactsSink+import com.vayunmathur.everysync.provider.impl.CH_LOCAL_READ_FAILED+import com.vayunmathur.everysync.provider.impl.CH_PULL_TRANSPORT+import com.vayunmathur.everysync.provider.impl.CH_RELAY_UNAVAILABLE+import com.vayunmathur.everysync.provider.impl.CH_UNDECRYPTABLE_LOG import com.vayunmathur.everysync.provider.impl.E2eeProvider+import com.vayunmathur.everysync.sync.SnapshotStore+import com.vayunmathur.everysync.sync.SnapshotStore.SnapshotMeta import com.vayunmathur.everysync.sync.SyncScheduler import com.vayunmathur.everysync.sync.SyncStatus import com.vayunmathur.library.util.AppMessages@@ -72,12 +79,40 @@ class EverySyncViewModel(app: Application) : AndroidViewModel(app) {         SyncScheduler.syncNow(getApplication(), accountName)     } +    /**+     * Snapshot-now entry point for the UI (e.g. a "back up now" affordance).+     * Same-day vaults are skipped by the store, so this is idempotent.+     */+    fun snapshotNow() {+        viewModelScope.launch(Dispatchers.IO) {+            SnapshotStore.snapshotAll(getApplication())+            loadSnapshots()+        }+    }+     fun toggleType(accountName: String, type: DataType, enabled: Boolean) {         viewModelScope.launch {             val config = store.get(accountName) ?: return@launch+            val app = getApplication<Application>()+            if (!enabled) {+                // Snapshot BEFORE removing the type: all purge paths below+                // are account- or vault-wide and the merge never infers+                // deletion from absence, so the snapshot is the way back.+                // Best-effort: purge is explicit user intent either way.+                // (IPC types snapshot again inside purgeType — same-day+                // snapshots are skipped, so the duplicate is a no-op.)+                withContext(Dispatchers.IO) {+                    runCatching {+                        for (meta in VaultStore.getAll(app).filter {+                            it.dataType == type.relayType()+                        }) {+                            SnapshotStore.snapshotVault(app, meta.vaultId, meta.dataType)+                        }+                    }+                }+            }             val types = if (enabled) config.enabledTypes + type else config.enabledTypes - type             store.upsert(config.copy(enabledTypes = types))-            val app = getApplication<Application>()             if (enabled) {                 // Re-sync so the just-enabled type is repopulated on-device.                 SyncScheduler.syncNow(app, accountName)@@ -119,6 +154,62 @@ class EverySyncViewModel(app: Application) : AndroidViewModel(app) {         viewModelScope.launch { store.remove(accountName) }     } +    // --- Sync health + snapshots (observability + last-resort recovery) ---++    /**+     * Human-readable explanation of an account's `lastSyncError`, mapping the+     * stable abort codes (see `VaultSyncAbort`) to user-facing strings. Null+     * when there is no error. Never includes key material or record contents.+     */+    fun syncErrorText(accountName: String): String? {+        val config = store.get(accountName) ?: return null+        val error = config.lastSyncError ?: return null+        val app = getApplication<Application>()+        return when {+            CH_PULL_TRANSPORT in error -> app.getString(R.string.sync_error_pull_failed)+            CH_UNDECRYPTABLE_LOG in error -> app.getString(R.string.sync_error_undecryptable)+            CH_LOCAL_READ_FAILED in error -> app.getString(R.string.sync_error_local_read)+            CH_RELAY_UNAVAILABLE in error -> app.getString(R.string.sync_error_relay_unavailable)+            else -> error+        }+    }++    private val _snapshots = MutableStateFlow<List<SnapshotMeta>>(emptyList())+    val snapshots: StateFlow<List<SnapshotMeta>> = _snapshots.asStateFlow()++    private val _restoring = MutableStateFlow(false)+    val restoring: StateFlow<Boolean> = _restoring.asStateFlow()++    fun loadSnapshots() {+        viewModelScope.launch(Dispatchers.IO) {+            _snapshots.value = SnapshotStore.listAll(getApplication())+        }+    }++    fun restoreSnapshot(snapshot: SnapshotMeta) {+        viewModelScope.launch(Dispatchers.IO) {+            _restoring.value = true+            try {+                val count = SnapshotStore.restore(getApplication(), snapshot)+                withContext(Dispatchers.Main) {+                    announce(+                        if (count != null) {+                            getApplication<Application>().getString(R.string.snapshot_restored, count)+                        } else {+                            getApplication<Application>().getString(R.string.snapshot_restore_failed)+                        },+                    )+                }+                if (count != null) {+                    // Reconcile the restored rows against the relay immediately.+                    SyncScheduler.syncAllNow(getApplication())+                }+            } finally {+                _restoring.value = false+            }+        }+    }+     // --- Vault sharing helpers (EverySync-only; see EverySyncVaults) ---      private val _safetyCode = MutableStateFlow<String?>(null)
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/E2eeProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/E2eeProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/E2eeProvider.ktindex 64ac024ef6..1d1425b1ed 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/E2eeProvider.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/E2eeProvider.kt@@ -11,6 +11,7 @@ import com.vayunmathur.everysync.data.RemotePassword import com.vayunmathur.everysync.data.RemoteTodo import com.vayunmathur.everysync.data.VaultMeta import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.readKey import com.vayunmathur.everysync.data.sink.CalendarSink import com.vayunmathur.everysync.data.sink.ContactsSink import com.vayunmathur.everysync.network.remote.RelayCursorStore@@ -24,6 +25,8 @@ import com.vayunmathur.everysync.provider.SyncState import com.vayunmathur.everysync.sync.CalendarRelayStore import com.vayunmathur.everysync.sync.ContactRelayStore import com.vayunmathur.everysync.sync.EntityKind+import com.vayunmathur.everysync.sync.LocalReadException+import com.vayunmathur.everysync.sync.SnapshotStore import com.vayunmathur.everysync.sync.NoteRelayStore import com.vayunmathur.everysync.sync.OwnerTransfer import com.vayunmathur.everysync.sync.PasswordRelayStore@@ -75,6 +78,11 @@ import kotlinx.serialization.json.Json  * PUSH/PULL direction support: PULL skips the append step (remote changes are  * still merged locally); PUSH skips applying pulled remote state locally but  * still folds + appends so local edits propagate.+ *+ * Loss-prevention: a vault cycle that cannot prove what the relay holds aborts+ * via [VaultSyncAbort] with zero local writes, zero relay appends, and zero+ * baseline/cursor mutations (see `driveMerge`). Absence is never deletion:+ * only an explicit `deleted=true` envelope deletes (see `RelayMerge`).  */ class E2eeProvider : SyncProvider {     override val id = "e2ee"@@ -92,8 +100,9 @@ class E2eeProvider : SyncProvider {     override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {         if (!RelaySync.init(context)) {             Log.error(TAG, "sync: relay unavailable for '${config.accountName}'")-            return+            throw VaultSyncAbort(CH_RELAY_UNAVAILABLE, "")         }+        var firstAbort: VaultSyncAbort? = null         for (type in capabilities) {             if (type !in config.enabledTypes) continue             try {@@ -106,10 +115,18 @@ class E2eeProvider : SyncProvider {                 }             } catch (e: CancellationException) {                 throw e+            } catch (abort: VaultSyncAbort) {+                // One vault's abort must not block the others, but it must+                // surface: SyncEngine records lastSyncError from the throw.+                Log.error(TAG, "sync $type aborted for '${config.accountName}': ${abort.code}", abort)+                if (firstAbort == null) firstAbort = abort             } catch (expected: Exception) {                 Log.error(TAG, "sync $type failed for '${config.accountName}'", expected)             }         }+        // Surface the first abort so lastSyncError reflects it; SyncEngine+        // records it via its existing catch path.+        firstAbort?.let { throw it }     }      // --- Contacts vault <-> ContactsContract via ContactsSink ---@@ -227,9 +244,30 @@ class E2eeProvider : SyncProvider {         // Full log pull (from 0): the merge needs full remote state, not a         // delta. The pull cursor still advances so live-push paths can skip         // re-reads; the merge itself never depends on it.+        //+        // A failed pull is NOT an empty log: abort with zero writes, zero+        // appends, zero baseline/cursor mutations. Merging a failure as empty+        // would delete every baseline-present row (see RelayMerge).         val pulled = RelaySync.pullRecords(channel, vault.key, 0)+            ?: throw VaultSyncAbort(CH_PULL_TRANSPORT, channelType)+        if (pulled.fullyUndecryptable) {+            // Records exist but none decrypt under this epoch key: re-key or+            // epoch fetch is needed, not a merge of an "empty" vault.+            throw VaultSyncAbort(CH_UNDECRYPTABLE_LOG, channelType)+        }         val remote = pulled.items.mapNotNull { store.parseRemote(it) }-        val local = store.listLocal()+        val local = try {+            store.listLocal()+        } catch (read: LocalReadException) {+            // A failed local read is not an empty vault: abort with zero+            // writes, zero appends, zero baseline/cursor mutations.+            throw VaultSyncAbort(CH_LOCAL_READ_FAILED, channelType)+        }+        if (!store.listLocalOk) {+            // The sink tracked a failed/partial read without throwing (null+            // cursor, swallowed IPC error): same abort, never merge.+            throw VaultSyncAbort(CH_LOCAL_READ_FAILED, channelType)+        }         val baseline = store.loadBaseline()         val plan = RelayMerge.merge(kind, local, remote, baseline, now)         if (direction != SyncDirection.PULL && vault.canEdit && plan.remoteOut.isNotEmpty()) {@@ -301,7 +339,8 @@ class E2eeProvider : SyncProvider {             }             SyncState.set(context, config.accountName, vaultScope(rt), meta.vaultId)         }-        val baseKey = runCatching { Base64.decode(meta.keyB64) }.getOrNull()+        // Unseal the Keystore-wrapped key; fail closed when it cannot be read.+        val baseKey = meta.readKey(context)         if (baseKey == null || baseKey.isEmpty()) return null         val baseOwnerKey = meta.ownerKeyB64         val ownerKey = OwnerTransfer.fetchOwnerKey(meta.vaultId, baseOwnerKey)@@ -320,6 +359,7 @@ class E2eeProvider : SyncProvider {     }      private suspend fun createVault(context: Context, accountName: String, relayType: String): VaultMeta? {+        // upsert seals keyB64 at rest; the TokenStore copy stays Keystore-encrypted too.         return runCatching {             val vaultId = RelaySync.newVaultId()             val key = RelaySync.newVaultKey()@@ -333,7 +373,7 @@ class E2eeProvider : SyncProvider {                 isOwner = true,             )             VaultStore.upsert(context, meta)-            TokenStore.getInstance(context).putSyncKey(accountName, relayType, meta.keyB64)+            TokenStore.getInstance(context).putSyncKey(accountName, relayType, Base64.encode(key))             VaultRoster.recordMembers(vaultId, listOf(RelaySync.Member(RelaySync.deviceId, "", RelayRoles.OWNER)))             publishTitle(meta)             meta@@ -377,9 +417,23 @@ class E2eeProvider : SyncProvider {          * it doesn't linger; it is pulled again if re-enabled. Called from          * `EverySyncViewModel.toggleType`. Contacts/calendar purges are          * account-wide by sink design (one call covers every vault).+         *+         * Takes a pre-purge snapshot of each affected vault first: a purge is+         * exactly the "everything vanished locally" shape the merge refuses to+         * infer, so the snapshot is the way back if the user re-enables and+         * the relay has moved on.          */         fun purgeType(context: Context, accountName: String, type: DataType) {             val rt = type.relayType() ?: return+            // Snapshot first (fire-and-forget on failure: purge is explicit+            // user intent, the snapshot is only the way back).+            for (meta in VaultStore.getAll(context).filter { it.dataType == rt }) {+                runCatching {+                    kotlinx.coroutines.runBlocking {+                        SnapshotStore.snapshotVault(context, meta.vaultId, rt)+                    }+                }+            }             when (type) {                 DataType.CONTACTS -> ContactsSink.purge(context, accountName)                 DataType.CALENDAR -> CalendarSink.purge(context, accountName)@@ -399,3 +453,19 @@ class E2eeProvider : SyncProvider {         }     } }++/**+ * A vault sync cycle that cannot prove what the relay holds. Carries a stable+ * machine-readable [code] (surfaced via `AccountConfig.lastSyncError`) plus the+ * vault [channelType] for scoping. Throwing aborts the cycle with zero local+ * writes, zero relay appends, and zero baseline/cursor mutations — never+ * degrade an abort into a merge.+ */+class VaultSyncAbort(val code: String, val channelType: String) :+    Exception("vault sync aborted: $code ($channelType)")++/** Stable `VaultSyncAbort` codes, safe to persist and to show in UI. */+const val CH_PULL_TRANSPORT = "pull_transport_failed"+const val CH_UNDECRYPTABLE_LOG = "log_undecryptable"+const val CH_LOCAL_READ_FAILED = "local_read_failed"+const val CH_RELAY_UNAVAILABLE = "relay_unavailable"
everysync/src/main/java/com/vayunmathur/everysync/sync/OwnerTransfer.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/OwnerTransfer.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/OwnerTransfer.ktindex 01d31d2404..6c6ede45bc 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/OwnerTransfer.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/OwnerTransfer.kt@@ -38,8 +38,11 @@ object OwnerTransfer {     suspend fun fetchOwnerKey(vaultId: String, baseOwnerKeyB64: String): ByteArray? {         var ownerKey = baseOwnerKeyB64.takeIf { it.isNotBlank() }             ?.let { runCatching { Base64.decode(it) }.getOrNull() } ?: return null+        // A failed pull keeps the base key: a transfer chain we cannot read is+        // not a chain that doesn't exist. resolveVault re-fetches every cycle,+        // so a recovered relay is picked up on retry.         val transfers = runCatching { RelaySync.pullRaw(ownerChannel(vaultId), 0) }-            .getOrDefault(emptyList()).mapNotNull { decodeTransfer(it) }+            .getOrNull()?.mapNotNull { decodeTransfer(it) } ?: return ownerKey         val used = HashSet<Int>()         var advanced = true         while (advanced) {
everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.ktindex fe1b02e6c9..8b387c2f83 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt@@ -83,6 +83,10 @@ object RelayBlobStore {      * Pulls blob envelopes since the persisted cursor, folds to latest per      * name, and mirrors them into local files. Advances the cursor past the      * pulled sequence. Returns the envelopes that changed something locally.+     *+     * A failed pull returns an empty list WITHOUT advancing the cursor: blob+     * deletes apply only from explicit delete envelopes in a verified pull,+     * so a failure deletes nothing and retries next cycle.      */     suspend fun pull(         context: Context,@@ -91,8 +95,14 @@ object RelayBlobStore {     ): List<BlobEnvelope> {         val channel = blobChannel(vaultId)         val since = RelayCursorStore.get(context, "notes", vaultId, channel)-        val result = RelaySync.pullRecords(channel, vaultKey, since)+        val result = RelaySync.pullRecords(channel, vaultKey, since) ?: return emptyList()         if (result.items.isEmpty()) {+            if (result.fullyUndecryptable) {+                // Records exist but none decrypt: a key/epoch problem, not an+                // empty blob log. Do NOT advance the cursor; retry next cycle.+                Log.status(TAG, "pull $channel: ${result.rawCount} records, none decryptable; skipping")+                return emptyList()+            }             RelayCursorStore.advance(context, "notes", vaultId, channel, result.seq)             return emptyList()         }
everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.ktindex b5e3f6daf0..d542da3df8 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt@@ -36,6 +36,12 @@ fun relayContentHash(canonical: String): String {  * itself ([com.vayunmathur.everysync.network.remote.RelaySync]) stays outside,  * this interface only adapts typed entities to the string envelopes the relay  * carries.+ *+ * Loss-prevention contract on [listLocal]: a failed local read must surface as+ * failure (throw `LocalReadException`, or a store whose `listLocalOk` returns+ * false), NEVER as an empty list. An empty list means "this vault provably+ * holds nothing locally" — merging a read failure as empty would delete every+ * baseline-present relay record.  */ interface RelayStore<T> {     suspend fun listLocal(): List<T>@@ -45,6 +51,14 @@ interface RelayStore<T> {     suspend fun saveSnapshots(snapshots: List<RelaySnapshot>)     suspend fun removeSnapshots(syncIds: List<String>) +    /**+     * True when the last [listLocal] observed a healthy read. Stores whose+     * read path can fail (ContentProvider IPC, system providers) track this;+     * [RelayMerge] consults it and the driver aborts on false.+     */+    val listLocalOk: Boolean+        get() = true+     /** Parse one decrypted relay envelope; null skips a foreign/corrupt entry. */     fun parseRemote(json: String): T? @@ -52,6 +66,9 @@ interface RelayStore<T> {     fun serializeForRemote(entity: T): String } +/** Thrown by [RelayStore.listLocal] when the local read cannot be trusted. */+class LocalReadException(message: String, cause: Throwable? = null) : Exception(message, cause)+ /** Per-type behaviour for the generic three-way merge. */ abstract class EntityKind<T> {     abstract val kind: String@@ -64,6 +81,18 @@ abstract class EntityKind<T> {     abstract fun withDeleted(e: T, deleted: Boolean): T     abstract fun withUpdatedAt(e: T, updatedAt: Long): T +    /**+     * Whether this store's local side carries authoritative local delete marks+     * that survive in [listLocal] output. When true (soft deletes: tombstone+     * rows from system-provider DELETED flags or app tombstone rows), an id+     * that is absent from [listLocal] WITHOUT a tombstone is never a local+     * delete — it is a missed read — so the merge resurrects the relay copy+     * instead of tombstoning it. When false (hard deletes: the row is gone and+     * only the baseline remembers it), a healthy-read absence is a genuine+     * local delete and the merge propagates a tombstone to the relay.+     */+    open val localDeletesAreAuthoritative: Boolean = true+     fun snapshot(         syncId: String,         hash: String,@@ -126,6 +155,15 @@ class MergeAccumulator<T> {  * Generic three-way merge extracted from the passwords KDBX engine, without any  * KDBX dependency.  *+ * LOSS-PREVENTION RULE: only an explicit tombstone deletes. An id that is+ * present on one side but absent from the folded relay log — with a baseline+ * or without — is NEVER treated as a deletion: the append-only relay log may+ * be truncated, partially read, or mid-propagation, and none of those is proof+ * that anyone deleted anything. Deletion propagates exclusively through an+ * explicit `deleted=true` envelope for that syncId in the folded log+ * (`reconcilePresent` tombstone path). See the KDoc on `RelaySync` for the+ * key-hygiene invariant bounding who can author tombstones.+ *  * Conflict rule is last-writer-wins by [EntityKind.updatedAt], tie-broken by  * [EntityKind.contentHash] so equal timestamps stay deterministic across  * devices. Tombstones ([EntityKind.isDeleted]) win or lose by the same LWW@@ -133,6 +171,9 @@ class MergeAccumulator<T> {  *  * Driver contract (the relay is an append-only log — records are never  * rewritten, only appended):+ *  0. NEVER call `merge` with a remote fold the transport could not prove:+ *     a failed pull must abort the cycle, not produce an empty [remoteEntities]+ *     list. (An empty list here means "the log provably holds nothing".)  *  1. Fold the full decrypted record log into [remoteEntities] (tombstones  *     included; this must be the FULL state, not a delta, so absence vs  *     deletion stays decidable against the baseline).@@ -153,7 +194,13 @@ object RelayMerge {         val accumulator = MergeAccumulator<T>()         val local = indexLocal(kind, localEntities, accumulator)         val remote = indexRemote(kind, local, remoteEntities, accumulator)-        reconcileAll(kind, local, remote, baseline, now, accumulator)+        // The authoritative-marks flag lives on the kind: one source of truth+        // per vault type (soft-delete stores resurrect unmarked absences;+        // hard-delete stores propagate them as genuine deletes).+        reconcileAll(+            kind, local, remote, baseline, now, accumulator,+            kind.localDeletesAreAuthoritative,+        )         return accumulator.toPlan()     } @@ -236,9 +283,10 @@ object RelayMerge {         baseline: Map<String, RelaySnapshot>,         now: Long,         accumulator: MergeAccumulator<T>,+        localDeletesAreAuthoritative: Boolean,     ) {         for (id in local.keys + remote.keys) {-            reconcileOne(kind, id, local[id], remote[id], baseline[id], now, accumulator)+            reconcileOne(kind, id, local[id], remote[id], baseline[id], now, accumulator, localDeletesAreAuthoritative)         }     } @@ -250,6 +298,7 @@ object RelayMerge {         base: RelaySnapshot?,         now: Long,         accumulator: MergeAccumulator<T>,+        localDeletesAreAuthoritative: Boolean,     ) {         if (localEntity != null && remoteEntity != null) {             reconcilePresent(kind, id, localEntity, remoteEntity, base, now, accumulator)@@ -259,7 +308,7 @@ object RelayMerge {             reconcileLocalOnly(kind, id, localEntity, base, now, accumulator)             return         }-        reconcileRemoteOnly(kind, id, remoteEntity!!, base, now, accumulator)+        reconcileRemoteOnly(kind, id, remoteEntity!!, base, now, accumulator, localDeletesAreAuthoritative)     }      private fun <T> reconcilePresent(@@ -473,10 +522,12 @@ object RelayMerge {             accumulator.removed += id             return         }-        // Present at baseline, gone from the folded relay state: the remote deleted it.-        accumulator.localDeletes += localEntity-        accumulator.removed += id-        accumulator.deletedLocal+++        // Present at baseline but absent from the folded relay log WITHOUT an+        // explicit tombstone: NOT a remote delete. The log may be truncated or+        // partially read (which step 0 of the driver contract rules out only+        // for transport failure, not for a wiped/shortened log). Keep the+        // local row and the baseline untouched; the id will reconcile on a+        // later cycle once its record (or a real tombstone) reappears.     }      private fun <T> reconcileRemoteOnly(@@ -486,14 +537,18 @@ object RelayMerge {         base: RelaySnapshot?,         now: Long,         accumulator: MergeAccumulator<T>,+        localDeletesAreAuthoritative: Boolean,     ) {         if (base?.deleted == true) {             // Tombstone already acknowledged: steady state, nothing to do.             return         }-        if (base != null && !kind.isDeleted(remoteEntity)) {-            // Present at baseline, gone locally: the local side deleted it.-            // Append a tombstone so the delete propagates instead of resurrecting.+        if (base != null && !kind.isDeleted(remoteEntity) && !localDeletesAreAuthoritative) {+            // Hard-delete store (passwords): rows vanish with only the baseline+            // remembering them, so a healthy-read absence IS a genuine local+            // delete. Propagate a tombstone so the delete does not resurrect.+            // (driveMerge aborts on failed local reads, so absence here is+            // evidence, not a missed read.)             val tombstone = kind.withUpdatedAt(                 kind.withDeleted(kind.rebind(remoteEntity, id), true),                 maxOf(kind.updatedAt(remoteEntity), now),@@ -511,6 +566,44 @@ object RelayMerge {             accumulator.deletedRemote++             return         }+        if (base != null && !kind.isDeleted(remoteEntity)) {+            // Soft-delete store (notes, todos, contacts, calendar): local+            // deletes carry explicit marks (app tombstone rows or+            // system-provider DELETED flags surfaced via getLocalChanges), so+            // an absence WITHOUT a mark is never a local delete — it is a+            // missed read. Do NOT tombstone the relay on zero evidence.+            // Pull the relay copy back instead; a genuinely deleted row will+            // arrive with its mark and propagate through the normal path.+            val rebound = kind.rebind(remoteEntity, id)+            if (kind.isDeleted(rebound)) {+                accumulator.snapshots += kind.snapshot(+                    id,+                    kind.contentHash(rebound),+                    kind.updatedAt(rebound),+                    kind.updatedAt(rebound),+                    now,+                    true,+                )+                accumulator.deletedRemote+++                return+            }+            accumulator.localUpserts += rebound+            if (id in accumulator.adoptedRemote) {+                // The relay copy lacks our sync id; re-append it identified.+                accumulator.remoteOut += rebound+                accumulator.remoteChanged = true+            }+            accumulator.pulled+++            val stamp = kind.updatedAt(remoteEntity)+            accumulator.snapshots += kind.snapshot(+                id,+                kind.contentHash(rebound),+                stamp,+                stamp,+                now,+            )+            return+        }         val rebound = kind.rebind(remoteEntity, id)         if (kind.isDeleted(rebound)) {             // Fresh remote tombstone with no local row: record it, nothing to pull.
everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.ktnew file mode 100644index 0000000000..7ca24ac938--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt@@ -0,0 +1,425 @@+package com.vayunmathur.everysync.sync++import android.content.Context+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.sink.CalendarSink+import com.vayunmathur.everysync.data.sink.ContactsSink+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.provider.SyncState+import com.vayunmathur.everysync.sync.adapters.CalendarKind+import com.vayunmathur.everysync.sync.adapters.ContactKind+import com.vayunmathur.everysync.sync.adapters.NoteKind+import com.vayunmathur.everysync.sync.adapters.PasswordKind+import com.vayunmathur.everysync.sync.adapters.TodoKind+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.security.SecureRandom+import javax.crypto.Cipher+import javax.crypto.spec.GCMParameterSpec+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Daily encrypted snapshots of every vault type — the last-resort recovery net.+ *+ * Each snapshot is the vault's full local state in relay-envelope form (the+ * exact bytes the merge driver consumes), AES-256-GCM encrypted with a+ * device-local snapshot key (Keystore-backed via [SnapshotKeyStore], same+ * pattern as `TokenStore`), written to `filesDir/snapshots/<vaultId>/<day>.bin`+ * plus `RelayBlobStore` file copies for note images.+ *+ * - One snapshot per day per (vaultId, type), taken by [SnapshotWorker].+ * - 30-day TTL: entries older than [RETENTION_DAYS] are pruned on every write.+ * - Restore replays envelopes through the existing sink `upsertAll` paths as+ *   normal merge input, so conflicts with newer edits resolve by the existing+ *   LWW rules — restore never overwrites by force.+ * - `purgeType` callers must snapshot first (see `E2eeProvider.purgeType`+ *   contract): a sync-off purge is exactly the "everything vanished locally"+ *   shape the merge refuses to infer, so the snapshot is the way back.+ *+ * Never log envelope plaintext, keys, or snapshot contents — only counts and ids.+ */+object SnapshotStore {+    private const val TAG = "SnapshotStore"++    /** Snapshots older than this are pruned on every write. */+    const val RETENTION_DAYS = 30L+    private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000++    private const val DIR_SNAPSHOTS = "snapshots"+    private const val DIR_BLOBS = "blobs"+    private const val EXT = ".bin"++    private const val KEY_INDEX = "snapshot_index"+    private const val KEY_LAST_TAKEN_PREFIX = "snapshot_last_taken:"++    private val json = Json { ignoreUnknownKeys = true }++    /** One restorable snapshot: day (epoch millis at midnight UTC) + envelope payloads. */+    @Serializable+    data class SnapshotMeta(+        val vaultId: String,+        val dataType: String,+        val dayEpochMs: Long,+        val recordCount: Int,+        val blobCount: Int = 0,+        val takenAtMs: Long = 0L,+    )++    @Serializable+    private data class StoredIndex(val snapshots: List<SnapshotMeta> = emptyList())++    @Serializable+    private data class SnapshotPayload(+        val records: List<String> = emptyList(),+        /** Blob name -> base64 bytes (note images only; contacts/calendar/passwords/todos carry none). */+        val blobs: Map<String, String> = emptyMap(),+    )++    private fun vaultDir(context: Context, vaultId: String): File =+        File(File(context.filesDir, DIR_SNAPSHOTS), vaultId).apply { mkdirs() }++    private fun snapshotFile(context: Context, vaultId: String, dayEpochMs: Long): File =+        File(vaultDir(context, vaultId), "$dayEpochMs$EXT")++    private fun blobDir(context: Context, vaultId: String): File =+        File(File(vaultDir(context, vaultId), DIR_BLOBS), "").apply { mkdirs() }++    private fun dayOf(timestampMs: Long): Long = (timestampMs / MILLIS_PER_DAY) * MILLIS_PER_DAY++    private fun loadIndex(context: Context): StoredIndex {+        val raw = DataStoreUtils.getInstance(context).getString(KEY_INDEX)+        if (raw.isNullOrBlank()) return StoredIndex()+        return runCatching { json.decodeFromString<StoredIndex>(raw) }.getOrDefault(StoredIndex())+    }++    private suspend fun saveIndex(context: Context, index: StoredIndex) {+        DataStoreUtils.getInstance(context).setString(KEY_INDEX, json.encodeToString(index))+    }++    /** All known snapshots, newest first. */+    fun listAll(context: Context): List<SnapshotMeta> =+        loadIndex(context).snapshots.sortedByDescending { it.dayEpochMs }++    /** Snapshots for one vault, newest first. */+    fun listForVault(context: Context, vaultId: String): List<SnapshotMeta> =+        listAll(context).filter { it.vaultId == vaultId }++    /** True when a snapshot was already taken today for this vault. */+    fun takenToday(context: Context, vaultId: String, nowMs: Long = System.currentTimeMillis()): Boolean {+        val last = DataStoreUtils.getInstance(context)+            .getLong(KEY_LAST_TAKEN_PREFIX + vaultId) ?: 0L+        return dayOf(last) == dayOf(nowMs)+    }++    /**+     * Takes today's snapshot for every known vault (all five types + note+     * blobs). Skips vaults already snapshotted today. Prunes entries older+     * than [RETENTION_DAYS] afterwards. Returns how many snapshots were taken.+     */+    suspend fun snapshotAll(context: Context, nowMs: Long = System.currentTimeMillis()): Int =+        withContext(Dispatchers.IO) {+            var taken = 0+            for (meta in VaultStore.getAll(context)) {+                if (takenToday(context, meta.vaultId, nowMs)) continue+                if (snapshotVault(context, meta.vaultId, meta.dataType, nowMs)) taken+++            }+            pruneExpired(context, nowMs)+            taken+        }++    /**+     * Takes today's snapshot for one vault. Records are the sink's full local+     * state in relay-envelope bytes (tombstones included — a restore must see+     * the same deletes the merge saw). Returns false when the local read is+     * unhealthy (never snapshot a partial view) or the vault has no key.+     */+    suspend fun snapshotVault(+        context: Context,+        vaultId: String,+        dataType: String,+        nowMs: Long = System.currentTimeMillis(),+    ): Boolean = withContext(Dispatchers.IO) {+        val day = dayOf(nowMs)+        val (records, healthy) = readRecords(context, vaultId, dataType)+        if (!healthy) {+            Log.status(TAG, "snapshot skipped for $vaultId/$dataType: unhealthy local read")+            return@withContext false+        }+        val blobs = readBlobs(context, vaultId, dataType)+        val payload = SnapshotPayload(records, blobs)+        val plain = json.encodeToString(payload).encodeToByteArray()+        val sealed = SnapshotKeyStore.seal(context, plain) ?: run {+            Log.error(TAG, "snapshot failed for $vaultId/$dataType: keystore unavailable")+            return@withContext false+        }+        runCatching { snapshotFile(context, vaultId, day).writeBytes(sealed) }.getOrNull()+            ?: run {+                Log.error(TAG, "snapshot failed for $vaultId/$dataType: write failed")+                return@withContext false+            }+        // Blob copies ride inside the sealed payload; the blob dir mirrors the+        // live files for inspection-free restore (never read back except restore).+        val index = loadIndex(context)+        val kept = index.snapshots.filterNot { it.vaultId == vaultId && it.dayEpochMs == day } ++            SnapshotMeta(vaultId, dataType, day, records.size, blobs.size, nowMs)+        saveIndex(context, StoredIndex(kept))+        DataStoreUtils.getInstance(context).setLong(KEY_LAST_TAKEN_PREFIX + vaultId, nowMs)+        Log.status(TAG, "snapshot taken for $vaultId/$dataType: ${records.size} records, ${blobs.size} blobs")+        pruneExpired(context, nowMs)+        true+    }++    /**+     * Restores [snapshot] by replaying its envelopes through the sink+     * `upsertAll` paths with pulled timestamps preserved — i.e. as normal+     * merge input. Newer local edits win by LWW where they conflict; nothing+     * is force-overwritten and baselines are left for the next sync cycle to+     * reconcile. Returns the restored record count, or null on failure.+     */+    suspend fun restore(context: Context, snapshot: SnapshotMeta): Int? =+        withContext(Dispatchers.IO) {+            val sealed = runCatching {+                snapshotFile(context, snapshot.vaultId, snapshot.dayEpochMs).readBytes()+            }.getOrNull() ?: return@withContext null+            val plain = SnapshotKeyStore.unseal(context, sealed) ?: return@withContext null+            val payload = runCatching {+                json.decodeFromString<SnapshotPayload>(plain.decodeToString())+            }.getOrNull() ?: return@withContext null+            val count = writeRecords(context, snapshot.vaultId, snapshot.dataType, payload.records)+                ?: return@withContext null+            writeBlobs(context, snapshot.vaultId, snapshot.dataType, payload.blobs)+            Log.status(TAG, "restored ${snapshot.vaultId}/${snapshot.dataType} @${snapshot.dayEpochMs}: $count records")+            count+        }++    /** Drops snapshots (files + index rows) older than [RETENTION_DAYS]. */+    suspend fun pruneExpired(context: Context, nowMs: Long = System.currentTimeMillis()) =+        withContext(Dispatchers.IO) {+            val cutoff = dayOf(nowMs) - RETENTION_DAYS * MILLIS_PER_DAY+            val index = loadIndex(context)+            val (expired, kept) = index.snapshots.partition { it.dayEpochMs < cutoff }+            if (expired.isEmpty()) return@withContext+            for (meta in expired) {+                runCatching { snapshotFile(context, meta.vaultId, meta.dayEpochMs).delete() }+            }+            // Drop blob mirrors for vaults with no snapshots left.+            val liveVaults = kept.map { it.vaultId }.toSet()+            for (meta in expired.filterNot { it.vaultId in liveVaults }) {+                runCatching { blobDir(context, meta.vaultId).deleteRecursively() }+            }+            saveIndex(context, StoredIndex(kept))+            Log.status(TAG, "pruned ${expired.size} expired snapshots")+        }++    // --- Per-type record readers (envelope bytes + health flag) ---++    private fun readRecords(context: Context, vaultId: String, dataType: String): Pair<List<String>, Boolean> {+        return when (dataType) {+            "passwords" -> {+                // Throws on unhealthy read — fail closed, never snapshot partial.+                val records = runCatching {+                    PasswordSink.listLocalOrThrow(context, vaultId)+                        .map { PasswordKind.toJson(it) }+                }.getOrNull()+                if (records == null || !PasswordSink.lastListLocalOk) emptyList<String>() to false+                else records to true+            }+            "notes" -> {+                val records = NoteSink.listLocal(context, vaultId).map { NoteKind.toJson(it) }+                if (!NoteSink.lastListLocalOk) emptyList<String>() to false else records to true+            }+            "todos" -> {+                val records = TodoIpcSink.listLocal(context, vaultId).map { TodoKind.toJson(it) }+                if (!TodoIpcSink.lastListLocalOk) emptyList<String>() to false else records to true+            }+            "contacts" -> {+                // Contacts/calendar rows are account-scoped, not vault-scoped:+                // snapshot the bound account's rows (see accountForVault).+                val account = accountForVault(context, vaultId) ?: return emptyList<String>() to false+                val records = ContactsSink.listLocal(context, account).map { ContactKind.toJson(it) }+                if (!ContactsSink.lastListLocalOk) emptyList<String>() to false else records to true+            }+            "calendar" -> {+                val account = accountForVault(context, vaultId) ?: return emptyList<String>() to false+                val calendarId = CalendarSink.localCalendars(context, account)+                    .firstOrNull() ?: return emptyList<String>() to true+                val records = CalendarSink.listLocal(context, calendarId).map { CalendarKind.toJson(it) }+                if (!CalendarSink.lastListLocalOk) emptyList<String>() to false else records to true+            }+            else -> emptyList<String>() to false+        }+    }++    private fun accountForVault(context: Context, vaultId: String): String? {+        // Reverse the SyncState account->vault binding: scan known vault scopes.+        // The binding key layout is `e2ee_vault_<type>` per account.+        // Fallback: the single account when exactly one exists.+        val accounts = AccountStore.getInstance(context).getAll()+        if (accounts.size == 1) return accounts.single().accountName+        for (account in accounts) {+            for (type in listOf("contacts", "calendar", "passwords", "notes", "todos")) {+                if (SyncState.get(context, account.accountName, "e2ee_vault_$type") == vaultId) {+                    return account.accountName+                }+            }+        }+        return null+    }++    private fun readBlobs(context: Context, vaultId: String, dataType: String): Map<String, String> {+        if (dataType != "notes") return emptyMap()+        val dir = File(context.filesDir, "relay_blobs/$vaultId")+        if (!dir.isDirectory) return emptyMap()+        return dir.listFiles()?.filter { it.isFile }?.associate { file ->+            val bytes = runCatching { file.readBytes() }.getOrNull() ?: return@associate file.name to ""+            file.name to Base64.encode(bytes)+        }?.filterValues { it.isNotEmpty() } ?: emptyMap()+    }++    private fun writeRecords(+        context: Context,+        vaultId: String,+        dataType: String,+        records: List<String>,+    ): Int? {+        return runCatching {+            when (dataType) {+                "passwords" -> {+                    val parsed = records.mapNotNull { PasswordKind.fromJson(it) }+                    PasswordSink.upsertAll(context, vaultId, parsed)+                    parsed.size+                }+                "notes" -> {+                    val parsed = records.mapNotNull { NoteKind.fromJson(it) }+                    NoteSink.upsertAll(context, vaultId, parsed)+                    parsed.size+                }+                "todos" -> {+                    val parsed = records.mapNotNull { TodoKind.fromJson(it) }+                    TodoIpcSink.upsertAll(context, vaultId, parsed)+                    parsed.size+                }+                "contacts" -> {+                    val account = accountForVault(context, vaultId) ?: return null+                    val parsed = records.mapNotNull { ContactKind.fromJson(it) }+                    for (item in parsed) ContactsSink.upsert(context, account, item)+                    parsed.size+                }+                "calendar" -> {+                    val account = accountForVault(context, vaultId) ?: return null+                    val calendarId = CalendarSink.getOrCreateCalendarId(+                        context, account, vaultId, vaultId, null,+                    )+                    if (calendarId == -1L) return null+                    val parsed = records.mapNotNull { CalendarKind.fromJson(it) }+                    for (item in parsed) CalendarSink.upsertEvent(context, account, calendarId, item)+                    parsed.size+                }+                else -> null+            }+        }.getOrNull()+    }++    private fun writeBlobs(context: Context, vaultId: String, dataType: String, blobs: Map<String, String>) {+        if (dataType != "notes" || blobs.isEmpty()) return+        for ((name, b64) in blobs) {+            if (name.isBlank()) continue+            val bytes = runCatching { Base64.decode(b64) }.getOrNull() ?: continue+            RelayBlobStore.writeLocal(context, vaultId, name, bytes)+        }+    }+}++/**+ * Device-local AES-256-GCM snapshot key, Keystore-backed (same pattern as+ * `TokenStore`: non-exportable Keystore key encrypts the bytes, ciphertext in+ * DataStore). Snapshots are recoverable only on this device — by design: the+ * relay already covers cross-device recovery, snapshots cover local disaster.+ */+private object SnapshotKeyStore {+    private const val ANDROID_KEYSTORE = "AndroidKeyStore"+    private const val KEY_ALIAS = "everysync_snapshot_key"+    private const val TRANSFORMATION = "AES/GCM/NoPadding"+    private const val GCM_TAG_BITS = 128++    private fun secretKey(): javax.crypto.SecretKey {+        val ks = java.security.KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (ks.getEntry(KEY_ALIAS, null) as? java.security.KeyStore.SecretKeyEntry)?.let { return it.secretKey }+        val generator = javax.crypto.KeyGenerator.getInstance(+            android.security.keystore.KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE,+        )+        generator.init(+            android.security.keystore.KeyGenParameterSpec.Builder(+                KEY_ALIAS,+                android.security.keystore.KeyProperties.PURPOSE_ENCRYPT or+                    android.security.keystore.KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(android.security.keystore.KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(android.security.keystore.KeyProperties.ENCRYPTION_PADDING_NONE)+                .build(),+        )+        return generator.generateKey()+    }++    fun seal(context: Context, plain: ByteArray): ByteArray? = runCatching {+        // Fresh random content key per snapshot file, wrapped by the Keystore+        // key: keeps the Keystore key's GCM nonce space unbounded.+        val contentKey = ByteArray(32).also { SecureRandom().nextBytes(it) }+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(contentKey, "AES"))+        val iv = cipher.iv+        val ct = cipher.doFinal(plain)+        val wrapCipher = Cipher.getInstance(TRANSFORMATION)+        wrapCipher.init(Cipher.ENCRYPT_MODE, secretKey())+        val wrapIv = wrapCipher.iv+        val wrappedKey = wrapCipher.doFinal(contentKey)+        // Wrap parameters live alongside the file header (length-prefixed).+        wrapIv.size.toByteArray() + wrapIv + wrappedKey.size.toByteArray() + wrappedKey ++            iv.size.toByteArray() + iv + ct+    }.getOrNull()++    fun unseal(context: Context, sealed: ByteArray): ByteArray? = runCatching {+        var off = 0+        fun readChunk(): ByteArray {+            val len = sealed.copyOfRange(off, off + 4).toInt()+            off += 4+            val chunk = sealed.copyOfRange(off, off + len)+            off += len+            return chunk+        }+        val wrapIv = readChunk()+        val wrappedKey = readChunk()+        val iv = readChunk()+        val ct = sealed.copyOfRange(off, sealed.size)+        val unwrapCipher = Cipher.getInstance(TRANSFORMATION)+        unwrapCipher.init(+            Cipher.DECRYPT_MODE, secretKey(),+            GCMParameterSpec(GCM_TAG_BITS, wrapIv),+        )+        val contentKey = unwrapCipher.doFinal(wrappedKey)+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(+            Cipher.DECRYPT_MODE, SecretKeySpec(contentKey, "AES"),+            GCMParameterSpec(GCM_TAG_BITS, iv),+        )+        cipher.doFinal(ct)+    }.getOrNull()++    private fun Int.toByteArray(): ByteArray = byteArrayOf(+        (this shr 24).toByte(), (this shr 16).toByte(), (this shr 8).toByte(), this.toByte(),+    )++    private fun ByteArray.toInt(): Int =+        ((this[0].toInt() and 0xFF) shl 24) or ((this[1].toInt() and 0xFF) shl 16) or+            ((this[2].toInt() and 0xFF) shl 8) or (this[3].toInt() and 0xFF)+}
everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotWorker.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotWorker.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotWorker.ktnew file mode 100644index 0000000000..b99afa014b--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotWorker.kt@@ -0,0 +1,47 @@+package com.vayunmathur.everysync.sync++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.library.log.Log+import java.util.concurrent.TimeUnit++/**+ * Takes the daily encrypted snapshot of every vault ([SnapshotStore]) and+ * prunes entries older than the 30-day retention. Runs once a day, survives+ * reboots via the same WorkManager persistence as the sync schedule (plus+ * [com.vayunmathur.everysync.platform.BootReceiver] re-registration).+ */+class SnapshotWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {++    override suspend fun doWork(): Result {+        return try {+            val taken = SnapshotStore.snapshotAll(applicationContext)+            Log.status(TAG, "daily snapshots: $taken taken")+            Result.success()+        } catch (expected: Exception) {+            Log.error(TAG, "daily snapshots failed", expected)+            Result.retry()+        }+    }++    companion object {+        private const val TAG = "SnapshotWorker"+        private const val UNIQUE_WORK = "EverySyncSnapshots"++        fun scheduleDaily(context: Context) {+            val request = PeriodicWorkRequestBuilder<SnapshotWorker>(24, TimeUnit.HOURS)+                .build()+            WorkManager.getInstance(context).enqueueUniquePeriodicWork(+                UNIQUE_WORK, ExistingPeriodicWorkPolicy.KEEP, request,+            )+        }++        fun cancel(context: Context) {+            WorkManager.getInstance(context).cancelUniqueWork(UNIQUE_WORK)+        }+    }+}
everysync/src/main/java/com/vayunmathur/everysync/sync/VaultKeys.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultKeys.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultKeys.ktindex 26f10271ad..4071fb4ca0 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultKeys.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultKeys.kt@@ -39,6 +39,10 @@ object VaultKeys {      * Resolves the current content key: the highest owner-signed epoch this      * device can unseal, falling back to ([inviteEpoch], [inviteKey]).      * Returns (epoch, key).+     *+     * A failed pull keeps the invite key (the epoch loop simply finds nothing+     * newer); epoch-bearing history stays unreadable until the pull succeeds,+     * which is fail-closed — the record cycle aborts before merging.      */     suspend fun fetchCurrentKey(         vaultId: String,@@ -50,7 +54,9 @@ object VaultKeys {         if (ownerKey == null || ownerKey.isEmpty()) return inviteEpoch to inviteKey         var bestEpoch = inviteEpoch         var bestKey = inviteKey-        for (blob in runCatching { RelaySync.pullRaw(keysChannel(vaultId), 0) }.getOrDefault(emptyList())) {+        val blobs = runCatching { RelaySync.pullRaw(keysChannel(vaultId), 0) }.getOrNull()+            ?: return inviteEpoch to inviteKey+        for (blob in blobs) {             val epoch = decodeEpoch(blob) ?: continue             val sig = runCatching { Base64.decode(epoch.sig) }.getOrNull() ?: continue             if (!RelaySync.verify(ownerKey, epochSigningBytes(vaultId, epoch.epoch, epoch.wraps), sig)) continue
everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.ktindex fe5fa22b48..aab5533ce7 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt@@ -45,6 +45,15 @@ class ContactRelayStore(     private val context: Context,     private val accountName: String, ) : RelayStore<RemoteContact> {+    /**+     * Contacts soft-delete at the platform layer (DELETED flags surfaced via+     * `getLocalChanges`), so a missing id without a mark is never a local+     * delete (see `EntityKind.localDeletesAreAuthoritative`). Read health is+     * still enforced via `listLocalOk`.+     */+    override val listLocalOk: Boolean+        get() = ContactsSink.lastListLocalOk+     override suspend fun listLocal(): List<RemoteContact> =         ContactsSink.listLocal(context, accountName) @@ -79,6 +88,14 @@ class CalendarRelayStore(     private val accountName: String,     private val calendarId: Long, ) : RelayStore<RemoteEvent> {+    /**+     * Calendar soft-deletes at the platform layer like contacts (see+     * `ContactRelayStore`): a missing id without a mark is never a local+     * delete.+     */+    override val listLocalOk: Boolean+        get() = CalendarSink.lastListLocalOk+     override suspend fun listLocal(): List<RemoteEvent> =         CalendarSink.listLocal(context, calendarId) @@ -112,8 +129,18 @@ class PasswordRelayStore(     private val context: Context,     private val vaultId: String, ) : RelayStore<RemotePassword> {+    /**+     * Passwords hard-delete locally: rows vanish with only the app-side+     * `SyncSnapshot` remembering them. A healthy-read absence is therefore a+     * genuine local delete, and the merge propagates a relay tombstone for it.+     * Read health is enforced by `listLocalOk` (plus `listLocal` throwing):+     * a provider failure aborts the cycle instead of merging a partial view.+     */+    override val listLocalOk: Boolean+        get() = PasswordSink.lastListLocalOk+     override suspend fun listLocal(): List<RemotePassword> =-        PasswordSink.listLocal(context, vaultId)+        PasswordSink.listLocalOrThrow(context, vaultId)      override suspend fun upsertLocal(items: List<RemotePassword>) {         PasswordSink.upsertAll(context, vaultId, items)@@ -147,6 +174,15 @@ class NoteRelayStore(     private val context: Context,     private val vaultId: String, ) : RelayStore<RemoteNote> {+    /**+     * Notes soft-delete (tombstone rows survive in `listLocal`), so a missing+     * id without a mark is never a local delete (see+     * `EntityKind.localDeletesAreAuthoritative`). Read health is still+     * enforced via `listLocalOk`.+     */+    override val listLocalOk: Boolean+        get() = NoteSink.lastListLocalOk+     override suspend fun listLocal(): List<RemoteNote> =         NoteSink.listLocal(context, vaultId) @@ -182,6 +218,13 @@ class TodoRelayStore(     private val context: Context,     private val vaultId: String, ) : RelayStore<RemoteTodo> {+    /**+     * Todos soft-delete like notes (see `NoteRelayStore`): a missing id+     * without a mark is never a local delete.+     */+    override val listLocalOk: Boolean+        get() = TodoIpcSink.lastListLocalOk+     override suspend fun listLocal(): List<RemoteTodo> =         TodoIpcSink.listLocal(context, vaultId) 
everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRoster.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRoster.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRoster.ktindex 34c0ae1176..1de92a8435 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRoster.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRoster.kt@@ -40,13 +40,19 @@ object VaultRoster {     /**      * Reads + verifies the roster: only envelopes with a valid [ownerKey]      * signature are honored. Returns member id → member, last record wins.+     *+     * A failed pull returns an empty map (fail closed): the merge driver+     * already aborts the record cycle before consulting the roster, and+     * `resolveVault` treats "not on roster" as "skip this vault".      */     suspend fun fetchRoster(vaultId: String, ownerKey: ByteArray): Map<String, RelaySync.Member> {         if (ownerKey.isEmpty()) return emptyMap()+        val raw = runCatching { RelaySync.pullRaw(membersChannel(vaultId), 0) }.getOrNull()+            ?: return emptyMap()         val byId = LinkedHashMap<String, RelaySync.Member>()-        for (raw in runCatching { RelaySync.pullRaw(membersChannel(vaultId), 0) }.getOrDefault(emptyList())) {+        for (r in raw) {             val envelope = runCatching {-                json.decodeFromString<RelaySync.SignedEnvelope>(raw)+                json.decodeFromString<RelaySync.SignedEnvelope>(r)             }.getOrNull() ?: continue             val sig = runCatching { Base64.decode(envelope.sig) }.getOrNull() ?: continue             if (!RelaySync.verify(ownerKey, envelope.payload.encodeToByteArray(), sig)) continue
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/CalendarKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/CalendarKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/CalendarKind.ktindex e66eec1bcf..e22787ce3f 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/CalendarKind.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/CalendarKind.kt@@ -16,6 +16,9 @@ import kotlinx.serialization.json.Json object CalendarKind : EntityKind<RemoteEvent>() {     override val kind = "event" +    /** Calendar soft-deletes at the platform layer (DELETED flags); the default holds. */+    override val localDeletesAreAuthoritative = true+     private val json = Json { ignoreUnknownKeys = true }      /** UID + RECURRENCE-ID so one instance never collides with its master. */
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/ContactKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/ContactKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/ContactKind.ktindex b45c95087b..1272594178 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/ContactKind.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/ContactKind.kt@@ -16,6 +16,9 @@ import kotlinx.serialization.json.Json object ContactKind : EntityKind<RemoteContact>() {     override val kind = "contact" +    /** Contacts soft-delete at the platform layer (DELETED flags); the default holds. */+    override val localDeletesAreAuthoritative = true+     private val json = Json { ignoreUnknownKeys = true }      override fun syncId(e: RemoteContact) = e.uid
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/NoteKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/NoteKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/NoteKind.ktindex 77083ae302..f42889f29e 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/NoteKind.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/NoteKind.kt@@ -14,6 +14,9 @@ import kotlinx.serialization.json.Json object NoteKind : EntityKind<RemoteNote>() {     override val kind = "note" +    /** Notes soft-delete (tombstone rows survive locally); the default holds. */+    override val localDeletesAreAuthoritative = true+     private val json = Json { ignoreUnknownKeys = true }      override fun syncId(e: RemoteNote) = e.uid
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.ktindex dd08406b2b..430556fdd4 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt@@ -14,6 +14,13 @@ import kotlinx.serialization.json.Json object PasswordKind : EntityKind<RemotePassword>() {     override val kind = "password" +    /**+     * Passwords hard-delete locally (rows vanish; only the app-side snapshot+     * remembers them), so a healthy-read absence IS a genuine local delete.+     * See `EntityKind.localDeletesAreAuthoritative`.+     */+    override val localDeletesAreAuthoritative = false+     private val json = Json { ignoreUnknownKeys = true }      override fun syncId(e: RemotePassword) = e.uid@@ -42,6 +49,13 @@ object PasswordKind : EntityKind<RemotePassword>() {         e.copy(uid = "", updatedAt = 0L, deleted = false),     ) +    /**+     * True when this envelope is an explicit deletion marker. The merge treats+     * ONLY such envelopes as deletes; every other envelope is live data even+     * when the referenced row is otherwise unknown.+     */+    fun isTombstoneEnvelope(e: RemotePassword): Boolean = e.deleted+     fun toJson(e: RemotePassword): String = json.encodeToString(e)      fun fromJson(raw: String): RemotePassword? = runCatching {
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoKind.ktindex 37daf64ad9..b3063906ae 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoKind.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoKind.kt@@ -20,6 +20,9 @@ import kotlinx.serialization.json.Json object TodoKind : EntityKind<RemoteTodo>() {     override val kind = "todo" +    /** Todos soft-delete like notes; the default holds. */+    override val localDeletesAreAuthoritative = true+     private val json = Json { ignoreUnknownKeys = true }      /** Relay channel for a vault's task log. */
everysync/src/main/java/com/vayunmathur/everysync/ui/AccountDetailScreen.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/ui/AccountDetailScreen.kt b/everysync/src/main/java/com/vayunmathur/everysync/ui/AccountDetailScreen.ktindex cdd9949282..01eac06780 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/ui/AccountDetailScreen.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/ui/AccountDetailScreen.kt@@ -25,6 +25,7 @@ import com.vayunmathur.everysync.provider.ProviderRegistry import com.vayunmathur.everysync.platform.AccountDetailActions import com.vayunmathur.everysync.platform.AccountDetailUiState import com.vayunmathur.everysync.platform.EverySyncViewModel+import com.vayunmathur.everysync.sync.SnapshotStore.SnapshotMeta import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.sharedText @@ -38,7 +39,12 @@ fun AccountDetailScreen(backStack: NavBackStack<Route>, viewModel: EverySyncView     val vaultUi by viewModel.vaults.vaultUi.collectAsStateWithLifecycle()     val safetyCode by viewModel.safetyCode.collectAsStateWithLifecycle()     val computingCode by viewModel.computingCode.collectAsStateWithLifecycle()-    LaunchedEffect(Unit) { viewModel.vaults.load() }+    val snapshots by viewModel.snapshots.collectAsStateWithLifecycle()+    val restoring by viewModel.restoring.collectAsStateWithLifecycle()+    LaunchedEffect(Unit) {+        viewModel.vaults.load()+        viewModel.loadSnapshots()+    }     val actions = remember(viewModel, backStack) {         object : AccountDetailActions {             override fun toggleType(accountName: String, type: DataType, enabled: Boolean) =@@ -46,6 +52,10 @@ fun AccountDetailScreen(backStack: NavBackStack<Route>, viewModel: EverySyncView              override fun syncNow(accountName: String) = viewModel.syncNow(accountName) +            override fun restoreSnapshot(snapshot: SnapshotMeta) = viewModel.restoreSnapshot(snapshot)++            override fun snapshotNow() = viewModel.snapshotNow()+             override fun removeAccount(accountName: String) {                 viewModel.removeAccount(accountName)                 backStack.pop()@@ -87,6 +97,11 @@ fun AccountDetailScreen(backStack: NavBackStack<Route>, viewModel: EverySyncView             deviceId = deviceId,             safetyCode = safetyCode,             computingCode = computingCode,+            syncErrorText = config?.let { viewModel.syncErrorText(accountName) },+            snapshots = snapshots.filter { snap ->+                vaults.any { it.vaultId == snap.vaultId }+            },+            restoring = restoring,         ),         actions = actions,     )@@ -116,6 +131,10 @@ fun AccountDetailScreen(state: AccountDetailUiState, actions: AccountDetailActio             Text(stringResource(R.string.no_accounts))             return@DetailScaffold         }+        state.syncErrorText?.let { errorText ->+            SyncErrorBanner(errorText = errorText)+            Spacer(Modifier.height(16.dp))+        }         if (DataType.CONTACTS in provider.capabilities) {             TypeToggle(R.string.sync_contacts, DataType.CONTACTS in state.enabledTypes) {                 actions.toggleType(state.accountName, DataType.CONTACTS, it)@@ -162,6 +181,16 @@ fun AccountDetailScreen(state: AccountDetailUiState, actions: AccountDetailActio             onClick = { actions.removeAccount(state.accountName) },             modifier = Modifier.fillMaxWidth(),         ) { Text(stringResource(R.string.remove_account)) }++        if (state.snapshots.isNotEmpty() || state.vaults.isNotEmpty()) {+            Spacer(Modifier.height(16.dp))+            SnapshotSection(+                snapshots = state.snapshots,+                restoring = state.restoring,+                onRestore = { actions.restoreSnapshot(it) },+                onSnapshotNow = { actions.snapshotNow() },+            )+        }     } } 
everysync/src/main/java/com/vayunmathur/everysync/ui/SyncHealthSection.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/ui/SyncHealthSection.kt b/everysync/src/main/java/com/vayunmathur/everysync/ui/SyncHealthSection.ktnew file mode 100644index 0000000000..4c3a4d61a7--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/ui/SyncHealthSection.kt@@ -0,0 +1,122 @@+package com.vayunmathur.everysync.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.sync.SnapshotStore.SnapshotMeta+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.DateString+import com.vayunmathur.library.ui.is24Hour+import androidx.compose.ui.platform.LocalContext+import kotlin.time.Instant++/**+ * Sync-health banner: shown when the last sync aborted instead of merging.+ * The text is pre-mapped by `EverySyncViewModel.syncErrorText` (stable abort+ * codes to user-facing strings) — this composable never sees raw errors, key+ * material, or record contents.+ */+@Composable+fun SyncErrorBanner(errorText: String) {+    ListItem(+        headlineContent = { Text(errorText) },+        supportingContent = { Text(stringResource(R.string.sync_error_hint)) },+    )+}++/**+ * Daily snapshot recovery: one row per restorable day (newest first) with a+ * confirm dialog. Restore replays records through the sinks as normal merge+ * input — newer edits win by LWW where they conflict, nothing is overwritten.+ */+@Composable+fun SnapshotSection(+    snapshots: List<SnapshotMeta>,+    restoring: Boolean,+    onRestore: (SnapshotMeta) -> Unit,+    onSnapshotNow: () -> Unit,+) {+    val context = LocalContext.current+    var pending: SnapshotMeta? by remember { mutableStateOf(null) }++    SettingsSection(title = stringResource(R.string.snapshots_title)) {+        Text(stringResource(R.string.snapshots_description))+        Spacer(Modifier.height(8.dp))+        OutlinedButton(+            onClick = onSnapshotNow,+            enabled = !restoring,+            modifier = Modifier.fillMaxWidth(),+        ) { Text(stringResource(R.string.snapshot_take_now)) }+        Spacer(Modifier.height(8.dp))+        if (snapshots.isEmpty()) {+            Text(stringResource(R.string.snapshots_empty))+        }+        Column {+            snapshots.forEach { snapshot ->+                val day = DateString.dateTime(+                    Instant.fromEpochMilliseconds(snapshot.dayEpochMs),+                    is24Hour(context),+                )+                ListItem(+                    headlineContent = { Text(day) },+                    supportingContent = {+                        Text(+                            stringResource(+                                R.string.snapshot_row,+                                snapshot.dataType,+                                snapshot.recordCount,+                            ),+                        )+                    },+                    trailingContent = {+                        OutlinedButton(+                            onClick = { pending = snapshot },+                            enabled = !restoring,+                            modifier = Modifier.fillMaxWidth(0.4f),+                        ) { Text(stringResource(R.string.snapshot_restore)) }+                    },+                )+            }+        }+    }++    pending?.let { snapshot ->+        val day = DateString.dateTime(+            Instant.fromEpochMilliseconds(snapshot.dayEpochMs),+            is24Hour(context),+        )+        AlertDialog(+            onDismissRequest = { pending = null },+            title = { Text(stringResource(R.string.snapshot_restore_title)) },+            text = { Text(stringResource(R.string.snapshot_restore_confirm, day, snapshot.dataType)) },+            confirmButton = {+                TextButton(+                    onClick = {+                        pending = null+                        onRestore(snapshot)+                    },+                ) { Text(stringResource(R.string.snapshot_restore)) }+            },+            dismissButton = {+                TextButton(onClick = { pending = null }) {+                    Text(stringResource(com.vayunmathur.library.ui.R.string.cancel))+                }+            },+        )+    }+}
everysync/src/main/res/values/strings.xml
diff --git a/everysync/src/main/res/values/strings.xml b/everysync/src/main/res/values/strings.xmlindex 912ff24b85..663a8a7bfe 100644--- a/everysync/src/main/res/values/strings.xml+++ b/everysync/src/main/res/values/strings.xml@@ -78,4 +78,26 @@      <!-- AccountsScreen PermissionsChecker: Rationale text explaining why contacts/calendar permission needed -->     <string name="need_permissions">EverySync needs contacts and calendar access to sync your vaults.</string>++    <!-- SyncErrorBanner: user-facing text for stable abort codes (see VaultSyncAbort). No key material, no contents -->+    <string name="sync_error_pull_failed">Could not reach the sync server. Nothing was changed — will retry automatically.</string>+    <string name="sync_error_undecryptable">The server data could not be unlocked with this vault key. Nothing was changed — check the vault key epoch.</string>+    <string name="sync_error_local_read">Could not read local data (the app may be locked). Nothing was changed — will retry automatically.</string>+    <string name="sync_error_relay_unavailable">The sync server is unavailable. Nothing was changed — will retry automatically.</string>+    <string name="sync_error_hint">Sync paused safely: no data was deleted. It resumes on the next sync.</string>++    <!-- SnapshotSection: header + description for daily encrypted recovery snapshots -->+    <string name="snapshots_title">Recovery snapshots</string>+    <string name="snapshots_description">One encrypted snapshot per day, kept for 30 days. Restoring replays a day through sync — newer edits still win where they conflict.</string>+    <!-- SnapshotSection row: %1$s = vault type, %2$d = record count -->+    <string name="snapshot_row">%1$s · <xliff:g id="count" example="42">%2$d</xliff:g> records</string>+    <string name="snapshot_restore">Restore</string>+    <string name="snapshot_take_now">Back up now</string>+    <string name="snapshots_empty">No snapshots yet. Snapshots are taken daily and before sync is turned off.</string>+    <string name="snapshot_restore_title">Restore snapshot?</string>+    <!-- SnapshotSection restore confirm: %1$s = date, %2$s = vault type -->+    <string name="snapshot_restore_confirm">Replay <xliff:g id="date" example="Oct 13, 2026">%1$s</xliff:g> (<xliff:g id="type" example="passwords">%2$s</xliff:g>) through sync? Newer edits still win where they conflict.</string>+    <!-- ViewModel announce: %1$d = restored record count -->+    <string name="snapshot_restored">Restored <xliff:g id="count" example="42">%1$d</xliff:g> records. Reconciling with the server…</string>+    <string name="snapshot_restore_failed">Could not restore that snapshot.</string> </resources>
passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.ktindex 1698ca4045..521c76eec9 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt@@ -18,6 +18,20 @@ object EntryMapper {     const val FIELD_SYNC_ID = "_SyncId"     const val FIELD_MODIFIED = "_Modified" +    /**+     * Own-client deletion marker. When this client deletes an entry it writes+     * a tombstone entry carrying `FIELD_TOMBSTONE = TOMBSTONE_VALUE` (plus the+     * `_SyncId`) and retains it until the delete is acked, instead of dropping+     * the row from the file. Foreign clients cannot write tombstones, so a+     * baseline-present id that is merely ABSENT from the file is ambiguous+     * (format-level: no proof of deletion) and quarantines the sync rather+     * than deleting either side. Only this exact marker value deletes; any+     * other value (including a foreign client's same-named key) is treated as+     * live data and carried through.+     */+    const val FIELD_TOMBSTONE = "_Tombstone"+    const val TOMBSTONE_VALUE = "deleted"+     private const val FIELD_SIGN_COUNT = "_SignCount"     private const val FIELD_CREATED = "_Created"     private const val FIELD_LAST_USED = "_LastUsed"@@ -26,15 +40,26 @@ object EntryMapper {     /**      * Every key this mapper can emit. Keys outside this set belong to whatever client      * wrote the vault (Notes, Tags, ...) and are carried through untouched on push.+     *+     * `FIELD_TOMBSTONE` is reserved for own-client deletion markers (see+     * `KdbxSyncEngine`): only the exact `TOMBSTONE_VALUE` in an entry this+     * client manages arms the deletion path. Any other value under that key —+     * including one written by a foreign client — is stripped on push (see+     * `applyLocalWins`) and never interpreted.      */     val OWNED_KEYS = setOf(         "Title", "UserName", "Email", "Password", "Notes", "URL", "Websites", "otp", "TOTP Seed",-        FIELD_TYPE, FIELD_SYNC_ID, FIELD_MODIFIED,+        FIELD_TYPE, FIELD_SYNC_ID, FIELD_MODIFIED, FIELD_TOMBSTONE,         FIELD_SIGN_COUNT, FIELD_CREATED, FIELD_LAST_USED, FIELD_LINKED_PASSWORD,         "KPEX_PASSKEY_USERNAME", "KPEX_PASSKEY_PRIVATE_KEY_PEM", "KPEX_PASSKEY_CREDENTIAL_ID",         "KPEX_PASSKEY_USER_HANDLE", "KPEX_PASSKEY_RELYING_PARTY",     ) +    /** True when this entry is an own-client deletion marker (see FIELD_TOMBSTONE). */+    fun isTombstoneEntry(entry: Map<String, String>): Boolean =+        entry[FIELD_TOMBSTONE] == TOMBSTONE_VALUE &&+            entry[FIELD_SYNC_ID]?.isNotBlank() == true+     fun isPasskeyEntry(entry: Map<String, String>): Boolean =         entry.keys.any { it.startsWith("KPEX_PASSKEY_") } @@ -127,11 +152,11 @@ object EntryMapper {         )     } -    /** Content fingerprint ignoring identity and timestamps, so it is comparable across sides. */+    /** Content fingerprint ignoring identity, timestamps and tombstone markers, so it is comparable across sides. */     fun contentHash(fields: Map<String, String>): String {         val digest = MessageDigest.getInstance("SHA-256")         fields.entries-            .filter { it.key != FIELD_SYNC_ID && it.key != FIELD_MODIFIED }+            .filter { it.key != FIELD_SYNC_ID && it.key != FIELD_MODIFIED && it.key != FIELD_TOMBSTONE }             .sortedBy { it.key }             .forEach { digest.update("${it.key}=${it.value}\n".toByteArray(Charsets.UTF_8)) }         return digest.digest().joinToString("") { "%02x".format(it) }
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.ktindex 4f14133582..c3016db801 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt@@ -14,6 +14,7 @@ import com.vayunmathur.passwords.data.SyncSnapshot import com.vayunmathur.passwords.data.SyncSnapshotDao import com.vayunmathur.passwords.data.newSyncId import com.vayunmathur.passwords.util.KdbxNative+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.Flow import org.json.JSONArray import org.json.JSONObject@@ -33,6 +34,14 @@ sealed interface KdbxSyncResult {     data object FileMissing : KdbxSyncResult     data object WrongPassword : KdbxSyncResult     data object VerifyFailed : KdbxSyncResult+    /**+     * Ambiguous foreign absence: baseline entries are missing from the file+     * without own-client tombstones, so no side can prove deletion. Nothing+     * was changed on either side; the user must resolve it explicitly (see+     * `KdbxSyncSettings.recordQuarantine`). [count] is the number of affected+     * baseline ids, for display only — never logged with content.+     */+    data class Quarantined(val count: Int) : KdbxSyncResult     data class Error(val message: String) : KdbxSyncResult } @@ -41,6 +50,7 @@ fun KdbxSyncResult.errorCode(): String = when (this) {     KdbxSyncResult.FileMissing -> "file_missing"     KdbxSyncResult.WrongPassword -> "wrong_password"     KdbxSyncResult.VerifyFailed -> "verify_failed"+    is KdbxSyncResult.Quarantined -> "quarantined"     is KdbxSyncResult.Error -> message     else -> "" }@@ -61,9 +71,15 @@ interface KdbxCodec { /**  * Bidirectional sync between the encrypted Room database and one kdbx file.  *- * The whole merge is computed in memory. Nothing is mutated until the remote has been- * read, decrypted, merged, re-encoded and verified — so a missing, unreadable or- * wrongly-keyed file can never wipe the local vault.+ * LOSS-PREVENTION RULE: only an explicit tombstone deletes. Own-client+ * deletes are written as tombstone entries (`EntryMapper.FIELD_TOMBSTONE`)+ * and retained until acked. A baseline-present id that is merely ABSENT from+ * the file is ambiguous — a foreign client (KeePassXC) cannot write+ * tombstones, and the file may be truncated or partially written — so it+ * quarantines the whole sync (nothing changes on either side) instead of+ * deleting. The whole merge is computed in memory; nothing is mutated until+ * the remote has been read, decrypted, merged, re-encoded and verified — so a+ * missing, unreadable or wrongly-keyed file can never wipe the local vault.  */ class KdbxSyncEngine(     private val passwordDao: PasswordDao,@@ -168,7 +184,23 @@ class KdbxSyncEngine(          val now = System.currentTimeMillis()         val baseline = snapshotDao.getAll().associateBy { it.syncId }-        val (remotePasskeys, remotePasswords) = remoteEntries.partition { EntryMapper.isPasskeyEntry(it) }+        // Tombstone entries are markers, not credentials: split them out+        // before partitioning by type (a tombstone carries no passkey fields).+        val (tombstones, liveEntries) = remoteEntries.partition { EntryMapper.isTombstoneEntry(it) }+        val tombstonedIds = tombstones.mapNotNull { it[EntryMapper.FIELD_SYNC_ID] }.toSet()+        val (remotePasskeys, remotePasswords) = liveEntries.partition { EntryMapper.isPasskeyEntry(it) }++        // Ambiguous foreign absence: baseline ids missing from the file with+        // NO own-client tombstone. No side can prove deletion (a foreign+        // client cannot write tombstones; the file may be truncated), so halt+        // the whole sync with zero mutations on either side.+        val ambiguousIds = baseline.keys -+            (remotePasswords.mapNotNull { it[EntryMapper.FIELD_SYNC_ID] } ++                remotePasskeys.mapNotNull { it[EntryMapper.FIELD_SYNC_ID] } ++                tombstonedIds).toSet()+        if (ambiguousIds.isNotEmpty()) {+            return KdbxSyncResult.Quarantined(ambiguousIds.size)+        }          val passwordPlan = merge(             passwordKind,@@ -176,6 +208,7 @@ class KdbxSyncEngine(             remotePasswords,             baseline.filterValues { it.kind == SyncSnapshot.KIND_PASSWORD },             now,+            tombstonedIds,         )         val passkeyPlan = merge(             passkeyKind,@@ -183,10 +216,29 @@ class KdbxSyncEngine(             remotePasskeys,             baseline.filterValues { it.kind == SyncSnapshot.KIND_PASSKEY },             now,+            tombstonedIds,         ) +        // Fail-closed guard: the pre-merge quarantine check above must have+        // caught every ambiguous absence; if the merge still produced one+        // (logic drift), halt rather than delete.+        val quarantineIds = passwordPlan.quarantineIds + passkeyPlan.quarantineIds+        if (quarantineIds.isNotEmpty()) {+            return KdbxSyncResult.Quarantined(quarantineIds.size)+        }+         if (passwordPlan.remoteChanged || passkeyPlan.remoteChanged) {-            val merged = passwordPlan.remoteFields + passkeyPlan.remoteFields+            val tombstoneEntries = (passwordPlan.tombstoneIds + passkeyPlan.tombstoneIds).map { id ->+                mapOf(+                    EntryMapper.FIELD_SYNC_ID to id,+                    EntryMapper.FIELD_TYPE to "tombstone",+                    EntryMapper.FIELD_TOMBSTONE to EntryMapper.TOMBSTONE_VALUE,+                    EntryMapper.FIELD_MODIFIED to now.toString(),+                )+            } + (passwordPlan.retainedTombstoneIds + passkeyPlan.retainedTombstoneIds).mapNotNull { id ->+                tombstones.firstOrNull { it[EntryMapper.FIELD_SYNC_ID] == id }+            }+            val merged = passwordPlan.remoteFields + passkeyPlan.remoteFields + tombstoneEntries             val bytes = codec.write(vaultPassword, merged)                 ?: return KdbxSyncResult.Error("Failed to encode KDBX")             // A SAF single-document write truncates, so prove the payload parses first.@@ -226,11 +278,12 @@ class KdbxSyncEngine(         remoteEntries: List<Map<String, String>>,         baseline: Map<String, SyncSnapshot>,         now: Long,+        tombstonedIds: Set<String>,     ): Plan<T> {         val accumulator = MergeAccumulator<T>()         val local = indexLocal(kind, localEntities, accumulator)         val remote = indexRemote(kind, local, remoteEntries, accumulator)-        reconcileAll(kind, local, remote, baseline, now, accumulator)+        reconcileAll(kind, local, remote, baseline, now, accumulator, tombstonedIds)         return accumulator.toPlan()     } @@ -240,6 +293,12 @@ class KdbxSyncEngine(         val remoteOut = mutableListOf<Map<String, String>>()         val snapshots = mutableListOf<SyncSnapshot>()         val removed = mutableListOf<String>()+        /** Own-client tombstone ids to write into the file (local deleted, propagating). */+        val tombstones = mutableListOf<String>()+        /** Own tombstone ids already in the file to retain (delete still propagating). */+        val retainedTombstones = mutableListOf<String>()+        /** Fail-closed guard: baselined ids with neither live nor tombstoned entry. */+        val quarantineIds = mutableListOf<String>()         val freshlyIdentified = mutableSetOf<String>()         var remoteChanged = false         var pushed = 0@@ -258,6 +317,9 @@ class KdbxSyncEngine(             pulled = pulled,             deletedLocal = deletedLocal,             deletedRemote = deletedRemote,+            tombstoneIds = tombstones,+            retainedTombstoneIds = retainedTombstones,+            quarantineIds = quarantineIds,         )     } @@ -335,9 +397,10 @@ class KdbxSyncEngine(         baseline: Map<String, SyncSnapshot>,         now: Long,         accumulator: MergeAccumulator<T>,+        tombstonedIds: Set<String>,     ) {         for (id in local.keys + remote.keys) {-            reconcileOne(kind, id, local[id], remote[id], baseline[id], now, accumulator)+            reconcileOne(kind, id, local[id], remote[id], baseline[id], now, accumulator, tombstonedIds)         }     } @@ -349,16 +412,17 @@ class KdbxSyncEngine(         base: SyncSnapshot?,         now: Long,         accumulator: MergeAccumulator<T>,+        tombstonedIds: Set<String>,     ) {         if (localEntity != null && remoteEntry != null) {-            reconcilePresent(kind, id, localEntity, remoteEntry, base, now, accumulator)+            reconcilePresent(kind, id, localEntity, remoteEntry, base, now, accumulator, tombstonedIds)             return         }         if (localEntity != null) {-            reconcileLocalOnly(kind, id, localEntity, base, now, accumulator)+            reconcileLocalOnly(kind, id, localEntity, base, now, accumulator, tombstonedIds)             return         }-        reconcileRemoteOnly(kind, id, remoteEntry!!, base, now, accumulator)+        reconcileRemoteOnly(kind, id, remoteEntry!!, base, now, accumulator, tombstonedIds)     }      private fun <T> reconcilePresent(@@ -369,7 +433,19 @@ class KdbxSyncEngine(         base: SyncSnapshot?,         now: Long,         accumulator: MergeAccumulator<T>,+        tombstonedIds: Set<String>,     ) {+        if (id in tombstonedIds) {+            // Our own tombstone met the local row (e.g. recreated after delete+            // while the tombstone still propagates): the delete wins — drop+            // the local row, retain the tombstone until the delete settles.+            accumulator.localDeletes += localEntity+            accumulator.removed += id+            accumulator.retainedTombstones += id+            accumulator.remoteChanged = true+            accumulator.deletedLocal+++            return+        }         val localFields = kind.fields(localEntity)         val remoteEntity = kind.entity(remoteEntry)         val remoteFields = kind.fields(remoteEntity)@@ -428,6 +504,8 @@ class KdbxSyncEngine(         accumulator: MergeAccumulator<T>,     ) {         // Keep fields no client of ours understands (Notes, Tags, ...).+        // The tombstone marker is ours to manage: strip any foreign value so a+        // same-named foreign key can never arm the deletion path.         accumulator.remoteOut += remoteEntry.filterKeys { it !in EntryMapper.OWNED_KEYS } + localFields         accumulator.remoteChanged = true         accumulator.pushed++@@ -462,11 +540,16 @@ class KdbxSyncEngine(         base: SyncSnapshot?,         now: Long,         accumulator: MergeAccumulator<T>,+        tombstonedIds: Set<String>,     ) {         if (base != null) {+            // Own-client deleted locally: write a tombstone entry (retained+            // until acked) instead of dropping the row from the file.+            accumulator.tombstones += id+            accumulator.remoteChanged = true+            accumulator.deletedRemote++             accumulator.localDeletes += localEntity             accumulator.removed += id-            accumulator.deletedLocal++             return         }         val localFields = kind.fields(localEntity)@@ -491,13 +574,23 @@ class KdbxSyncEngine(         base: SyncSnapshot?,         now: Long,         accumulator: MergeAccumulator<T>,+        tombstonedIds: Set<String>,     ) {-        if (base != null) {+        if (id in tombstonedIds) {+            // Our own tombstone for an already-locally-deleted id: retain it+            // (the delete is still propagating) and drop the baseline.+            accumulator.retainedTombstones += id             accumulator.removed += id-            accumulator.deletedRemote++             accumulator.remoteChanged = true             return         }+        if (base != null) {+            // Unreachable: ambiguous foreign absences quarantine in sync()+            // before merge() runs, so a baselined id always has a live or+            // tombstoned remote entry. Retained as a hard fail-closed guard.+            accumulator.quarantineIds += id+            return+        }         val remoteEntity = kind.entity(remoteEntry)         accumulator.localUpserts += kind.rebind(remoteEntity, 0, id)         accumulator.remoteOut += remoteEntry@@ -540,6 +633,9 @@ private class Plan<T>(     val pulled: Int,

Diff truncated.