everysync: desktop EDS/Windows system sinks + log-fold fix
- Commit
a7fcd4ecc3c0762497142661c6f451edb7eeb6c7- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-18 04:29 UTC (1 month ago)
- Parents
b26d86e
Diff
desktop/notes/build.gradle.kts
diff --git a/desktop/notes/build.gradle.kts b/desktop/notes/build.gradle.ktsindex 61cc93532c..74cc635fe3 100644--- a/desktop/notes/build.gradle.kts+++ b/desktop/notes/build.gradle.kts@@ -6,6 +6,9 @@ plugins { dependencies { implementation(project(":library:everysync-core")) implementation(libs.kotlinx.coroutines.core)+ // EDS native bridge stub (EdsBridge JNA shapes for libecal/libebook);+ // inactive until a Linux lib links (see EdsBridge.isAvailable).+ implementation(libs.jna) } application {
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.ktindex 97d16b1879..b96cda50cb 100644--- a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt@@ -110,7 +110,16 @@ class NoteSync( ): Boolean { val pulled = transport.pullRecords(channel, key, 0) ?: return false if (pulled.fullyUndecryptable) return false- val remote = pulled.items.mapNotNull { store.parseRemote(it) }+ // Fold to FULL state: last envelope per sync id wins (append-only+ // log). Without this, a superseded envelope (e.g. a live row followed+ // by its tombstone) reaches the merge as a duplicate id and the+ // tombstone is adopted under a fresh id instead of reconciling.+ val folded = LinkedHashMap<String, String>()+ for (raw in pulled.items) {+ val entity = store.parseRemote(raw) ?: continue+ folded[kind.syncId(entity)] = raw+ }+ val remote = folded.values.mapNotNull { store.parseRemote(it) } return SyncDriver.drive( kind = kind, store = store,
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/FileStoreIo.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/FileStoreIo.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/FileStoreIo.ktnew file mode 100644index 0000000000..615640ba3c--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/FileStoreIo.kt@@ -0,0 +1,51 @@+package com.vayunmathur.desktop.notes.systemsinks++import com.vayunmathur.everysync.core.sync.RelaySnapshot+import java.io.File++/**+ * Shared file persistence for the desktop system-sink providers (Linux EDS+ * bridges + Windows read-only mirrors).+ *+ * Snapshot TSV shape is verbatim the [com.vayunmathur.desktop.notes.NoteVault]+ * / `TodoView` / `PasswordVault` format — 7 tab-separated fields+ * (`syncId, kind, contentHash, localUpdatedAt, remoteModified, lastSyncedAt,+ * deleted`) — so baselines stay comparable across shells. Row JSON stays+ * per-sink (each sink documents its own op semantics); only the snapshot+ * encoding is shared, because a drifted snapshot format would silently break+ * the merge's delete-vs-absence bookkeeping.+ */+internal object FileStoreIo {++ fun loadSnapshots(file: File): LinkedHashMap<String, RelaySnapshot> {+ val out = LinkedHashMap<String, RelaySnapshot>()+ if (!file.isFile) return out+ for (line in file.readLines()) {+ val parts = line.split("\t")+ if (parts.size != 7) continue+ out[parts[0]] = RelaySnapshot(+ syncId = parts[0],+ kind = parts[1],+ contentHash = parts[2],+ localUpdatedAt = parts[3].toLongOrNull() ?: 0L,+ remoteModified = parts[4].toLongOrNull() ?: 0L,+ lastSyncedAt = parts[5].toLongOrNull() ?: 0L,+ deleted = parts[6] == "1",+ )+ }+ return out+ }++ fun saveSnapshots(file: File, snapshots: Map<String, RelaySnapshot>) {+ file.parentFile?.mkdirs()+ file.writeText(+ snapshots.values.joinToString("\n") {+ listOf(+ it.syncId, it.kind, it.contentHash,+ it.localUpdatedAt.toString(), it.remoteModified.toString(),+ it.lastSyncedAt.toString(), if (it.deleted) "1" else "0",+ ).joinToString("\t")+ },+ )+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsBridge.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsBridge.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsBridge.ktnew file mode 100644index 0000000000..68c8e67aac--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsBridge.kt@@ -0,0 +1,148 @@+package com.vayunmathur.desktop.notes.systemsinks.linux++import com.sun.jna.Library+import com.sun.jna.Native+import com.sun.jna.Pointer+import com.sun.jna.ptr.PointerByReference++/**+ * Evolution Data Server (EDS) native bridge for the Linux system sinks.+ *+ * **STUB STATUS — file-backed stores are the active backend.** This object+ * declares the real `libecal-2.0` / `libebook-2.0` C entry points the future+ * native path will call (signatures below are the genuine EDS C signatures+ * with GObject handles as opaque [Pointer]s), plus [isAvailable] to probe+ * for a linkable lib. The CI/Windows environment cannot link EDS, so+ * [isAvailable] returns false there and every sink in this package persists+ * to its file mirror instead — with the exact EDS field mapping documented in+ * that sink's KDoc so the native swap changes storage, never semantics.+ *+ * Wiring the native path (needs a Linux device/CI run with+ * `libecal-2.0` + `libebook-2.0` + GObject introspection):+ * 1. `Native.load("ecal-2.0", LibECal::class.java)` succeeds ([isAvailable]).+ * 2. Open the collection's [Pointer] client (`e_cal_client_new` /+ * `e_book_client_new` on the account's `ESource`).+ * 3. Replace each sink's file read/write with the list/create/modify/remove+ * calls below, keeping the (uid, stamp, vault) triple and the tombstone+ * discipline identical.+ */+object EdsBridge {++ private const val LIB_ECAL = "ecal-2.0"+ private const val LIB_EBOOK = "libebook-2.0"++ @Volatile private var availability: Boolean? = null++ /**+ * True when both EDS client libs load in this process. False on+ * CI/Windows (no EDS) — sinks then use their file mirrors. Never throws:+ * a failed load is a normal "no native provider" signal, not an error.+ */+ fun isAvailable(): Boolean {+ availability?.let { return it }+ val ok = runCatching {+ Native.load(LIB_ECAL, LibECal::class.java)+ Native.load(LIB_EBOOK, LibEBook::class.java)+ true+ }.getOrDefault(false)+ availability = ok+ return ok+ }++ /**+ * STUB — JNA shape of the `libecal-2.0` calls the calendar + task-list+ * sinks will use. Real C signatures (GObject pointers opaque here):+ * - `ECalClient *e_cal_client_new(ESource *source, ECalClientSourceType source_type, GError **error)`+ * - `gboolean e_cal_client_get_object_list_sync(ECalClient *client, const gchar *sexp, GCancellable *cancellable, GSList **objects, GError **error)`+ * - `gboolean e_cal_client_create_objects_sync(ECalClient *client, const GSList *icalcomps, GCancellable *cancellable, GSList **uids, ECalOperationFlags flags, GError **error)`+ * - `gboolean e_cal_client_modify_objects_sync(ECalClient *client, const GSList *icalcomps, ECalObjModType mod, ECalOperationFlags flags, GCancellable *cancellable, GError **error)`+ * - `gboolean e_cal_client_remove_objects_sync(ECalClient *client, const GSList *ids, ECalObjModType mod, ECalOperationFlags flags, GCancellable *cancellable, GError **error)`+ *+ * `source_type` is `E_CAL_CLIENT_SOURCE_TYPE_EVENTS` (calendar) or+ * `E_CAL_CLIENT_SOURCE_TYPE_TASKS` (task list); `sexp` filters+ * (`"#t"` = all objects); components ride as `ECalComponent`/`ICalComponent`+ * pointers wrapping the same iCalendar text `core.format.ICalendar` emits.+ */+ interface LibECal : Library {+ fun e_cal_client_new(source: Pointer, sourceType: Int, error: PointerByReference): Pointer?+ fun e_cal_client_get_object_list_sync(+ client: Pointer,+ sexp: String,+ cancellable: Pointer?,+ objects: PointerByReference,+ error: PointerByReference,+ ): Boolean+ fun e_cal_client_create_objects_sync(+ client: Pointer,+ icalcomps: Pointer,+ cancellable: Pointer?,+ uids: PointerByReference,+ flags: Int,+ error: PointerByReference,+ ): Boolean+ fun e_cal_client_modify_objects_sync(+ client: Pointer,+ icalcomps: Pointer,+ mod: Int,+ flags: Int,+ cancellable: Pointer?,+ error: PointerByReference,+ ): Boolean+ fun e_cal_client_remove_objects_sync(+ client: Pointer,+ ids: Pointer,+ mod: Int,+ flags: Int,+ cancellable: Pointer?,+ error: PointerByReference,+ ): Boolean+ }++ /**+ * STUB — JNA shape of the `libebook-2.0` calls the contacts sink will use.+ * Real C signatures:+ * - `EBookClient *e_book_client_new(ESource *source, GError **error)`+ * - `gboolean e_book_client_get_contacts_sync(EBookClient *client, const gchar *sexp, GSList **contacts, GCancellable *cancellable, GError **error)`+ * - `gboolean e_book_client_add_contact_sync(EBookClient *client, EContact *contact, GCancellable *cancellable, gchar **added_uid, GError **error)`+ * - `gboolean e_book_client_modify_contact_sync(EBookClient *client, EContact *contact, GCancellable *cancellable, GError **error)`+ * - `gboolean e_book_client_remove_contact_sync(EBookClient *client, const gchar *uid, GCancellable *cancellable, GError **error)`+ *+ * Contacts ride as `EContact` pointers wrapping the same vCard text+ * `core.format.VCard` emits; `E_CONTACT_UID` is the sync identity.+ */+ interface LibEBook : Library {+ fun e_book_client_new(source: Pointer, error: PointerByReference): Pointer?+ fun e_book_client_get_contacts_sync(+ client: Pointer,+ sexp: String,+ contacts: PointerByReference,+ cancellable: Pointer?,+ error: PointerByReference,+ ): Boolean+ fun e_book_client_add_contact_sync(+ client: Pointer,+ contact: Pointer,+ cancellable: Pointer?,+ addedUid: PointerByReference,+ error: PointerByReference,+ ): Boolean+ fun e_book_client_modify_contact_sync(+ client: Pointer,+ contact: Pointer,+ cancellable: Pointer?,+ error: PointerByReference,+ ): Boolean+ fun e_book_client_remove_contact_sync(+ client: Pointer,+ uid: String,+ cancellable: Pointer?,+ error: PointerByReference,+ ): Boolean+ }++ /** `ESource` type selectors for [LibECal.e_cal_client_new]. */+ object SourceType {+ const val EVENTS = 0 // E_CAL_CLIENT_SOURCE_TYPE_EVENTS+ const val TASKS = 1 // E_CAL_CLIENT_SOURCE_TYPE_TASKS+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsCalendarSink.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsCalendarSink.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsCalendarSink.ktnew file mode 100644index 0000000000..5d8bef7810--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsCalendarSink.kt@@ -0,0 +1,205 @@+package com.vayunmathur.desktop.notes.systemsinks.linux++import com.vayunmathur.everysync.core.data.RemoteEvent+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.sinks.CalendarSystemSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.CalendarKind+import com.vayunmathur.desktop.notes.systemsinks.FileStoreIo+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Linux `CalendarSystemSink` over Evolution Data Server (`libecal`): syncs+ * the `calendar:<vaultId>` relay channel into the user's EDS calendar.+ *+ * **BACKEND: file mirror (EDS native path is a stub).** [EdsBridge.isAvailable]+ * is false wherever no `libecal-2.0` links (CI, Windows, bare containers), so+ * this sink persists the channel to `calendar-<vaultId>.json` under [dataDir]+ * with the EXACT EDS field mapping below. Swapping in the native client+ * changes storage, never semantics: the merge contract (tombstone-only delete,+ * pulled-`updatedAt` preserved verbatim, identity = UID + RECURRENCE-ID) is+ * identical on both backends.+ *+ * EDS field mapping (what the native path MUST persist per row):+ * - Sync identity: `ECalComponent` `UID` + `RECURRENCE-ID` override pair —+ * the same pair `CalendarKind.syncId` joins with `\u0000`. Masters carry no+ * RECURRENCE-ID; overridden instances carry the overridden occurrence's id.+ * - Stamp: `ECalComponent` `LAST-MODIFIED` (relay `updatedAt`, ms) —+ * preserved verbatim on relay→EDS writes; read back on EDS→merge reads.+ * - Vault tag: `X-EVERYSYNC-VAULT: <vaultId>` extended property on every+ * component this sink creates, so a shared EDS calendar holding several+ * vaults stays partitionable (mirrors Android `SYNC_DATA2`).+ * - Body: the same iCalendar text `core.format.ICalendar.serialize` emits —+ * SUMMARY/DESCRIPTION/LOCATION/DTSTART/DTEND (+ VALUE=DATE for all-day) and+ * RRULE carried verbatim; recurring masters keep duration-instead-of-end per+ * the shared serializer. `CalendarKind.canonical` strips UID/RECURRENCE-ID+ * only for hashing — storage keeps both.+ * - Query: `e_cal_client_get_object_list_sync` with sexp `"#t"` filtered to+ * components carrying this vault's `X-EVERYSYNC-VAULT`.+ *+ * Soft-delete rule (provider `DELETED`-flag semantics): delete paths NEVER+ * hard-remove a live row. `delete()` flags the mirror row (and, natively,+ * would set the EDS-side deleted mark on the component) so the tombstone+ * survives in [listLocal] until the merge proves both sides acknowledged it.+ * Only [RelayStore.deleteLocal] hard-removes, for merge-acknowledged ids only.+ * Absence without a tombstone is a missed read, never a delete (matches+ * `EntityKind.localDeletesAreAuthoritative = true` for calendar).+ */+class EdsCalendarSink(+ private val dataDir: File,+ private val vaultId: String,+) : CalendarSystemSink, RelayStore<RemoteEvent> {++ private val storeFile: File get() = File(dataDir, "calendar-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-calendar-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteEvent>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ /** True on a Linux host with a linkable `libecal-2.0` (see [EdsBridge]). */+ val nativeAvailable: Boolean get() = EdsBridge.isAvailable()++ /**+ * Full local state, tombstones included. A failed read throws+ * [LocalReadException] (never an empty list): merging a failure as empty+ * would delete every baseline-present relay record.+ */+ override suspend fun listLocal(vaultId: String): List<RemoteEvent> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /** Rows with `updatedAt` past [since], tombstones included. */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteEvent>> =+ mutex.withLock {+ loadLocked()+ rows.values.filter { it.updatedAt > since }.map {+ LocalChange(CalendarKind.syncId(it), it.updatedAt, it.deleted, it)+ }+ }++ /**+ * Idempotent upsert keyed on UID + RECURRENCE-ID ([CalendarKind.syncId]),+ * preserving the pulled `updatedAt`. `deleted = true` flags the row+ * instead of removing it.+ */+ override suspend fun upsert(vaultId: String, item: RemoteEvent) {+ if (item.uid.isBlank()) return+ mutex.withLock {+ loadLocked()+ rows[CalendarKind.syncId(item)] = item+ saveLocked()+ }+ }++ /**+ * Soft-delete: flags the row (EDS-side: component deleted mark). Pulled+ * tombstones arrive via [upsert] as `deleted = true` envelopes, never as+ * raw deletes.+ */+ override suspend fun delete(vaultId: String, syncId: String) {+ mutex.withLock {+ loadLocked()+ val existing = rows[syncId] ?: return+ rows[syncId] = CalendarKind.withUpdatedAt(+ CalendarKind.withDeleted(existing, true),+ maxOf(existing.updatedAt, System.currentTimeMillis()),+ )+ saveLocked()+ }+ }++ /** Drops every row *and* its snapshots for this vault. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface) ---++ override suspend fun listLocal(): List<RemoteEvent> = listLocal(vaultId)++ override suspend fun upsertLocal(items: List<RemoteEvent>) {+ for (item in items) upsert(vaultId, item)+ }++ /**+ * Merge-confirmed removals only: every id here is baseline-proved+ * acknowledged on both sides.+ */+ override suspend fun deleteLocal(items: List<RemoteEvent>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(CalendarKind.syncId(item))+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ snapshots.clear()+ snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (s in snapshots) this.snapshots[s.syncId] = s+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (id in syncIds) this.snapshots.remove(id)+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override fun parseRemote(json: String): RemoteEvent? =+ CalendarKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteEvent): String = CalendarKind.toJson(entity)++ // --- File mirror persistence (JSON rows; snapshots via FileStoreIo) ---++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteEvent>>(file.readText())+ rows.clear()+ for (event in decoded) {+ if (event.uid.isNotBlank()) rows[CalendarKind.syncId(event)] = event+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("EdsCalendarSink read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsContactsSink.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsContactsSink.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsContactsSink.ktnew file mode 100644index 0000000000..934dd238ae--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsContactsSink.kt@@ -0,0 +1,205 @@+package com.vayunmathur.desktop.notes.systemsinks.linux++import com.vayunmathur.everysync.core.data.RemoteContact+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.sinks.ContactsSystemSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.ContactKind+import com.vayunmathur.desktop.notes.systemsinks.FileStoreIo+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Linux `ContactsSystemSink` over Evolution Data Server (`libebook`): syncs+ * the `contacts:<vaultId>` relay channel into the user's EDS address book.+ *+ * **BACKEND: file mirror (EDS native path is a stub).** [EdsBridge.isAvailable]+ * is false wherever no `libebook-2.0` links (CI, Windows, bare containers), so+ * this sink persists the channel to `contacts-<vaultId>.json` under [dataDir]+ * with the EXACT EDS field mapping below. Swapping in the native client+ * changes storage, never semantics: the merge contract (tombstone-only delete,+ * pulled-`updatedAt` preserved verbatim, identity = relay uid) is identical on+ * both backends.+ *+ * EDS field mapping (what the native path MUST persist per row):+ * - Sync identity: `EContact` `UID` property = relay `uid` (created via+ * `e_book_client_add_contact_sync`, which returns the server uid — the sink+ * writes the relay uid in, matching Android `RawContacts.SOURCE_ID` usage).+ * - Stamp: `EContact` `REV` (revision timestamp) = relay `updatedAt` (ms) —+ * preserved verbatim on relay→EDS writes; read back on EDS→merge reads.+ * Mirrors Android `SYNC1`.+ * - Vault tag: `X-EVERYSYNC-VAULT: <vaultId>` extended vCard property on every+ * contact this sink creates (mirrors Android `SYNC2`), so a shared address+ * book holding several vaults stays partitionable.+ * - Body: the same vCard text `core.format.VCard.serialize` emits — N/FN/ORG/+ * TEL/EMAIL/ADR/BDAY/NOTE with the shared `PhoneKind`/`EmailKind`/`PostalKind`+ * ints riding `TYPE=` params (`CELL/WORK/HOME/FAX/VOICE`,+ * `WORK/HOME/INTERNET`, `WORK/HOME/OTHER`). `ContactKind.canonical` strips+ * uid/etag/href only for hashing — storage keeps the full row.+ * - Query: `e_book_client_get_contacts_sync` with sexp `"#t"` filtered to+ * contacts carrying this vault's `X-EVERYSYNC-VAULT`.+ *+ * Soft-delete rule (provider `DELETED`-flag semantics): delete paths NEVER+ * hard-remove a live row. `delete()` flags the mirror row (and, natively,+ * would set the EDS-side deleted mark) so the tombstone survives in+ * [listLocal] until the merge proves both sides acknowledged it. Only+ * [RelayStore.deleteLocal] hard-removes, for merge-acknowledged ids only.+ * Absence without a tombstone is a missed read, never a delete (matches+ * `EntityKind.localDeletesAreAuthoritative = true` for contacts).+ */+class EdsContactsSink(+ private val dataDir: File,+ private val vaultId: String,+) : ContactsSystemSink, RelayStore<RemoteContact> {++ private val storeFile: File get() = File(dataDir, "contacts-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-contact-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteContact>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ /** True on a Linux host with a linkable `libebook-2.0` (see [EdsBridge]). */+ val nativeAvailable: Boolean get() = EdsBridge.isAvailable()++ /**+ * Full local state, tombstones included. A failed read throws+ * [LocalReadException] (never an empty list): merging a failure as empty+ * would delete every baseline-present relay record.+ */+ override suspend fun listLocal(vaultId: String): List<RemoteContact> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /** Rows with `updatedAt` past [since], tombstones included. */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteContact>> =+ mutex.withLock {+ loadLocked()+ rows.values.filter { it.updatedAt > since }.map {+ LocalChange(it.uid, it.updatedAt, it.deleted, it)+ }+ }++ /**+ * Idempotent upsert keyed on the relay sync identity, preserving the+ * pulled `updatedAt`. `deleted = true` flags the row instead of removing it.+ */+ override suspend fun upsert(vaultId: String, item: RemoteContact) {+ if (item.uid.isBlank()) return+ mutex.withLock {+ loadLocked()+ rows[item.uid] = item+ saveLocked()+ }+ }++ /**+ * Soft-delete: flags the row (EDS-side: contact deleted mark). Pulled+ * tombstones arrive via [upsert] as `deleted = true` envelopes, never as+ * raw deletes.+ */+ override suspend fun delete(vaultId: String, syncId: String) {+ mutex.withLock {+ loadLocked()+ val existing = rows[syncId] ?: return+ rows[syncId] = ContactKind.withUpdatedAt(+ ContactKind.withDeleted(existing, true),+ maxOf(existing.updatedAt, System.currentTimeMillis()),+ )+ saveLocked()+ }+ }++ /** Drops every row *and* its snapshots for this vault. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface) ---++ override suspend fun listLocal(): List<RemoteContact> = listLocal(vaultId)++ override suspend fun upsertLocal(items: List<RemoteContact>) {+ for (item in items) upsert(vaultId, item)+ }++ /**+ * Merge-confirmed removals only: every id here is baseline-proved+ * acknowledged on both sides.+ */+ override suspend fun deleteLocal(items: List<RemoteContact>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(item.uid)+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ snapshots.clear()+ snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (s in snapshots) this.snapshots[s.syncId] = s+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (id in syncIds) this.snapshots.remove(id)+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override fun parseRemote(json: String): RemoteContact? =+ ContactKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteContact): String = ContactKind.toJson(entity)++ // --- File mirror persistence (JSON rows; snapshots via FileStoreIo) ---++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteContact>>(file.readText())+ rows.clear()+ for (contact in decoded) {+ if (contact.uid.isNotBlank()) rows[contact.uid] = contact+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("EdsContactsSink read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSync.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSync.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSync.ktnew file mode 100644index 0000000000..841968d1b7--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSync.kt@@ -0,0 +1,98 @@+package com.vayunmathur.desktop.notes.systemsinks.linux++import com.vayunmathur.everysync.core.network.RelayTransport+import com.vayunmathur.everysync.core.network.appendRecords+import com.vayunmathur.everysync.core.network.pullRecords+import com.vayunmathur.everysync.core.network.recordChannel+import com.vayunmathur.everysync.core.provider.SyncDriver+import com.vayunmathur.everysync.core.sync.EntityKind+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.CalendarKind+import com.vayunmathur.everysync.core.sync.adapters.ContactKind+import com.vayunmathur.everysync.core.sync.adapters.TodoKind+import java.io.File++/**+ * Drives the calendar + contacts + EDS-todos channels through the shared+ * [SyncDriver] over the shared [RelayTransport] (JVM:+ * `JvmRelayTransport`).+ *+ * Per-channel cycle (mirrors `E2eeProvider.driveMerge` and+ * `NoteSync.syncChannel`):+ * 1. Fold the FULL decrypted record log from 0 (tombstones included — full+ * state, never a delta, so absence vs deletion stays decidable).+ * 2. A failed pull (null) or a fully-undecryptable log aborts the channel+ * with zero writes — never merge a failure as empty.+ * 3. [SyncDriver.drive] merges against the sink's full local state ++ * baseline, appends `remoteOut` BEFORE persisting locally, then applies+ * the local half.+ *+ * Channels: `calendar:<vaultId>`, `contacts:<vaultId>`,+ * `todos:<vaultId>` (via [TodoKind.channel], same channel the [TodoView]+ * shell syncs — one channel, two bindings).+ *+ * Vault-key note: the caller supplies the epoch-0 vault key directly. Roster+ * / key-epoch / ownership resolution (`VaultRoster`, `VaultKeys`,+ * `OwnerTransfer`) is future work for the desktop shell — shared vaults that+ * rotated keys need that before this driver can read them.+ */+class EdsSync(+ private val transport: RelayTransport,+ private val dataDir: File,+) {+ data class ChannelResult(val ok: Boolean, val localCount: Int)+ data class SyncResult(+ val calendar: ChannelResult,+ val contacts: ChannelResult,+ val todos: ChannelResult,+ )++ suspend fun syncOnce(vaultId: String, vaultKey: ByteArray): SyncResult {+ val calendar = EdsCalendarSink(dataDir, vaultId)+ val contacts = EdsContactsSink(dataDir, vaultId)+ val todos = EdsTodoSink(dataDir, vaultId)+ val now = System.currentTimeMillis()+ val calendarOk = syncChannel(+ CalendarKind, calendar, recordChannel("calendar", vaultId), vaultKey, now,+ )+ val contactsOk = syncChannel(+ ContactKind, contacts, recordChannel("contacts", vaultId), vaultKey, now,+ )+ val todosOk = syncChannel(+ TodoKind, todos, TodoKind.channel(vaultId), vaultKey, now,+ )+ return SyncResult(+ calendar = ChannelResult(calendarOk, calendar.listLocal().size),+ contacts = ChannelResult(contactsOk, contacts.listLocal().size),+ todos = ChannelResult(todosOk, todos.listLocal().size),+ )+ }++ private suspend fun <T> syncChannel(+ kind: EntityKind<T>,+ store: RelayStore<T>,+ channel: String,+ key: ByteArray,+ now: Long,+ ): Boolean {+ val pulled = transport.pullRecords(channel, key, 0) ?: return false+ if (pulled.fullyUndecryptable) return false+ // Fold to FULL state: last envelope per sync id wins (append-only+ // log). Without this, a superseded envelope (e.g. a live row followed+ // by its tombstone) reaches the merge as a duplicate id and the+ // tombstone is adopted under a fresh id instead of reconciling.+ val folded = LinkedHashMap<String, String>()+ for (raw in pulled.items) {+ val entity = store.parseRemote(raw) ?: continue+ folded[kind.syncId(entity)] = raw+ }+ val remote = folded.values.mapNotNull { store.parseRemote(it) }+ return SyncDriver.drive(+ kind = kind,+ store = store,+ remoteEntities = remote,+ appendRemote = { items -> transport.appendRecords(channel, key, items) != null },+ now = now,+ )+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsTodoSink.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsTodoSink.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsTodoSink.ktnew file mode 100644index 0000000000..3aa2b28c31--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsTodoSink.kt@@ -0,0 +1,210 @@+package com.vayunmathur.desktop.notes.systemsinks.linux++import com.vayunmathur.everysync.core.data.RemoteTodo+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.sinks.TodoSystemSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.TodoKind+import com.vayunmathur.desktop.notes.systemsinks.FileStoreIo+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Linux `TodoSystemSink` over the EDS task list (`libecal` todos): syncs the+ * `todos:<vaultId>` relay channel into the user's EDS tasks collection.+ *+ * **BACKEND: file mirror (EDS native path is a stub); READ-WRITE.**+ * [EdsBridge.isAvailable] is false wherever no `libecal-2.0` links (CI,+ * Windows, bare containers), so this sink persists the channel to+ * `eds-todos-<vaultId>.json` under [dataDir] with the EXACT VTODO field+ * mapping below. Unlike the calendar/contacts bridges, this sink is fully+ * read-write on BOTH backends: local creates/edits/deletes flow to the relay+ * through the merge, and tombstones propagate as real rows.+ *+ * EDS VTODO field mapping (what the native path MUST persist per row, via+ * `E_CAL_CLIENT_SOURCE_TYPE_TASKS` clients):+ * - Identity: VTODO `UID` = relay `uid` (created with+ * `e_cal_client_create_objects_sync`; read back with+ * `e_cal_client_get_object_list_sync` sexp `"#t"` filtered to this vault's+ * `X-EVERYSYNC-VAULT`).+ * - Title: VTODO `SUMMARY` = [RemoteTodo.title].+ * - Body: VTODO `DESCRIPTION` = [RemoteTodo.notes] — persisted VERBATIM+ * (Phase 1 drift fix: `notes` is an envelope field AND a merge-hash input;+ * dropping or trimming it breaks LWW convergence on that field).+ * - Done: VTODO `STATUS` = `COMPLETED` iff [RemoteTodo.done] (else `NEEDS-ACTION`).+ * - Due: VTODO `DUE` (UTC `Z` form) = [RemoteTodo.dueAt], absent when null.+ * - Created: VTODO `CREATED` (UTC `Z` form) = [RemoteTodo.createdAt] —+ * persisted VERBATIM (same drift fix: `createdAt` feeds the adoption+ * content key `todo\0<title>\0<createdAt>`; dropping it re-adopts every+ * remote task as new on each cycle).+ * - Stamp: VTODO `LAST-MODIFIED` = relay `updatedAt` (ms), preserved verbatim+ * on relay→EDS writes and read back on EDS→merge reads.+ * - Vault tag: `X-EVERYSYNC-VAULT: <vaultId>` extended property (mirrors+ * Android `SYNC_DATA2`).+ * - Ordering: [RemoteTodo.position] is ordering-only (excluded from the merge+ * hash) — persisted verbatim as `X-EVERYSYNC-POSITION`, never bumping+ * `updatedAt` on a pure reorder.+ *+ * Tombstone rule (read-write soft-delete): [delete] flags the row (EDS-side:+ * component deleted mark); tombstones persist in [listLocal] until the merge+ * proves both sides acknowledged them. Only [RelayStore.deleteLocal]+ * hard-removes, for merge-acknowledged ids only. Absence without a tombstone+ * resurrects the relay copy — never deletes.+ */+class EdsTodoSink(+ private val dataDir: File,+ private val vaultId: String,+) : TodoSystemSink, RelayStore<RemoteTodo> {++ private val storeFile: File get() = File(dataDir, "eds-todos-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-eds-todo-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteTodo>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ /** True on a Linux host with a linkable `libecal-2.0` (see [EdsBridge]). */+ val nativeAvailable: Boolean get() = EdsBridge.isAvailable()++ /**+ * Full local state, tombstones included. A failed read throws+ * [LocalReadException] (never an empty list): merging a failure as empty+ * would delete every baseline-present relay record.+ */+ override suspend fun listLocal(vaultId: String): List<RemoteTodo> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /** Rows with `updatedAt` past [since], tombstones included. */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteTodo>> =+ mutex.withLock {+ loadLocked()+ rows.values.filter { it.updatedAt > since }.map {+ LocalChange(it.uid, it.updatedAt, it.deleted, it)+ }+ }++ /**+ * Idempotent upsert keyed on the relay sync identity, preserving the+ * pulled `updatedAt` and the full envelope (`notes`, `createdAt`).+ * `deleted = true` tombstones the row instead of removing it.+ */+ override suspend fun upsert(vaultId: String, item: RemoteTodo) {+ if (item.uid.isBlank()) return+ mutex.withLock {+ loadLocked()+ rows[item.uid] = item+ saveLocked()+ }+ }++ /**+ * Soft-delete: tombstones the row so the deletion propagates. Pulled+ * tombstones arrive via [upsert] as `deleted = true` envelopes, never as+ * raw deletes.+ */+ override suspend fun delete(vaultId: String, syncId: String) {+ mutex.withLock {+ loadLocked()+ val existing = rows[syncId] ?: return+ rows[syncId] = TodoKind.withUpdatedAt(+ TodoKind.withDeleted(existing, true),+ maxOf(existing.updatedAt, System.currentTimeMillis()),+ )+ saveLocked()+ }+ }++ /** Drops every row *and* its snapshots for this vault. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface) ---++ override suspend fun listLocal(): List<RemoteTodo> = listLocal(vaultId)++ override suspend fun upsertLocal(items: List<RemoteTodo>) {+ for (item in items) upsert(vaultId, item)+ }++ /**+ * Merge-confirmed removals only: every id here is baseline-proved+ * acknowledged on both sides.+ */+ override suspend fun deleteLocal(items: List<RemoteTodo>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(item.uid)+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ snapshots.clear()+ snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (s in snapshots) this.snapshots[s.syncId] = s+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (id in syncIds) this.snapshots.remove(id)+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override fun parseRemote(json: String): RemoteTodo? =+ TodoKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteTodo): String = TodoKind.toJson(entity)++ // --- File mirror persistence (JSON rows; snapshots via FileStoreIo) ---++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteTodo>>(file.readText())+ rows.clear()+ for (todo in decoded) {+ if (todo.uid.isNotBlank()) rows[todo.uid] = todo+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("EdsTodoSink read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrors.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrors.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrors.ktnew file mode 100644index 0000000000..d750adb488--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrors.kt@@ -0,0 +1,333 @@+package com.vayunmathur.desktop.notes.systemsinks.windows++import com.vayunmathur.everysync.core.data.RemoteContact+import com.vayunmathur.everysync.core.data.RemoteEvent+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.sinks.CalendarSystemSink+import com.vayunmathur.everysync.core.sinks.ContactsSystemSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.CalendarKind+import com.vayunmathur.everysync.core.sync.adapters.ContactKind+import com.vayunmathur.desktop.notes.systemsinks.FileStoreIo+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Windows v1 system bridges — READ-ONLY.+ *+ * On Windows there is no writable sync-provider surface available to this+ * JVM shell (`AppointmentStore` / `ContactStore` expose no sync-adapter+ * contract like Android's `CALLER_IS_SYNCADAPTER` + `DIRTY`/`DELETED`, so+ * relay writes could never be told apart from user edits). These bridges+ * therefore MIRROR the relay channels into local read models only:+ *+ * - `WindowsCalendarMirror : CalendarSystemSink` mirrors+ * `calendar:<vaultId>` — local queriable copy of the folded relay state.+ * - `WindowsContactsMirror : ContactsSystemSink` mirrors+ * `contacts:<vaultId>` — same discipline.+ *+ * Read-only discipline (why [upsert]/[delete]/[purge] refuse local writes+ * but still accept merge writes):+ * - The merge driver calls the SAME [RelayStore] surface for both halves of+ * the plan: `upsertLocal` (relay→local) and `deleteLocal`+ * (merge-acknowledged cleanup). Those MUST apply — they persist what the+ * relay already decided; blocking them would wedge the baseline forever.+ * - Direct [upsert]/[delete] (local-originated edits), however, are user+ * writes with no native store to land in, so they are IGNORED (no-op):+ * there is no local edit source on Windows v1, and silently accepting an+ * edit callers believe persisted would be worse than refusing it.+ * - [localChanges] always returns empty: nothing local can change, so the+ * merge never pushes from this side (`remoteOut` only ever carries+ * adoptions of unidentified relay rows, never local edits).+ * - [purge] still drops rows + snapshots: vault-scoped teardown is not an+ * edit — it is the same `deleteByVault` the merge issues on vault removal.+ *+ * A future writable Windows path (Graph-backed provider or a sync-adapter+ * equivalent) would flip [localChanges]/[upsert]/[delete] to real+ * implementations behind this same [CalendarSystemSink]/[ContactsSystemSink]+ * surface; the relay channel, tombstone semantics, and identity columns are+ * unchanged.+ *+ * Todos are NOT mirrored here: Windows renders the SAME `todos:<vaultId>`+ * channel inside the Notes UI via the existing `TodoView.todosAsNotes`+ * projection (read-write through `updateTodoFromNote`). A second todos copy+ * in this package would split the channel — so there is deliberately no+ * `WindowsTodoMirror`.+ */+class WindowsCalendarMirror(+ private val dataDir: File,+ private val vaultId: String,+) : CalendarSystemSink, RelayStore<RemoteEvent> {++ private val storeFile: File get() = File(dataDir, "win-calendar-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-win-calendar-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteEvent>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ /**+ * Mirror of the folded relay state, tombstones included. Failed reads+ * throw [LocalReadException], never an empty list.+ */+ override suspend fun listLocal(vaultId: String): List<RemoteEvent> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /**+ * Always empty (read-only v1): no local edit source exists, so the merge+ * never pushes from this side.+ */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteEvent>> =+ emptyList()++ /**+ * No-op (read-only v1): local-originated writes have no native store to+ * land in. Merge-driven relay→local writes arrive via [upsertLocal],+ * never here.+ */+ override suspend fun upsert(vaultId: String, item: RemoteEvent) = Unit++ /**+ * No-op (read-only v1): see [upsert]. Merge-acknowledged cleanup arrives+ * via [deleteLocal].+ */+ override suspend fun delete(vaultId: String, syncId: String) = Unit++ /** Vault teardown: drops every row *and* its snapshots. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface: relay→local half applies) ---++ override suspend fun listLocal(): List<RemoteEvent> = listLocal(vaultId)++ /**+ * Applies the merge's relay→local half: persists what the relay already+ * decided (pulls, resurrections, relay-won tombstones). This is a mirror+ * update, not a local edit, so it applies even on read-only v1.+ */+ override suspend fun upsertLocal(items: List<RemoteEvent>) {+ mutex.withLock {+ loadLocked()+ for (item in items) {+ if (item.uid.isBlank()) continue+ rows[CalendarKind.syncId(item)] = item+ }+ saveLocked()+ }+ }++ /**+ * Merge-confirmed removals only: every id here is baseline-proved+ * acknowledged on both sides.+ */+ override suspend fun deleteLocal(items: List<RemoteEvent>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(CalendarKind.syncId(item))+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ snapshots.clear()+ snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (s in snapshots) this.snapshots[s.syncId] = s+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (id in syncIds) this.snapshots.remove(id)+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override fun parseRemote(json: String): RemoteEvent? =+ CalendarKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteEvent): String = CalendarKind.toJson(entity)++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteEvent>>(file.readText())+ rows.clear()+ for (event in decoded) {+ if (event.uid.isNotBlank()) rows[CalendarKind.syncId(event)] = event+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("WindowsCalendarMirror read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }+}++/**+ * Windows v1 contacts mirror — READ-ONLY. Same discipline as+ * [WindowsCalendarMirror]: [localChanges] is always empty, direct+ * [upsert]/[delete] are no-ops, while the merge's relay→local half+ * ([upsertLocal]/[deleteLocal]) and vault teardown ([purge]) apply.+ */+class WindowsContactsMirror(+ private val dataDir: File,+ private val vaultId: String,+) : ContactsSystemSink, RelayStore<RemoteContact> {++ private val storeFile: File get() = File(dataDir, "win-contacts-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-win-contact-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteContact>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ /**+ * Mirror of the folded relay state, tombstones included. Failed reads+ * throw [LocalReadException], never an empty list.+ */+ override suspend fun listLocal(vaultId: String): List<RemoteContact> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /** Always empty (read-only v1): no local edit source exists. */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteContact>> =+ emptyList()++ /** No-op (read-only v1): see [WindowsCalendarMirror.upsert]. */+ override suspend fun upsert(vaultId: String, item: RemoteContact) = Unit++ /** No-op (read-only v1): see [WindowsCalendarMirror.delete]. */+ override suspend fun delete(vaultId: String, syncId: String) = Unit++ /** Vault teardown: drops every row *and* its snapshots. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface: relay→local half applies) ---++ override suspend fun listLocal(): List<RemoteContact> = listLocal(vaultId)++ /**+ * Applies the merge's relay→local half (mirror update, not a local edit —+ * applies even on read-only v1).+ */+ override suspend fun upsertLocal(items: List<RemoteContact>) {+ mutex.withLock {+ loadLocked()+ for (item in items) {+ if (item.uid.isBlank()) continue+ rows[item.uid] = item+ }+ saveLocked()+ }+ }++ /**+ * Merge-confirmed removals only: every id here is baseline-proved+ * acknowledged on both sides.+ */+ override suspend fun deleteLocal(items: List<RemoteContact>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(item.uid)+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ snapshots.clear()+ snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (s in snapshots) this.snapshots[s.syncId] = s+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ this.snapshots.clear()+ this.snapshots.putAll(FileStoreIo.loadSnapshots(snapshotFile))+ for (id in syncIds) this.snapshots.remove(id)+ FileStoreIo.saveSnapshots(snapshotFile, this.snapshots)+ }+ }++ override fun parseRemote(json: String): RemoteContact? =+ ContactKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteContact): String = ContactKind.toJson(entity)++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteContact>>(file.readText())+ rows.clear()+ for (contact in decoded) {+ if (contact.uid.isNotBlank()) rows[contact.uid] = contact+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("WindowsContactsMirror read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsSync.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsSync.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsSync.ktnew file mode 100644index 0000000000..b5a790cf7d--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsSync.kt@@ -0,0 +1,86 @@+package com.vayunmathur.desktop.notes.systemsinks.windows++import com.vayunmathur.everysync.core.network.RelayTransport+import com.vayunmathur.everysync.core.network.appendRecords+import com.vayunmathur.everysync.core.network.pullRecords+import com.vayunmathur.everysync.core.network.recordChannel+import com.vayunmathur.everysync.core.provider.SyncDriver+import com.vayunmathur.everysync.core.sync.EntityKind+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.CalendarKind+import com.vayunmathur.everysync.core.sync.adapters.ContactKind+import java.io.File++/**+ * Drives the Windows v1 read-only mirrors through the shared [SyncDriver].+ *+ * The mirrors' `localChanges` is always empty (read-only v1: no local edit+ * source), so the merge's local half is trivially "nothing to push" — the+ * cycle still pulls the FULL folded log and applies the relay→local half+ * (`upsertLocal`/`deleteLocal`), keeping the mirror and its baseline current.+ * `remoteOut` on this path only ever carries re-appended adoptions of+ * unidentified relay rows, never local edits; `appendRemote` still runs+ * BEFORE the local persist per the driver contract.+ *+ * Channels: `calendar:<vaultId>`, `contacts:<vaultId>`. Todos are NOT driven+ * here — Windows renders the SAME `todos:<vaultId>` channel inside the Notes+ * UI via the existing `TodoView` path (read-write through+ * `updateTodoFromNote`).+ *+ * Invariants (same as every driver): a failed pull (null) or a+ * fully-undecryptable log aborts the channel with zero writes — never merge+ * a failure as empty.+ */+class WindowsSync(+ private val transport: RelayTransport,+ private val dataDir: File,+) {+ data class ChannelResult(val ok: Boolean, val localCount: Int)+ data class SyncResult(+ val calendar: ChannelResult,+ val contacts: ChannelResult,+ )++ suspend fun syncOnce(vaultId: String, vaultKey: ByteArray): SyncResult {+ val calendar = WindowsCalendarMirror(dataDir, vaultId)+ val contacts = WindowsContactsMirror(dataDir, vaultId)+ val now = System.currentTimeMillis()+ val calendarOk = syncChannel(+ CalendarKind, calendar, recordChannel("calendar", vaultId), vaultKey, now,+ )+ val contactsOk = syncChannel(+ ContactKind, contacts, recordChannel("contacts", vaultId), vaultKey, now,+ )+ return SyncResult(+ calendar = ChannelResult(calendarOk, calendar.listLocal().size),+ contacts = ChannelResult(contactsOk, contacts.listLocal().size),+ )+ }++ private suspend fun <T> syncChannel(+ kind: EntityKind<T>,+ store: RelayStore<T>,+ channel: String,+ key: ByteArray,+ now: Long,+ ): Boolean {+ val pulled = transport.pullRecords(channel, key, 0) ?: return false+ if (pulled.fullyUndecryptable) return false+ // Fold to FULL state: last envelope per sync id wins (append-only+ // log) — see EdsSync.syncChannel for why the raw log must not reach+ // the merge unfolded.+ val folded = LinkedHashMap<String, String>()+ for (raw in pulled.items) {+ val entity = store.parseRemote(raw) ?: continue+ folded[kind.syncId(entity)] = raw+ }+ val remote = folded.values.mapNotNull { store.parseRemote(it) }+ return SyncDriver.drive(+ kind = kind,+ store = store,+ remoteEntities = remote,+ appendRemote = { items -> transport.appendRecords(channel, key, items) != null },+ now = now,+ )+ }+}
desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/FakeRelayTransport.kt
diff --git a/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/FakeRelayTransport.kt b/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/FakeRelayTransport.ktnew file mode 100644index 0000000000..e2af3676c4--- /dev/null+++ b/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/FakeRelayTransport.kt@@ -0,0 +1,69 @@+package com.vayunmathur.desktop.notes.systemsinks++import com.vayunmathur.everysync.core.crypto.AesGcm+import com.vayunmathur.everysync.core.network.RelayTransport+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.emptyFlow+import kotlin.io.encoding.Base64++/**+ * In-memory [RelayTransport] for system-sink tests: no network, no PQC.+ * Channel logs hold ENCRYPTED envelopes (`Base64(AES_GCM(key, utf8))`, same+ * shape as the real `appendRecords`/`pullRecords` helpers), so tests exercise+ * the real envelope path through the shared helpers.+ *+ * Failure injection: set [failPullChannels] to make [pullRaw] return null for+ * a channel (transport failure → the driver must abort with zero writes, per+ * the null-pull invariant).+ */+class FakeRelayTransport : RelayTransport {+ val logs = LinkedHashMap<String, MutableList<String>>()+ val appended = LinkedHashMap<String, MutableList<String>>()+ var failPullChannels: Set<String> = emptySet()++ override val deviceId: String = "test-device"+ override val publicBundle: ByteArray = "fake-bundle".encodeToByteArray()++ override suspend fun register(): Boolean = true+ override suspend fun getKey(id: String): ByteArray? = null++ override suspend fun appendRaw(channel: String, items: List<String>): Int? {+ val log = logs.getOrPut(channel) { mutableListOf() }+ log += items+ appended.getOrPut(channel) { mutableListOf() } += items+ return log.size+ }++ override suspend fun pullRaw(channel: String, since: Int): List<String>? {+ if (channel in failPullChannels) return null+ val log = logs[channel] ?: return emptyList()+ if (since < 0 || since > log.size) return null+ return log.drop(since)+ }++ override fun subscribe(channel: String): Flow<String> = emptyFlow()++ override suspend fun sign(data: ByteArray): ByteArray = data+ override suspend fun verify(publicBundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean = true+ override suspend fun seal(bundle: ByteArray, data: ByteArray): ByteArray = data+ override suspend fun unseal(data: ByteArray): ByteArray = data+ override fun newVaultKey(): ByteArray = ByteArray(32)+ override fun newVaultId(): String = "vault-test"++ /**+ * Seeds [channel] with plaintext envelopes encrypted under [key] (what+ * `appendRecords` would have written).+ */+ fun seed(channel: String, key: ByteArray, plaintexts: List<String>) {+ val log = logs.getOrPut(channel) { mutableListOf() }+ for (plain in plaintexts) {+ log += Base64.encode(AesGcm.encrypt(key, plain.encodeToByteArray()))+ }+ }++ /** Decrypts every envelope appended to [channel] during the test. */+ fun appendedPlaintexts(channel: String, key: ByteArray): List<String> =+ (appended[channel] ?: emptyList()).mapNotNull { blob ->+ runCatching { AesGcm.decrypt(key, Base64.decode(blob)).decodeToString() }.getOrNull()+ }+}
desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSinkTest.kt
diff --git a/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSinkTest.kt b/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSinkTest.ktnew file mode 100644index 0000000000..e7d42864f4--- /dev/null+++ b/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/linux/EdsSinkTest.kt@@ -0,0 +1,181 @@+package com.vayunmathur.desktop.notes.systemsinks.linux++import com.vayunmathur.desktop.notes.systemsinks.FakeRelayTransport+import com.vayunmathur.everysync.core.data.RemoteTodo+import com.vayunmathur.everysync.core.network.recordChannel+import com.vayunmathur.everysync.core.sync.adapters.TodoKind+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++/**+ * Linux EDS sink tests against the file-mirror backend (no `libecal` on CI:+ * [EdsBridge.isAvailable] is false here, so every assertion runs against the+ * file mirror — the same merge contract the native swap preserves).+ *+ * Covers: full EDS-todos round-trip (`notes` + `createdAt` survive, tombstones+ * propagate as real rows), [EdsTodoSink] local edit → relay push, calendar /+ * contacts mirror pull + tombstone persistence, and the null-pull abort+ * (failed pull writes nothing, returns `ok=false`).+ *+ * A Linux device/CI run with `libecal-2.0` additionally needs: native-client+ * open + list/create/modify against a scratch EDS collection asserting the+ * VTODO/VCALENDAR field map in each sink's KDoc.+ */+class EdsSinkTest {++ private val vaultKey = ByteArray(32) { (it + 1).toByte() }++ @Test+ fun `eds todos round-trip preserves notes and createdAt`() = runBlocking {+ val dir = tempDir()+ val sink = EdsTodoSink(dir, "v1")+ val todo = RemoteTodo(+ uid = "t1", title = "Buy milk", notes = "oat, not dairy",+ done = false, dueAt = 1_700_000_000_000L, position = 1.0,+ createdAt = 1_699_000_000_000L, updatedAt = 1_700_000_000_001L,+ )+ sink.upsert("v1", todo)+ val read = sink.listLocal("v1").single()+ assertEquals("oat, not dairy", read.notes)+ assertEquals(1_699_000_000_000L, read.createdAt)+ assertEquals(1_700_000_000_000L, read.dueAt)+ assertTrue(sink.listLocalOk)+ }++ @Test+ fun `eds todos soft-delete keeps tombstone and localChanges reports it`() = runBlocking {+ val dir = tempDir()+ val sink = EdsTodoSink(dir, "v1")+ sink.upsert("v1", RemoteTodo(uid = "t1", title = "A", updatedAt = 100L))+ sink.delete("v1", "t1")+ val rows = sink.listLocal("v1")+ assertEquals(1, rows.size)+ assertTrue(rows.single().deleted)+ val changes = sink.localChanges("v1", since = 0L)+ assertEquals(1, changes.size)+ assertTrue(changes.single().deleted)+ }++ @Test+ fun `eds sync pulls remote todos and pushes local edits`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = TodoKind.channel("v1")+ val remoteTodo = RemoteTodo(+ uid = "r1", title = "Remote", notes = "from relay",+ createdAt = 500L, updatedAt = 1_000L,+ )+ transport.seed(channel, vaultKey, listOf(TodoKind.toJson(remoteTodo)))++ val local = EdsTodoSink(dir, "v1")+ local.upsert("v1", RemoteTodo(uid = "l1", title = "Local", notes = "mine", createdAt = 10L, updatedAt = 20L))++ val result = EdsSync(transport, dir).syncOnce("v1", vaultKey)+ assertTrue(result.todos.ok)++ val todos = EdsTodoSink(dir, "v1").listLocal("v1")+ assertEquals(setOf("r1", "l1"), todos.map { it.uid }.toSet())+ // The local row was pushed to the relay (remoteOut BEFORE local persist).+ val pushed = transport.appendedPlaintexts(channel, vaultKey)+ .mapNotNull { TodoKind.fromJson(it) }+ assertTrue(pushed.any { it.uid == "l1" })+ // Pulled row kept its envelope fields verbatim.+ assertEquals("from relay", todos.single { it.uid == "r1" }.notes)+ }++ @Test+ fun `eds sync propagates a pulled tombstone into the mirror`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = TodoKind.channel("v1")+ val live = RemoteTodo(uid = "t9", title = "Gone", updatedAt = 100L)+ transport.seed(channel, vaultKey, listOf(TodoKind.toJson(live)))+ assertTrue(EdsSync(transport, dir).syncOnce("v1", vaultKey).todos.ok)+ assertFalse(EdsTodoSink(dir, "v1").listLocal("v1").single().deleted)++ val tombstone = live.copy(deleted = true, updatedAt = 200L)+ transport.seed(channel, vaultKey, listOf(TodoKind.toJson(tombstone)))+ assertTrue(EdsSync(transport, dir).syncOnce("v1", vaultKey).todos.ok)++ val rows = EdsTodoSink(dir, "v1").listLocal("v1")+ assertEquals(1, rows.size)+ assertTrue(rows.single().deleted)+ }++ @Test+ fun `null pull aborts with zero local writes`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = TodoKind.channel("v1")+ transport.failPullChannels = setOf(channel)+ transport.seed(channel, vaultKey, listOf(TodoKind.toJson(RemoteTodo(uid = "x", updatedAt = 1L))))++ val result = EdsSync(transport, dir).syncOnce("v1", vaultKey)+ assertFalse(result.todos.ok)+ // Aborted cycle: seed was unreachable (failed pull), mirror untouched.+ assertTrue(EdsTodoSink(dir, "v1").listLocal("v1").isEmpty())+ }++ @Test+ fun `eds calendar mirror pulls events keyed by uid plus recurrence-id`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = recordChannel("calendar", "v1")+ val master = com.vayunmathur.everysync.core.data.RemoteEvent(+ uid = "e1", calendarId = "cal", summary = "Standup",+ startMillis = 1_700_000_000_000L, endMillis = 1_700_000_030_000L,+ updatedAt = 100L,+ )+ val instance = master.copy(+ recurrenceId = "20240101T090000Z", summary = "Standup (moved)", updatedAt = 200L,+ )+ transport.seed(+ channel, vaultKey,+ listOf(+ com.vayunmathur.everysync.core.sync.adapters.CalendarKind.toJson(master),+ com.vayunmathur.everysync.core.sync.adapters.CalendarKind.toJson(instance),+ ),+ )++ val result = EdsSync(transport, dir).syncOnce("v1", vaultKey)+ assertTrue(result.calendar.ok)+ val rows = EdsCalendarSink(dir, "v1").listLocal("v1")+ assertEquals(2, rows.size)+ assertEquals(+ setOf("e1", "e1\u000020240101T090000Z"),+ rows.map { com.vayunmathur.everysync.core.sync.adapters.CalendarKind.syncId(it) }.toSet(),+ )+ }++ @Test+ fun `eds contacts mirror pulls vcard rows and tombstones survive`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = recordChannel("contacts", "v1")+ val contact = com.vayunmathur.everysync.core.data.RemoteContact(+ uid = "c1", displayName = "Ada", firstName = "Ada",+ phones = listOf(+ com.vayunmathur.everysync.core.data.TypedValue("+1555", 2),+ ),+ updatedAt = 100L,+ )+ transport.seed(+ channel, vaultKey,+ listOf(com.vayunmathur.everysync.core.sync.adapters.ContactKind.toJson(contact)),+ )+ assertTrue(EdsSync(transport, dir).syncOnce("v1", vaultKey).contacts.ok)+ assertEquals("Ada", EdsContactsSink(dir, "v1").listLocal("v1").single().displayName)++ EdsContactsSink(dir, "v1").delete("v1", "c1")+ val rows = EdsContactsSink(dir, "v1").listLocal("v1")+ assertEquals(1, rows.size)+ assertTrue(rows.single().deleted)+ }++ private fun tempDir(): File =+ File(System.getProperty("java.io.tmpdir"), "eds-test-${System.nanoTime()}").apply { mkdirs() }+}
desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrorTest.kt
diff --git a/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrorTest.kt b/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrorTest.ktnew file mode 100644index 0000000000..044ef6fe94--- /dev/null+++ b/desktop/notes/src/test/kotlin/com/vayunmathur/desktop/notes/systemsinks/windows/WindowsMirrorTest.kt@@ -0,0 +1,111 @@+package com.vayunmathur.desktop.notes.systemsinks.windows++import com.vayunmathur.desktop.notes.TodoView+import com.vayunmathur.desktop.notes.systemsinks.FakeRelayTransport+import com.vayunmathur.everysync.core.data.RemoteContact+import com.vayunmathur.everysync.core.data.RemoteEvent+import com.vayunmathur.everysync.core.data.RemoteNote+import com.vayunmathur.everysync.core.data.RemoteTodo+import com.vayunmathur.everysync.core.network.recordChannel+import com.vayunmathur.everysync.core.sync.adapters.CalendarKind+import com.vayunmathur.everysync.core.sync.adapters.ContactKind+import com.vayunmathur.everysync.core.sync.adapters.TodoKind+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++/**+ * Windows v1 tests: read-only mirrors pull relay state, refuse local edits,+ * and the SAME `todos:<vaultId>` channel renders in the Notes UI through the+ * existing `TodoView.todosAsNotes` projection (no second todos copy).+ */+class WindowsMirrorTest {++ private val vaultKey = ByteArray(32) { (it + 7).toByte() }++ @Test+ fun `calendar mirror pulls relay state but ignores local upserts`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = recordChannel("calendar", "v1")+ val event = RemoteEvent(+ uid = "e1", calendarId = "cal", summary = "Demo",+ startMillis = 1_700_000_000_000L, endMillis = 1_700_000_060_000L,+ updatedAt = 100L,+ )+ transport.seed(channel, vaultKey, listOf(CalendarKind.toJson(event)))++ val result = WindowsSync(transport, dir).syncOnce("v1", vaultKey)+ assertTrue(result.calendar.ok)+ assertEquals("Demo", WindowsCalendarMirror(dir, "v1").listLocal("v1").single().summary)++ // Local-originated writes are refused on read-only v1.+ WindowsCalendarMirror(dir, "v1").upsert(+ "v1",+ event.copy(summary = "Hacked", updatedAt = 999L),+ )+ WindowsCalendarMirror(dir, "v1").delete("v1", "e1")+ assertEquals("Demo", WindowsCalendarMirror(dir, "v1").listLocal("v1").single().summary)+ // …and nothing local is ever reported, so the merge never pushes.+ assertTrue(WindowsCalendarMirror(dir, "v1").localChanges("v1", 0L).isEmpty())+ assertTrue(transport.appendedPlaintexts(channel, vaultKey).isEmpty())+ }++ @Test+ fun `contacts mirror pulls relay state but ignores local deletes`() = runBlocking {+ val dir = tempDir()+ val transport = FakeRelayTransport()+ val channel = recordChannel("contacts", "v1")+ val contact = RemoteContact(uid = "c1", displayName = "Grace", updatedAt = 50L)+ transport.seed(channel, vaultKey, listOf(ContactKind.toJson(contact)))++ val result = WindowsSync(transport, dir).syncOnce("v1", vaultKey)+ assertTrue(result.contacts.ok)+ assertEquals("Grace", WindowsContactsMirror(dir, "v1").listLocal("v1").single().displayName)++ WindowsContactsMirror(dir, "v1").delete("v1", "c1")+ assertEquals(1, WindowsContactsMirror(dir, "v1").listLocal("v1").size)+ assertTrue(WindowsContactsMirror(dir, "v1").localChanges("v1", 0L).isEmpty())+ }++ @Test+ fun `windows todos render in Notes UI through the same channel projection`() = runBlocking {+ val dir = tempDir()+ // Same TodoView store the Notes shell syncs: write a todo, project it.+ val todos = TodoView(dir, "v1")+ todos.upsert(+ "v1",+ RemoteTodo(+ uid = "t1", title = "File taxes", notes = "before April",+ done = false, createdAt = 42L, updatedAt = 100L,+ ),+ )+ val projected = todos.todosAsNotes()+ assertEquals(1, projected.size)+ val note: RemoteNote = projected.single()+ assertEquals("todo:t1", note.uid)+ assertEquals("File taxes", note.title)+ assertTrue(note.content.contains("before April"))++ // A projection edit writes back onto the SAME todos-channel row.+ todos.updateTodoFromNote(note.copy(title = "File taxes NOW"))+ assertEquals("File taxes NOW", todos.listLocal("v1").single().title)+ assertEquals("before April", todos.listLocal("v1").single().notes)++ // Tombstoned todos project to nothing (their tombstone stays on-channel).+ todos.delete("v1", "t1")+ assertTrue(todos.todosAsNotes().isEmpty())+ assertTrue(todos.listLocal("v1").single().deleted)++ // The projection round-trips through the real envelope codec.+ val envelope = TodoKind.toJson(todos.listLocal("v1").single())+ assertEquals("t1", TodoKind.fromJson(envelope)?.uid)+ // …and the channel name is the shared todos channel (no second copy).+ assertEquals("todos:v1", TodoKind.channel("v1"))+ }++ private fun tempDir(): File =+ File(System.getProperty("java.io.tmpdir"), "win-test-${System.nanoTime()}").apply { mkdirs() }+}
desktop/passwords/src/test/kotlin/com/vayunmathur/desktop/passwords/KdbxRoundTripTest.kt
diff --git a/desktop/passwords/src/test/kotlin/com/vayunmathur/desktop/passwords/KdbxRoundTripTest.kt b/desktop/passwords/src/test/kotlin/com/vayunmathur/desktop/passwords/KdbxRoundTripTest.ktnew file mode 100644index 0000000000..ab31435b29--- /dev/null+++ b/desktop/passwords/src/test/kotlin/com/vayunmathur/desktop/passwords/KdbxRoundTripTest.kt@@ -0,0 +1,151 @@+package com.vayunmathur.desktop.passwords++import com.vayunmathur.everysync.core.data.RemotePassword+import com.vayunmathur.everysync.core.passwords.EntryMapper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * KDBX interchange round-trip over the VERBATIM shared [EntryMapper] field+ * map: every key name asserted here is the shared constant (not a copy), so+ * renaming a key in either layer breaks this test instead of silently+ * forking the merge hashes across sides.+ *+ * Covers: password-half round-trip (incl. multi-website + TOTP seed),+ * passkey-half round-trip (incl. linked-password id), tombstone import+ * (deletion marker deletes the vault row; non-marker `_Tombstone` values are+ * live data), and sync-id/modified identity markers.+ */+class KdbxRoundTripTest {++ @Test+ fun `password round-trips through verbatim EntryMapper keys`() {+ val entry = RemotePassword(+ uid = "pw1",+ name = "Bank",+ username = "ada",+ email = "[email protected]",+ password = "s3cret",+ note = "vault note",+ totpSecret = "JBSWY3DPEHPK3PXP",+ websites = listOf("https://bank.example", "https://bank.example/mobile"),+ updatedAt = 1_700_000_000_000L,+ )+ val fields = KdbxCompat.toFields(entry)++ // Verbatim key assertions: these ARE the shared constants.+ assertEquals(entry.uid, fields[EntryMapper.FIELD_SYNC_ID])+ assertEquals(entry.updatedAt.toString(), fields[EntryMapper.FIELD_MODIFIED])+ assertEquals("password", fields[EntryMapper.FIELD_TYPE])+ assertEquals("Bank", fields["Title"])+ assertEquals("ada", fields["UserName"])+ assertEquals("[email protected]", fields["Email"])+ assertEquals("s3cret", fields["Password"])+ assertEquals("vault note", fields["Notes"])+ assertEquals("https://bank.example", fields["URL"])+ // Verbatim EntryMapper shape: Websites carries ALL sites joined+ // (first included — URL doubles as the primary).+ assertEquals("https://bank.example\nhttps://bank.example/mobile", fields["Websites"])+ assertEquals("otpauth://totp/?secret=JBSWY3DPEHPK3PXP", fields["otp"])+ // Only owned keys are written.+ assertTrue(fields.keys.all { it in EntryMapper.OWNED_KEYS })++ val back = KdbxCompat.fromFields(fields, now = 0L)!!+ assertEquals(entry.uid, back.uid)+ assertEquals(entry.name, back.name)+ assertEquals(entry.username, back.username)+ assertEquals(entry.email, back.email)+ assertEquals(entry.password, back.password)+ assertEquals(entry.note, back.note)+ assertEquals(entry.totpSecret, back.totpSecret)+ // Verbatim EntryMapper shape: Websites = ALL sites joined, so the+ // round-trip restores first→URL + full list→Websites losslessly.+ assertEquals(listOf("https://bank.example", "https://bank.example/mobile"), back.websites)+ assertEquals(entry.updatedAt, back.updatedAt)+ assertFalse(back.isPasskey)+ }++ @Test+ fun `passkey round-trips including linked password id`() {+ val entry = RemotePassword(+ uid = "pk1",+ isPasskey = true,+ rpId = "example.com",+ rpName = "Example",+ credentialId = "cred-1",+ userId = "user-1",+ userName = "ada",+ userDisplayName = "Ada",+ privateKeyB64 = "a2V5",+ linkedPasswordSyncId = "pw1",+ updatedAt = 2_000L,+ )+ val fields = KdbxCompat.toFields(entry)+ assertEquals("passkey", fields[EntryMapper.FIELD_TYPE])+ assertEquals("pw1", fields["_LinkedPassword"])+ assertTrue(fields.keys.all { it in EntryMapper.OWNED_KEYS })++ val back = KdbxCompat.fromFields(fields, now = 0L)!!+ assertTrue(back.isPasskey)+ assertEquals("example.com", back.rpId)+ assertEquals("cred-1", back.credentialId)+ assertEquals("user-1", back.userId)+ assertEquals("a2V5", back.privateKeyB64)+ assertEquals("pw1", back.linkedPasswordSyncId)+ assertEquals(2_000L, back.updatedAt)+ }++ @Test+ fun `csv export and import preserve the field map`() {+ val entries = listOf(+ RemotePassword(uid = "a", name = "A, quoted", username = "u", password = "p", updatedAt = 1L),+ RemotePassword(uid = "b", name = "B", username = "v", password = "q", updatedAt = 2L),+ )+ val csv = KdbxCompat.exportCsv(entries)+ val maps = KdbxCompat.importCsv(csv)+ assertEquals(2, maps.size)+ assertEquals("A, quoted", maps[0]["Title"])+ val back = maps.map { KdbxCompat.fromFields(it, now = 0L) }+ // CSV carries no _SyncId column: rows without one are skipped (null),+ // never adopted as new — silent adoption would fork sync ids.+ assertTrue(back.all { it == null })+ }++ @Test+ fun `json export and import round-trip`() {+ val entries = listOf(+ RemotePassword(uid = "a", name = "A", username = "u", password = "p", updatedAt = 1L),+ RemotePassword(+ uid = "pk", isPasskey = true, rpId = "r", credentialId = "c",+ updatedAt = 2L,+ ),+ )+ val maps = KdbxCompat.importJson(KdbxCompat.exportJson(entries))+ assertEquals(2, maps.size)+ val back = maps.mapNotNull { KdbxCompat.fromFields(it, now = 0L) }+ assertEquals(listOf("a", "pk"), back.map { it.uid })+ }++ @Test+ fun `tombstone import deletes the vault row`() {+ val tombstone = mapOf(+ EntryMapper.FIELD_SYNC_ID to "dead",+ EntryMapper.FIELD_TOMBSTONE to EntryMapper.TOMBSTONE_VALUE,+ )+ assertTrue(KdbxCompat.isTombstone(tombstone))+ assertEquals("dead", KdbxCompat.tombstoneSyncId(tombstone))+ assertNull(KdbxCompat.fromFields(tombstone, now = 0L))++ // Any other _Tombstone value is live data, never a delete.+ val live = mapOf(+ EntryMapper.FIELD_SYNC_ID to "live",+ EntryMapper.FIELD_TOMBSTONE to "foreign-value",+ "Title" to "T",+ )+ assertFalse(KdbxCompat.isTombstone(live))+ assertNull(KdbxCompat.tombstoneSyncId(live))+ }+}