todo, everysync: data model v3 with lists, subtasks, tags, priority, recurrence
- Commit
9472862d638e06435ff1ed7d3ff073404fae5cb0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-10-31 23:19 UTC (1 month ago)
- Parents
b3d73cc
todo: - Todo gains parent/list/section, tags, priority, timed due, start, recurrence, reminder, completedAt, estimate and blocked-by; new TodoList entity. - DB v3 migration; legacy UTC-midnight all-day due dates become local midnight (fixes the off-by-one due date west of UTC). Schema export turned on. - Pure Recurrence engine (daily/weekly BYDAY/monthly incl. last day/yearly, every-N-after-completion) and Completion, which rolls repeating tasks forward. - Relay provider: lists URIs, bulkInsert/applyBatch in one transaction, purge + snapshot clear in one transaction. Envelopes split out of the provider. - Tests: real migration against a v2 DB vs the exported schema, recurrence, completion, cross-version hash stability. everysync: - RemoteTodo mirrors the v3 fields (defaults omitted, so legacy hashes are unchanged); RemoteTodoList + TodoListKind on a separate todolists channel so pre-list builds never see list rows as tasks; skipped when the todo build predates lists. - TodoIpcSink/TodoListIpcSink upsert via bulkInsert.
Diff
everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.ktindex 0e79997dde..113bb3129d 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt@@ -136,4 +136,43 @@ data class RemoteTodo( val deleted: Boolean = false, /** Last local-or-remote modification (epoch ms); drives relay LWW. */ val updatedAt: Long = 0L,+ // v3 fields. Defaults are omitted on encode, so a task that never sets one hashes+ // exactly as it did before they existed. Mirror of todo's `RelayTodoJson`.+ /** Parent task uid for a subtask. */+ val parentUid: String? = null,+ /** Owning list uid ([RemoteTodoList.uid]); null is the Inbox. */+ val listUid: String? = null,+ val section: String? = null,+ val tags: List<String> = emptyList(),+ /** 0 none, 1 highest … 4 lowest. */+ val priority: Int = 0,+ /** When false, [dueAt] is an exact instant rather than local midnight. */+ val dueAllDay: Boolean = true,+ val startAt: Long? = null,+ /** RRULE-style repeat; `X-FROM=COMPLETION` marks after-completion repeats. */+ val recurrence: String? = null,+ val reminderAt: Long? = null,+ val completedAt: Long? = null,+ val estimateMinutes: Int? = null,+ /** Uids of tasks that must be done first. */+ val blockedBy: List<String> = emptyList(),+)++/**+ * A todo list (project), synced on its own `todolists:<vaultId>` channel so builds that+ * predate lists never mistake one for a task. Mirror of todo's `RelayTodoListJson`.+ */+@Serializable+data class RemoteTodoList(+ val uid: String,+ val name: String = "",+ /** ARGB, or null for the theme accent. */+ val color: Int? = null,+ val icon: String? = null,+ /** Sort position; excluded from the merge hash. */+ val position: Double = 0.0,+ val sections: List<String> = emptyList(),+ val createdAt: Long = 0L,+ val deleted: Boolean = false,+ val updatedAt: Long = 0L, )
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 a5f5c13817..04f1f49ae4 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@@ -164,9 +164,17 @@ object TodoIpcSink { } } - /** Bulk upsert for merge results; one IPC call per row like the single form. */+ /** Bulk upsert for merge results: one IPC call, applied in one provider transaction. */ fun upsertAll(context: Context, vaultId: String, todos: List<RemoteTodo>) {- for (todo in todos) upsert(context, vaultId, todo)+ if (todos.isEmpty()) return+ try {+ context.contentResolver.bulkInsert(+ upsertUri(vaultId),+ todos.map { ContentValues().apply { put(COL_PAYLOAD_JSON, toRelayJson(it)) } }.toTypedArray(),+ )+ } catch (expected: Exception) {+ Log.error(TAG, "upsertAll failed", expected)+ } } /**
everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoListIpcSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoListIpcSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoListIpcSink.ktnew file mode 100644index 0000000000..a0233502fd--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoListIpcSink.kt@@ -0,0 +1,91 @@+package com.vayunmathur.everysync.data.sink++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import androidx.core.database.getStringOrNull+import androidx.core.net.toUri+import com.vayunmathur.everysync.data.RemoteTodoList+import com.vayunmathur.everysync.sync.adapters.TodoListKind+import com.vayunmathur.library.log.Log++/**+ * Reads/writes todo lists through the todo app's relay ContentProvider — the list half of+ * [TodoIpcSink], same contract on `.../vault/<id>/lists[/querySince|upsertRaw|deleteByVault]`.+ * A todo build without lists answers these URIs with a null cursor, which is treated as a+ * failed read so the merge aborts rather than deleting anything.+ */+object TodoListIpcSink {+ private const val TAG = "TodoListIpcSink"+ private const val PATH_LISTS = "lists"++ @Volatile var lastListLocalOk: Boolean = true+ private set++ fun listsUri(vaultId: String): Uri =+ "content://${TodoIpcSink.AUTHORITY}/vault/$vaultId/$PATH_LISTS".toUri()++ /** False against a todo build that predates lists; the list merge is skipped then. */+ fun isSupported(context: Context, vaultId: String): Boolean =+ runCatching { context.contentResolver.getType(listsUri(vaultId)) != null }.getOrDefault(false)++ private fun upsertUri(vaultId: String): Uri =+ listsUri(vaultId).buildUpon().appendPath(TodoIpcSink.OP_UPSERT_RAW).build()++ fun listLocal(context: Context, vaultId: String): List<RemoteTodoList> {+ val out = mutableListOf<RemoteTodoList>()+ var failed = false+ try {+ val cursor = context.contentResolver.query(listsUri(vaultId), arrayOf(TodoIpcSink.COL_PAYLOAD_JSON), null, null, null)+ if (cursor == null) {+ failed = true+ } else {+ cursor.use { c ->+ val idx = c.getColumnIndex(TodoIpcSink.COL_PAYLOAD_JSON)+ while (c.moveToNext()) {+ val payload = if (idx >= 0) c.getStringOrNull(idx) else null+ if (!payload.isNullOrBlank()) {+ TodoListKind.fromJson(payload)?.takeIf { it.uid.isNotBlank() }?.let { out += it }+ }+ }+ }+ }+ } catch (expected: Exception) {+ Log.error(TAG, "listLocal failed", expected)+ failed = true+ }+ lastListLocalOk = !failed+ return out+ }++ fun upsertAll(context: Context, vaultId: String, lists: List<RemoteTodoList>) {+ if (lists.isEmpty()) return+ try {+ context.contentResolver.bulkInsert(+ upsertUri(vaultId),+ lists.map { ContentValues().apply { put(TodoIpcSink.COL_PAYLOAD_JSON, TodoListKind.toJson(it)) } }+ .toTypedArray(),+ )+ } catch (expected: Exception) {+ Log.error(TAG, "upsertAll failed", expected)+ }+ }++ fun deleteAll(context: Context, vaultId: String, uids: List<String>) {+ for (uid in uids) {+ try {+ context.contentResolver.delete(listsUri(vaultId), "${TodoIpcSink.COL_SYNC_ID} = ?", arrayOf(uid))+ } catch (expected: Exception) {+ Log.error(TAG, "delete failed", expected)+ }+ }+ }++ fun purge(context: Context, vaultId: String) {+ try {+ context.contentResolver.delete(TodoIpcSink.purgeUri(vaultId, PATH_LISTS), null, null)+ } catch (expected: Exception) {+ Log.error(TAG, "purge failed", expected)+ }+ }+}
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 1d1425b1ed..bf9a0e7848 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@@ -33,6 +33,7 @@ import com.vayunmathur.everysync.sync.PasswordRelayStore import com.vayunmathur.everysync.sync.RelayMerge import com.vayunmathur.everysync.sync.RelayPlan import com.vayunmathur.everysync.sync.RelayStore+import com.vayunmathur.everysync.sync.TodoListRelayStore import com.vayunmathur.everysync.sync.TodoRelayStore import com.vayunmathur.everysync.sync.VaultKeys import com.vayunmathur.everysync.sync.VaultRoster@@ -41,9 +42,11 @@ 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.everysync.sync.adapters.TodoListKind 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.data.sink.TodoListIpcSink import com.vayunmathur.library.log.Log import com.vayunmathur.library.ui.IconProvider import kotlin.io.encoding.Base64@@ -216,6 +219,16 @@ class E2eeProvider : SyncProvider { kind = TodoKind, store = TodoRelayStore(context, vault.vaultId), )+ if (TodoListIpcSink.isSupported(context, vault.vaultId)) {+ driveMerge(+ context = context,+ vault = vault,+ channelType = CH_TODO_LISTS,+ direction = direction,+ kind = TodoListKind,+ store = TodoListRelayStore(context, vault.vaultId),+ )+ } } /**@@ -395,6 +408,8 @@ class E2eeProvider : SyncProvider { const val CH_PASSWORDS = "passwords" const val CH_NOTES = "notes" const val CH_TODOS = "todos"+ /** Lists ride their own channel beside [CH_TODOS] under the same vault. */+ const val CH_TODO_LISTS = "todolists" private const val CH_RECORDS = "records" private val json = Json { ignoreUnknownKeys = true } @@ -448,6 +463,7 @@ class E2eeProvider : SyncProvider { DataType.TODOS -> for (meta in VaultStore.getAll(context).filter { it.dataType == rt }) { TodoIpcSink.purge(context, accountName, meta.vaultId)+ TodoListIpcSink.purge(context, meta.vaultId) } } }
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 aab5533ce7..48f228c43b 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt@@ -6,16 +6,19 @@ import com.vayunmathur.everysync.data.RemoteEvent import com.vayunmathur.everysync.data.RemoteNote import com.vayunmathur.everysync.data.RemotePassword import com.vayunmathur.everysync.data.RemoteTodo+import com.vayunmathur.everysync.data.RemoteTodoList 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.data.sink.TodoListIpcSink 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.everysync.sync.adapters.TodoListKind /** * [RelayStore] implementations over the on-device sinks, one per vault type.@@ -254,3 +257,39 @@ class TodoRelayStore( override fun serializeForRemote(entity: RemoteTodo): String = TodoKind.toJson(entity) }++class TodoListRelayStore(+ private val context: Context,+ private val vaultId: String,+) : RelayStore<RemoteTodoList> {+ override val listLocalOk: Boolean+ get() = TodoListIpcSink.lastListLocalOk++ override suspend fun listLocal(): List<RemoteTodoList> =+ TodoListIpcSink.listLocal(context, vaultId)++ override suspend fun upsertLocal(items: List<RemoteTodoList>) {+ TodoListIpcSink.upsertAll(context, vaultId, items)+ }++ override suspend fun deleteLocal(items: List<RemoteTodoList>) {+ TodoListIpcSink.deleteAll(context, vaultId, items.map { it.uid })+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> =+ VaultBaseline.load(context, vaultId, TodoListKind.kind)++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ VaultBaseline.save(context, vaultId, TodoListKind.kind, snapshots)+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ VaultBaseline.remove(context, vaultId, TodoListKind.kind, syncIds)+ }++ override fun parseRemote(json: String): RemoteTodoList? =+ TodoListKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteTodoList): String =+ TodoListKind.toJson(entity)+}
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoListKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoListKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoListKind.ktnew file mode 100644index 0000000000..dcfc052d9a--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/TodoListKind.kt@@ -0,0 +1,43 @@+package com.vayunmathur.everysync.sync.adapters++import com.vayunmathur.everysync.data.RemoteTodoList+import com.vayunmathur.everysync.sync.EntityKind+import com.vayunmathur.everysync.sync.relayContentHash+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Relay merge behaviour for todo lists on the `todolists:<vaultId>` channel, the companion+ * of [TodoKind]. Lists soft-delete like tasks; the canonical form strips identity,+ * ordering and timestamps so a reorder never looks like an edit.+ */+object TodoListKind : EntityKind<RemoteTodoList>() {+ override val kind = "todolist"++ override val localDeletesAreAuthoritative = true++ private val json = Json { ignoreUnknownKeys = true }++ override fun syncId(e: RemoteTodoList) = e.uid+ override fun updatedAt(e: RemoteTodoList) = e.updatedAt+ override fun isDeleted(e: RemoteTodoList) = e.deleted++ override fun contentHash(e: RemoteTodoList): String =+ relayContentHash(canonical(e) + "\u0000deleted=${e.deleted}")++ override fun contentKey(e: RemoteTodoList): String = "todolist\u0000${e.name}\u0000${e.createdAt}"++ override fun rebind(e: RemoteTodoList, syncId: String) = e.copy(uid = syncId)+ override fun withDeleted(e: RemoteTodoList, deleted: Boolean) = e.copy(deleted = deleted)+ override fun withUpdatedAt(e: RemoteTodoList, updatedAt: Long) = e.copy(updatedAt = updatedAt)++ fun canonical(e: RemoteTodoList): String = json.encodeToString(+ e.copy(uid = "", position = 0.0, updatedAt = 0L, deleted = false),+ )++ fun toJson(e: RemoteTodoList): String = json.encodeToString(e)++ fun fromJson(raw: String): RemoteTodoList? = runCatching {+ json.decodeFromString<RemoteTodoList>(raw)+ }.getOrNull()+}
everysync/src/test/java/com/vayunmathur/everysync/sync/adapters/TodoListKindTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/sync/adapters/TodoListKindTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/sync/adapters/TodoListKindTest.ktnew file mode 100644index 0000000000..a34b97ed29--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/sync/adapters/TodoListKindTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.everysync.sync.adapters++import com.vayunmathur.everysync.data.RemoteTodo+import com.vayunmathur.everysync.data.RemoteTodoList+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** The v3 todo fields and the list kind, with cross-version hash stability. */+class TodoListKindTest {++ @Test+ fun legacyTodoPayloadHashesTheSameUnderTheV3Model() {+ // Bytes a pre-v3 build put on the relay for this task.+ val legacyJson = """{"uid":"t1","title":"Shop","done":true,"dueAt":5,"createdAt":7,"updatedAt":100}"""+ val parsed = TodoKind.fromJson(legacyJson)!!+ assertEquals(legacyJson, TodoKind.toJson(parsed))+ assertEquals(+ """{"uid":"","title":"Shop","done":true,"dueAt":5,"createdAt":7}""",+ TodoKind.canonical(parsed),+ )+ }++ @Test+ fun v3TodoFieldsRoundTripAndCountAsEdits() {+ val base = RemoteTodo(uid = "t1", title = "Shop", createdAt = 7L)+ val rich = base.copy(+ listUid = "l1",+ parentUid = "p1",+ tags = listOf("home"),+ priority = 1,+ dueAllDay = false,+ recurrence = "FREQ=DAILY",+ blockedBy = listOf("b1"),+ )+ assertEquals(rich, TodoKind.fromJson(TodoKind.toJson(rich)))+ assertTrue(TodoKind.contentHash(base) != TodoKind.contentHash(rich))+ assertTrue(TodoKind.contentHash(base) != TodoKind.contentHash(base.copy(priority = 2)))+ }++ @Test+ fun listCanonicalIgnoresIdentityOrderAndClock() {+ val base = RemoteTodoList(uid = "l1", name = "Work", position = 1.0, createdAt = 3L, updatedAt = 10L)+ val variant = base.copy(uid = "l2", position = 9.0, updatedAt = 99L)+ assertEquals(TodoListKind.contentHash(base), TodoListKind.contentHash(variant))+ assertTrue(TodoListKind.contentHash(base) != TodoListKind.contentHash(base.copy(name = "Home")))+ assertTrue(TodoListKind.contentHash(base) != TodoListKind.contentHash(base.copy(deleted = true)))+ }++ @Test+ fun listContentKeyUsesNameAndCreatedAt() {+ val a = RemoteTodoList(uid = "a", name = "Work", createdAt = 1L)+ assertEquals(TodoListKind.contentKey(a), TodoListKind.contentKey(a.copy(uid = "b")))+ assertTrue(TodoListKind.contentKey(a) != TodoListKind.contentKey(a.copy(name = "Home")))+ assertTrue(TodoListKind.contentKey(a).startsWith("todolist"))+ }++ @Test+ fun listJsonRoundTrips() {+ val list = RemoteTodoList(uid = "l1", name = "Work", color = -16711936, icon = "work", sections = listOf("A", "B"))+ assertEquals(list, TodoListKind.fromJson(TodoListKind.toJson(list)))+ }+}
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex e296f5bb0f..46e9c6872c 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -211,6 +211,7 @@ androidx-savedstate = { group = "androidx.savedstate", name = "savedstate", vers androidx-lifecycle-viewmodel-savedstate = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-savedstate", version.ref = "lifecycle" } androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" } androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", version.ref = "sqlite" }+androidx-sqlite-bundled-jvm = { module = "androidx.sqlite:sqlite-bundled-jvm", version.ref = "sqlite" } androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" } androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }
todo/build.gradle.kts
diff --git a/todo/build.gradle.kts b/todo/build.gradle.ktsindex 4d727522e9..d62b1d1999 100644--- a/todo/build.gradle.kts+++ b/todo/build.gradle.kts@@ -16,7 +16,12 @@ android { } } +ksp {+ arg("room.schemaLocation", "$projectDir/schemas")+}+ dependencies { implementRoom(libs) implementation(project(":library:room"))+ testImplementation(libs.androidx.sqlite.bundled.jvm) }
todo/schemas/com.vayunmathur.todo.data.TodoDatabase/3.json
diff --git a/todo/schemas/com.vayunmathur.todo.data.TodoDatabase/3.json b/todo/schemas/com.vayunmathur.todo.data.TodoDatabase/3.jsonnew file mode 100644index 0000000000..82449ca171--- /dev/null+++ b/todo/schemas/com.vayunmathur.todo.data.TodoDatabase/3.json@@ -0,0 +1,306 @@+{+ "formatVersion": 1,+ "database": {+ "version": 3,+ "identityHash": "efaa234effa3d50d4962a5daaeb3fe3c",+ "entities": [+ {+ "tableName": "Todo",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, `notes` TEXT NOT NULL, `done` INTEGER NOT NULL, `position` REAL NOT NULL, `dueAt` INTEGER, `createdAt` INTEGER NOT NULL, `syncId` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `parentSyncId` TEXT, `listSyncId` TEXT, `section` TEXT, `tags` TEXT NOT NULL, `priority` INTEGER NOT NULL, `dueAllDay` INTEGER NOT NULL, `startAt` INTEGER, `recurrence` TEXT, `reminderAt` INTEGER, `completedAt` INTEGER, `estimateMinutes` INTEGER, `blockedBy` TEXT NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "notes",+ "columnName": "notes",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "done",+ "columnName": "done",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "dueAt",+ "columnName": "dueAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncId",+ "columnName": "syncId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updatedAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deleted",+ "columnName": "deleted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "parentSyncId",+ "columnName": "parentSyncId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "listSyncId",+ "columnName": "listSyncId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tags",+ "columnName": "tags",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "dueAllDay",+ "columnName": "dueAllDay",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "startAt",+ "columnName": "startAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "reminderAt",+ "columnName": "reminderAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completedAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "estimateMinutes",+ "columnName": "estimateMinutes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "blockedBy",+ "columnName": "blockedBy",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_Todo_syncId",+ "unique": false,+ "columnNames": [+ "syncId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Todo_syncId` ON `${TABLE_NAME}` (`syncId`)"+ },+ {+ "name": "index_Todo_listSyncId",+ "unique": false,+ "columnNames": [+ "listSyncId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Todo_listSyncId` ON `${TABLE_NAME}` (`listSyncId`)"+ },+ {+ "name": "index_Todo_parentSyncId",+ "unique": false,+ "columnNames": [+ "parentSyncId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Todo_parentSyncId` ON `${TABLE_NAME}` (`parentSyncId`)"+ }+ ]+ },+ {+ "tableName": "TodoList",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `syncId` TEXT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER, `icon` TEXT, `position` REAL NOT NULL, `sections` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncId",+ "columnName": "syncId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "color",+ "columnName": "color",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "icon",+ "columnName": "icon",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "sections",+ "columnName": "sections",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updatedAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deleted",+ "columnName": "deleted",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_TodoList_syncId",+ "unique": false,+ "columnNames": [+ "syncId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_TodoList_syncId` ON `${TABLE_NAME}` (`syncId`)"+ }+ ]+ },+ {+ "tableName": "SyncSnapshot",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`syncId` TEXT NOT NULL, `kind` TEXT NOT NULL, `contentHash` TEXT NOT NULL, `localUpdatedAt` INTEGER NOT NULL, `remoteModified` INTEGER NOT NULL, `lastSyncedAt` INTEGER NOT NULL, PRIMARY KEY(`syncId`))",+ "fields": [+ {+ "fieldPath": "syncId",+ "columnName": "syncId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "kind",+ "columnName": "kind",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentHash",+ "columnName": "contentHash",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "localUpdatedAt",+ "columnName": "localUpdatedAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteModified",+ "columnName": "remoteModified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "lastSyncedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "syncId"+ ]+ }+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'efaa234effa3d50d4962a5daaeb3fe3c')"+ ]+ }+}\ No newline at end of file
todo/src/main/java/com/vayunmathur/todo/data/SyncSnapshot.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/SyncSnapshot.kt b/todo/src/main/java/com/vayunmathur/todo/data/SyncSnapshot.ktindex d1fdc6a01c..262b6a6f2b 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/SyncSnapshot.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/SyncSnapshot.kt@@ -24,5 +24,6 @@ data class SyncSnapshot( ) { companion object { const val KIND_TODO = "todo"+ const val KIND_LIST = "todolist" } }
todo/src/main/java/com/vayunmathur/todo/data/Todo.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/Todo.kt b/todo/src/main/java/com/vayunmathur/todo/data/Todo.ktindex 22741cbbba..f057db1d78 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/Todo.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/Todo.kt@@ -1,25 +1,56 @@ package com.vayunmathur.todo.data import androidx.room3.Entity+import androidx.room3.Index import androidx.room3.PrimaryKey import com.vayunmathur.library.util.ReorderableDatabaseItem import kotlinx.serialization.Serializable @Serializable-@Entity+@Entity(indices = [Index("syncId"), Index("listSyncId"), Index("parentSyncId")]) data class Todo( @PrimaryKey(autoGenerate = true) override val id: Long = 0, val title: String = "", val notes: String = "", val done: Boolean = false, override val position: Double = 0.0,- /** Epoch ms the task is due, or null for no due date. */+ /**+ * Epoch ms the task is due, or null. When [dueAllDay] it is local midnight of the due+ * date; otherwise the exact instant.+ */ val dueAt: Long? = null, /** Epoch ms the task was created; part of the relay adoption content key. */ val createdAt: Long = System.currentTimeMillis(), val syncId: String = newSyncId(), val updatedAt: Long = System.currentTimeMillis(), val deleted: Boolean = false,+ /** Set on subtasks: the parent task's [syncId]. Subtasks are one level deep. */+ val parentSyncId: String? = null,+ /** The owning [TodoList.syncId]; null is the Inbox. */+ val listSyncId: String? = null,+ /** Name of a section in the owning list, or null. */+ val section: String? = null,+ val tags: List<String> = emptyList(),+ /** 0 none, 1 highest … 4 lowest. */+ val priority: Int = 0,+ val dueAllDay: Boolean = true,+ /** Hidden from Today/Upcoming until this epoch ms. */+ val startAt: Long? = null,+ /** [Recurrence][com.vayunmathur.todo.domain.Recurrence] string, or null. */+ val recurrence: String? = null,+ val reminderAt: Long? = null,+ /** Epoch ms of the last completion. */+ val completedAt: Long? = null,+ val estimateMinutes: Int? = null,+ /** Sync ids of tasks that must be done first. */+ val blockedBy: List<String> = emptyList(), ) : ReorderableDatabaseItem<Todo> { override fun withPosition(position: Double) = copy(position = position)++ val isSubtask: Boolean get() = parentSyncId != null++ companion object {+ const val PRIORITY_NONE = 0+ const val PRIORITY_MAX = 4+ } }
todo/src/main/java/com/vayunmathur/todo/data/TodoConverters.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoConverters.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoConverters.ktnew file mode 100644index 0000000000..cdcb271648--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoConverters.kt@@ -0,0 +1,13 @@+package com.vayunmathur.todo.data++import androidx.room3.ColumnTypeConverter+import kotlinx.serialization.json.Json++class TodoConverters {+ @ColumnTypeConverter+ fun fromStringList(value: List<String>): String = Json.encodeToString(value)++ @ColumnTypeConverter+ fun toStringList(value: String): List<String> =+ runCatching { Json.decodeFromString<List<String>>(value) }.getOrDefault(emptyList())+}
todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.ktindex 3d382b8881..423e9db8b2 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt@@ -1,16 +1,15 @@ package com.vayunmathur.todo.data import android.content.Context+import androidx.room3.ColumnTypeConverters import androidx.room3.Dao import androidx.room3.Database-import androidx.room3.Delete import androidx.room3.Query import androidx.room3.RoomDatabase import androidx.room3.Upsert+import androidx.room3.migration.Migration import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DatabaseMigrations-import androidx.room3.migration.Migration-import androidx.sqlite.execSQL import kotlinx.coroutines.flow.Flow const val DB_NAME = "todo-db"@@ -27,9 +26,6 @@ abstract class TodoDao { @Query("SELECT * FROM Todo WHERE deleted = 0 ORDER BY position") abstract suspend fun getAll(): List<Todo> - @Query("SELECT * FROM Todo")- abstract suspend fun getAllIncludingDeleted(): List<Todo>- @Query("SELECT * FROM Todo WHERE id = :id AND deleted = 0") abstract suspend fun getById(id: Long): Todo? @@ -39,50 +35,89 @@ abstract class TodoDao { @Query("SELECT * FROM Todo WHERE syncId = :syncId") abstract fun getBySyncIdFlow(syncId: String): Flow<Todo?> - @Query("SELECT MAX(position) FROM Todo WHERE deleted = 0")- abstract suspend fun maxPosition(): Double?+ @Query("SELECT * FROM Todo WHERE parentSyncId = :parentSyncId AND deleted = 0 ORDER BY position")+ abstract suspend fun getSubtasks(parentSyncId: String): List<Todo> @Query("SELECT * FROM Todo WHERE updatedAt > :since") abstract suspend fun getUpdatedSince(since: Long): List<Todo> + @Query("SELECT MAX(position) FROM Todo WHERE deleted = 0")+ abstract suspend fun maxPosition(): Double?++ @Query("SELECT * FROM Todo WHERE deleted = 0 AND listSyncId = :listSyncId")+ abstract suspend fun getInList(listSyncId: String): List<Todo>+ /** Local write: bumps updatedAt so the change is picked up by sync. */ suspend fun upsert(value: Todo): Long = upsertRaw(value.copy(updatedAt = System.currentTimeMillis())) + /** Local bulk write: bumps updatedAt on every row so reorders reach sync. */+ suspend fun upsertAll(values: List<Todo>) {+ val now = System.currentTimeMillis()+ upsertAllRaw(values.map { it.copy(updatedAt = now) })+ }+ /** Writes [value] verbatim. Only the relay sync uses this, to preserve a pulled timestamp. */ @Upsert abstract suspend fun upsertRaw(value: Todo): Long - @Delete- abstract suspend fun delete(value: Todo): Int+ /** Writes [values] verbatim. Only the relay sync uses this. */+ @Upsert+ abstract suspend fun upsertAllRaw(values: List<Todo>) - @Query("DELETE FROM Todo WHERE syncId = :syncId")- abstract suspend fun deleteBySyncId(syncId: String): Int+ @Query(+ "DELETE FROM Todo WHERE deleted = 1 AND updatedAt < :before " ++ "AND syncId NOT IN (SELECT syncId FROM SyncSnapshot)",+ )+ abstract suspend fun deleteUnsyncedTombstones(before: Long): Int @Query("DELETE FROM Todo") abstract suspend fun deleteAll()+} - /** Local bulk write: bumps updatedAt on every row so reorders reach sync. */- suspend fun upsertAll(values: List<Todo>) {+@Dao+abstract class TodoListDao {+ @Query("SELECT * FROM TodoList WHERE deleted = 0 ORDER BY position")+ abstract fun getAllFlow(): Flow<List<TodoList>>++ @Query("SELECT * FROM TodoList WHERE deleted = 0 ORDER BY position")+ abstract suspend fun getAll(): List<TodoList>++ @Query("SELECT * FROM TodoList WHERE syncId = :syncId")+ abstract suspend fun getBySyncId(syncId: String): TodoList?++ @Query("SELECT * FROM TodoList WHERE updatedAt > :since")+ abstract suspend fun getUpdatedSince(since: Long): List<TodoList>++ @Query("SELECT MAX(position) FROM TodoList WHERE deleted = 0")+ abstract suspend fun maxPosition(): Double?++ suspend fun upsert(value: TodoList): Long =+ upsertRaw(value.copy(updatedAt = System.currentTimeMillis()))++ suspend fun upsertAll(values: List<TodoList>) { val now = System.currentTimeMillis() upsertAllRaw(values.map { it.copy(updatedAt = now) }) } - @Query(- "DELETE FROM Todo WHERE deleted = 1 AND updatedAt < :before " +- "AND syncId NOT IN (SELECT syncId FROM SyncSnapshot)",- )- abstract suspend fun deleteUnsyncedTombstones(before: Long): Int+ @Upsert+ abstract suspend fun upsertRaw(value: TodoList): Long - /** Writes [values] verbatim. Only the relay sync uses this. */ @Upsert- abstract suspend fun upsertAllRaw(values: List<Todo>)+ abstract suspend fun upsertAllRaw(values: List<TodoList>)++ @Query("DELETE FROM TodoList")+ abstract suspend fun deleteAll() } @Dao interface TodoSyncSnapshotDao {- @Query("SELECT * FROM SyncSnapshot")- suspend fun getAll(): List<SyncSnapshot>+ @Query("SELECT * FROM SyncSnapshot WHERE kind = :kind")+ suspend fun getByKind(kind: String): List<SyncSnapshot>++ /** Todo snapshots predate the kind column being filled in, so match "anything but lists". */+ @Query("SELECT * FROM SyncSnapshot WHERE kind != :excludedKind")+ suspend fun getAllExcept(excludedKind: String): List<SyncSnapshot> @Upsert suspend fun upsert(snapshot: SyncSnapshot)@@ -90,25 +125,21 @@ interface TodoSyncSnapshotDao { @Query("DELETE FROM SyncSnapshot WHERE syncId = :syncId") suspend fun deleteBySyncId(syncId: String) - @Query("DELETE FROM SyncSnapshot")- suspend fun deleteAll()+ @Query("DELETE FROM SyncSnapshot WHERE kind = :kind")+ suspend fun deleteByKind(kind: String)++ @Query("DELETE FROM SyncSnapshot WHERE kind != :excludedKind")+ suspend fun deleteAllExcept(excludedKind: String) } -@Database(entities = [Todo::class, SyncSnapshot::class], version = 2, exportSchema = false)+@Database(entities = [Todo::class, TodoList::class, SyncSnapshot::class], version = 3, exportSchema = true)+@ColumnTypeConverters(TodoConverters::class) abstract class TodoDatabase : RoomDatabase() { abstract fun todoDao(): TodoDao+ abstract fun todoListDao(): TodoListDao abstract fun syncSnapshotDao(): TodoSyncSnapshotDao companion object : DatabaseMigrations {- // v2 adds the relay-carried `notes` + `createdAt` columns (drift fix):- // the relay envelope always carried both, but the native model dropped- // them on persist, so LWW on those fields never converged locally.- override val migrations: List<Migration> = listOf(- Migration(1, 2) {- it.execSQL("ALTER TABLE `Todo` ADD COLUMN `notes` TEXT NOT NULL DEFAULT ''")- it.execSQL("ALTER TABLE `Todo` ADD COLUMN `createdAt` INTEGER NOT NULL DEFAULT 0")- it.execSQL("UPDATE `Todo` SET `createdAt` = `updatedAt` WHERE `createdAt` = 0")- },- )+ override val migrations: List<Migration> = TodoMigrations.all } }
todo/src/main/java/com/vayunmathur/todo/data/TodoList.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoList.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoList.ktnew file mode 100644index 0000000000..e4488ab822--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoList.kt@@ -0,0 +1,28 @@+package com.vayunmathur.todo.data++import androidx.room3.Entity+import androidx.room3.Index+import androidx.room3.PrimaryKey+import com.vayunmathur.library.util.ReorderableDatabaseItem+import kotlinx.serialization.Serializable++/** A user list (project). Tasks point at it through [Todo.listSyncId]. */+@Serializable+@Entity(indices = [Index("syncId")])+data class TodoList(+ @PrimaryKey(autoGenerate = true) override val id: Long = 0,+ val syncId: String = newSyncId(),+ val name: String = "",+ /** ARGB, or null for the theme accent. */+ val color: Int? = null,+ /** Key into the list icon set drawn by the UI, or null for the default. */+ val icon: String? = null,+ override val position: Double = 0.0,+ /** Section names in display order. */+ val sections: List<String> = emptyList(),+ val createdAt: Long = System.currentTimeMillis(),+ val updatedAt: Long = System.currentTimeMillis(),+ val deleted: Boolean = false,+) : ReorderableDatabaseItem<TodoList> {+ override fun withPosition(position: Double) = copy(position = position)+}
todo/src/main/java/com/vayunmathur/todo/data/TodoMigrations.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoMigrations.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoMigrations.ktnew file mode 100644index 0000000000..22d1cb2708--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoMigrations.kt@@ -0,0 +1,66 @@+package com.vayunmathur.todo.data++import androidx.room3.migration.Migration+import androidx.sqlite.SQLiteConnection+import androidx.sqlite.execSQL+import com.vayunmathur.todo.domain.DueDates+import kotlinx.datetime.TimeZone++internal object TodoMigrations {+ // v2 adds the relay-carried `notes` + `createdAt` columns (drift fix): the relay+ // envelope always carried both, but the native model dropped them on persist.+ private val v1to2 = Migration(1, 2) {+ it.execSQL("ALTER TABLE `Todo` ADD COLUMN `notes` TEXT NOT NULL DEFAULT ''")+ it.execSQL("ALTER TABLE `Todo` ADD COLUMN `createdAt` INTEGER NOT NULL DEFAULT 0")+ it.execSQL("UPDATE `Todo` SET `createdAt` = `updatedAt` WHERE `createdAt` = 0")+ }++ // v3: lists, subtasks, tags, priority, timed due, start, recurrence, reminders.+ private val v2to3 = Migration(2, 3) { conn ->+ listOf(+ "`parentSyncId` TEXT",+ "`listSyncId` TEXT",+ "`section` TEXT",+ "`tags` TEXT NOT NULL DEFAULT '[]'",+ "`priority` INTEGER NOT NULL DEFAULT 0",+ "`dueAllDay` INTEGER NOT NULL DEFAULT 1",+ "`startAt` INTEGER",+ "`recurrence` TEXT",+ "`reminderAt` INTEGER",+ "`completedAt` INTEGER",+ "`estimateMinutes` INTEGER",+ "`blockedBy` TEXT NOT NULL DEFAULT '[]'",+ ).forEach { conn.execSQL("ALTER TABLE `Todo` ADD COLUMN $it") }+ conn.execSQL(+ "CREATE TABLE IF NOT EXISTS `TodoList` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++ "`syncId` TEXT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER, `icon` TEXT, " ++ "`position` REAL NOT NULL, `sections` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " ++ "`updatedAt` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)",+ )+ conn.execSQL("CREATE INDEX IF NOT EXISTS `index_Todo_syncId` ON `Todo` (`syncId`)")+ conn.execSQL("CREATE INDEX IF NOT EXISTS `index_Todo_listSyncId` ON `Todo` (`listSyncId`)")+ conn.execSQL("CREATE INDEX IF NOT EXISTS `index_Todo_parentSyncId` ON `Todo` (`parentSyncId`)")+ conn.execSQL("CREATE INDEX IF NOT EXISTS `index_TodoList_syncId` ON `TodoList` (`syncId`)")+ convertLegacyDueDates(conn, TimeZone.currentSystemDefault())+ }++ /** Pre-v3 all-day due values were the picker's UTC midnight; store local midnight instead. */+ private fun convertLegacyDueDates(conn: SQLiteConnection, zone: TimeZone) {+ val rows = mutableListOf<Pair<Long, Long>>()+ conn.prepare("SELECT `id`, `dueAt` FROM `Todo` WHERE `dueAt` IS NOT NULL").use { stmt ->+ while (stmt.step()) rows += stmt.getLong(0) to stmt.getLong(1)+ }+ conn.prepare("UPDATE `Todo` SET `dueAt` = ? WHERE `id` = ?").use { stmt ->+ for ((id, due) in rows) {+ val converted = DueDates.migrateLegacyAllDay(due, zone)+ if (converted == due) continue+ stmt.bindLong(1, converted)+ stmt.bindLong(2, id)+ stmt.step()+ stmt.reset()+ }+ }+ }++ val all: List<Migration> = listOf(v1to2, v2to3)+}
todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.ktindex bc6e60280e..af21d36da8 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt@@ -1,7 +1,9 @@ package com.vayunmathur.todo.data import android.content.Context+import androidx.room3.withWriteTransaction import com.vayunmathur.library.room.RoomRepository+import com.vayunmathur.todo.domain.Completion import com.vayunmathur.todo.domain.Positions import com.vayunmathur.todo.domain.TombstonePolicy import kotlinx.coroutines.CoroutineDispatcher@@ -9,6 +11,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow+import kotlinx.datetime.TimeZone class TodoRepository private constructor( context: Context,@@ -19,14 +22,21 @@ class TodoRepository private constructor( val appScope: CoroutineScope = CoroutineScope(SupervisorJob() + io) private val dao get() = db.todoDao()+ private val listDao get() = db.todoListDao() private val snapshotDao get() = db.syncSnapshotDao() val todos: Flow<List<Todo>> get() = dao.getAllFlow()+ val lists: Flow<List<TodoList>> get() = listDao.getAllFlow() fun todoBySyncIdFlow(syncId: String): Flow<Todo?> = dao.getBySyncIdFlow(syncId) + suspend fun <R> inTransaction(block: suspend () -> R): R = db.withWriteTransaction { block() }++ // --- Tasks ---+ suspend fun getAll(): List<Todo> = dao.getAll() suspend fun getById(id: Long): Todo? = dao.getById(id) suspend fun getBySyncId(syncId: String): Todo? = dao.getBySyncId(syncId)+ suspend fun getSubtasks(parentSyncId: String): List<Todo> = dao.getSubtasks(parentSyncId) suspend fun getUpdatedSince(since: Long): List<Todo> = dao.getUpdatedSince(since) suspend fun nextPosition(): Double = Positions.after(dao.maxPosition())@@ -39,11 +49,15 @@ class TodoRepository private constructor( /** Writes [value] verbatim. Only the relay sync uses this, to preserve a pulled timestamp. */ suspend fun upsertRaw(value: Todo): Long = dao.upsertRaw(value)- suspend fun upsertAllRaw(values: List<Todo>) = dao.upsertAllRaw(values) - /** Soft delete: the relay sync propagates the tombstone. */- suspend fun tombstone(value: Todo) {+ /** Soft delete: the relay sync propagates the tombstone. Subtasks go with their parent. */+ suspend fun tombstone(value: Todo) = inTransaction { dao.upsert(value.copy(deleted = true))+ dao.upsertAll(dao.getSubtasks(value.syncId).map { it.copy(deleted = true) })+ }++ suspend fun restore(value: Todo) = inTransaction {+ dao.upsert(value.copy(deleted = false)) } suspend fun tombstoneBySyncId(syncId: String): Int {@@ -52,10 +66,67 @@ class TodoRepository private constructor( return 1 } + /**+ * Sets the done state. Completing a repeating task rolls it to the next occurrence and+ * reopens its subtasks; returns the stored row.+ */+ suspend fun setDone(todo: Todo, done: Boolean, now: Long = System.currentTimeMillis()): Todo = inTransaction {+ val updated = if (done) Completion.complete(todo, now, TimeZone.currentSystemDefault()) else Completion.uncomplete(todo)+ dao.upsert(updated)+ if (Completion.rolledForward(todo, updated)) {+ dao.upsertAll(dao.getSubtasks(todo.syncId).filter { it.done }.map { Completion.uncomplete(it) })+ }+ updated+ }++ suspend fun duplicate(todo: Todo): Todo = inTransaction {+ val copy = todo.copy(+ id = 0,+ syncId = newSyncId(),+ title = todo.title,+ done = false,+ completedAt = null,+ position = nextPosition(),+ createdAt = System.currentTimeMillis(),+ )+ val id = dao.upsert(copy)+ dao.getSubtasks(todo.syncId).forEach { sub ->+ dao.upsert(sub.copy(id = 0, syncId = newSyncId(), parentSyncId = copy.syncId, createdAt = copy.createdAt))+ }+ copy.copy(id = id)+ }+ /** Removes every todo (including tombstones). Used when a relay vault is purged. */ suspend fun purge() = dao.deleteAll() - /** Housekeeping on launch: drop stale unsynced tombstones and repair colliding positions. */+ // --- Lists ---++ suspend fun getLists(): List<TodoList> = listDao.getAll()+ suspend fun getListBySyncId(syncId: String): TodoList? = listDao.getBySyncId(syncId)+ suspend fun getListsUpdatedSince(since: Long): List<TodoList> = listDao.getUpdatedSince(since)+ suspend fun nextListPosition(): Double = Positions.after(listDao.maxPosition())++ suspend fun upsertList(value: TodoList): Long = listDao.upsert(value)+ suspend fun upsertLists(values: List<TodoList>) = listDao.upsertAll(values)+ suspend fun upsertListRaw(value: TodoList): Long = listDao.upsertRaw(value)++ /** Deletes a list; its tasks move to the Inbox. */+ suspend fun tombstoneList(list: TodoList) = inTransaction {+ listDao.upsert(list.copy(deleted = true))+ dao.upsertAll(dao.getInList(list.syncId).map { it.copy(listSyncId = null, section = null) })+ }++ suspend fun tombstoneListBySyncId(syncId: String): Int {+ val existing = listDao.getBySyncId(syncId) ?: return 0+ if (!existing.deleted) listDao.upsert(existing.copy(deleted = true))+ return 1+ }++ suspend fun purgeLists() = listDao.deleteAll()++ // --- Housekeeping ---++ /** On launch: drop stale unsynced tombstones and repair colliding positions. */ suspend fun maintain(now: Long = System.currentTimeMillis()) { dao.deleteUnsyncedTombstones(TombstonePolicy.cutoff(now)) val ordered = dao.getAll().sortedWith(compareBy({ it.position }, { it.createdAt }))@@ -65,10 +136,14 @@ class TodoRepository private constructor( } } - suspend fun getAllSnapshots(): List<SyncSnapshot> = snapshotDao.getAll()+ // --- Relay snapshots ---++ suspend fun getTodoSnapshots(): List<SyncSnapshot> = snapshotDao.getAllExcept(SyncSnapshot.KIND_LIST)+ suspend fun getListSnapshots(): List<SyncSnapshot> = snapshotDao.getByKind(SyncSnapshot.KIND_LIST) suspend fun upsertSnapshot(snapshot: SyncSnapshot) = snapshotDao.upsert(snapshot) suspend fun deleteSnapshotBySyncId(syncId: String) = snapshotDao.deleteBySyncId(syncId)- suspend fun deleteAllSnapshots() = snapshotDao.deleteAll()+ suspend fun deleteTodoSnapshots() = snapshotDao.deleteAllExcept(SyncSnapshot.KIND_LIST)+ suspend fun deleteListSnapshots() = snapshotDao.deleteByKind(SyncSnapshot.KIND_LIST) companion object { @Volatile private var instance: TodoRepository? = null
todo/src/main/java/com/vayunmathur/todo/domain/Completion.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/Completion.kt b/todo/src/main/java/com/vayunmathur/todo/domain/Completion.ktnew file mode 100644index 0000000000..b6befd4308--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/Completion.kt@@ -0,0 +1,37 @@+package com.vayunmathur.todo.domain++import com.vayunmathur.todo.data.Todo+import kotlinx.datetime.TimeZone++/** Checking a task off. A repeating task rolls forward to its next occurrence instead. */+object Completion {++ fun complete(todo: Todo, now: Long, zone: TimeZone): Todo {+ val recurrence = Recurrence.parse(todo.recurrence)+ val due = todo.dueAt+ if (recurrence == null || (due == null && recurrence !is Recurrence.AfterCompletion)) {+ return todo.copy(done = true, completedAt = now)+ }+ val today = DueDates.localDate(now, zone)+ val dueDate = due?.let { DueDates.localDate(it, zone) } ?: today+ val nextDate = recurrence.nextDate(dueDate, today)+ val nextDue = if (due == null || todo.dueAllDay) {+ DueDates.startOfDay(nextDate, zone)+ } else {+ DueDates.at(nextDate, DueDates.localTime(due, zone), zone)+ }+ val shift = nextDue - (due ?: DueDates.startOfDay(today, zone))+ return todo.copy(+ done = false,+ completedAt = now,+ dueAt = nextDue,+ startAt = todo.startAt?.plus(shift),+ reminderAt = todo.reminderAt?.plus(shift),+ )+ }++ fun uncomplete(todo: Todo): Todo = todo.copy(done = false, completedAt = null)++ /** True when [complete] rolled the task forward rather than finishing it. */+ fun rolledForward(before: Todo, after: Todo): Boolean = !after.done && before.dueAt != after.dueAt+}
todo/src/main/java/com/vayunmathur/todo/domain/DueDates.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/DueDates.kt b/todo/src/main/java/com/vayunmathur/todo/domain/DueDates.ktnew file mode 100644index 0000000000..16c274a437--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/DueDates.kt@@ -0,0 +1,43 @@+package com.vayunmathur.todo.domain++import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/**+ * Conversions between stored due values and calendar dates.+ *+ * All-day due values are local midnight. The Material date picker speaks UTC midnight, so+ * values crossing that boundary go through [fromPickerMillis]/[toPickerMillis]; feeding a+ * UTC-midnight value straight into local formatting shows the previous day west of UTC.+ */+object DueDates {+ private const val DAY_MS = 86_400_000L++ fun localDate(epochMs: Long, zone: TimeZone): LocalDate =+ Instant.fromEpochMilliseconds(epochMs).toLocalDateTime(zone).date++ fun localTime(epochMs: Long, zone: TimeZone): LocalTime =+ Instant.fromEpochMilliseconds(epochMs).toLocalDateTime(zone).time++ fun startOfDay(date: LocalDate, zone: TimeZone): Long =+ date.atStartOfDayIn(zone).toEpochMilliseconds()++ fun at(date: LocalDate, time: LocalTime, zone: TimeZone): Long =+ LocalDateTime(date, time).toInstant(zone).toEpochMilliseconds()++ fun fromPickerMillis(utcMidnight: Long, zone: TimeZone): Long =+ startOfDay(localDate(utcMidnight, TimeZone.UTC), zone)++ fun toPickerMillis(localEpochMs: Long, zone: TimeZone): Long =+ startOfDay(localDate(localEpochMs, zone), TimeZone.UTC)++ /** Rewrites a legacy UTC-midnight all-day value as local midnight; other values pass through. */+ fun migrateLegacyAllDay(epochMs: Long, zone: TimeZone): Long =+ if (epochMs % DAY_MS == 0L) fromPickerMillis(epochMs, zone) else epochMs+}
todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt b/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.ktnew file mode 100644index 0000000000..2f06e82430--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt@@ -0,0 +1,134 @@+package com.vayunmathur.todo.domain++import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.DayOfWeek+import kotlinx.datetime.LocalDate+import kotlinx.datetime.daysUntil+import kotlinx.datetime.isoDayNumber+import kotlinx.datetime.minus+import kotlinx.datetime.number+import kotlinx.datetime.plus++/**+ * How a task repeats. Stored as an RRULE-style string ([serialize]/[parse]) so the calendar+ * mirror can hand the fixed schedules to CalendarContract unchanged; the after-completion+ * variant is carried with a private `X-FROM=COMPLETION` part.+ */+sealed interface Recurrence {+ val interval: Int++ data class Daily(override val interval: Int = 1) : Recurrence++ /** [days] empty means "the due date's weekday". */+ data class Weekly(override val interval: Int = 1, val days: Set<DayOfWeek> = emptySet()) : Recurrence++ /** [dayOfMonth] null means "the due date's day", [LAST_DAY] the last day of the month. */+ data class Monthly(override val interval: Int = 1, val dayOfMonth: Int? = null) : Recurrence++ data class Yearly(override val interval: Int = 1) : Recurrence++ /** Due [interval] days after the task is completed, whenever that is. */+ data class AfterCompletion(override val interval: Int = 1) : Recurrence++ /**+ * First due date after this occurrence: strictly after both [due] and [today], so+ * completing an overdue task never lands it in the past or back on today.+ */+ fun nextDate(due: LocalDate, today: LocalDate): LocalDate {+ val base = if (due > today) due else today+ return when (this) {+ is Daily -> due.plus(stepsPast(due.daysUntil(base), interval) * interval, DateTimeUnit.DAY)+ is Weekly -> nextWeekly(due, base)+ is Monthly -> nextMonthly(due, base)+ is Yearly -> generateSequence(1) { it + 1 }+ .map { due.plus(it * interval, DateTimeUnit.YEAR) }+ .first { it > base }+ is AfterCompletion -> today.plus(interval, DateTimeUnit.DAY)+ }+ }++ fun serialize(): String {+ val parts = mutableListOf<String>()+ parts += "FREQ=" + when (this) {+ is Daily, is AfterCompletion -> "DAILY"+ is Weekly -> "WEEKLY"+ is Monthly -> "MONTHLY"+ is Yearly -> "YEARLY"+ }+ if (interval != 1) parts += "INTERVAL=$interval"+ if (this is Weekly && days.isNotEmpty()) {+ parts += "BYDAY=" + days.sortedBy { it.isoDayNumber }.joinToString(",") { DAY_CODES.getValue(it) }+ }+ if (this is Monthly && dayOfMonth != null) parts += "BYMONTHDAY=$dayOfMonth"+ if (this is AfterCompletion) parts += "$X_FROM=COMPLETION"+ return parts.joinToString(";")+ }++ /** The plain RRULE for calendars, or null when the schedule depends on completion. */+ fun toRRule(): String? = if (this is AfterCompletion) null else serialize()++ companion object {+ const val LAST_DAY = -1+ private const val X_FROM = "X-FROM"+ private const val MAX_INTERVAL = 999++ private val DAY_CODES = mapOf(+ DayOfWeek.MONDAY to "MO", DayOfWeek.TUESDAY to "TU", DayOfWeek.WEDNESDAY to "WE",+ DayOfWeek.THURSDAY to "TH", DayOfWeek.FRIDAY to "FR", DayOfWeek.SATURDAY to "SA",+ DayOfWeek.SUNDAY to "SU",+ )+ private val CODE_DAYS = DAY_CODES.entries.associate { (k, v) -> v to k }++ fun parse(raw: String?): Recurrence? {+ if (raw.isNullOrBlank()) return null+ val parts = raw.removePrefix("RRULE:").split(';').mapNotNull { part ->+ val i = part.indexOf('=')+ if (i <= 0) null else part.substring(0, i).uppercase() to part.substring(i + 1)+ }.toMap()+ val interval = (parts["INTERVAL"]?.toIntOrNull() ?: 1).coerceIn(1, MAX_INTERVAL)+ return when (parts["FREQ"]?.uppercase()) {+ "DAILY" -> if (parts[X_FROM].equals("COMPLETION", true)) AfterCompletion(interval) else Daily(interval)+ "WEEKLY" -> Weekly(interval, parseDays(parts["BYDAY"]))+ "MONTHLY" -> Monthly(interval, parts["BYMONTHDAY"]?.toIntOrNull()?.takeIf { it == LAST_DAY || it in 1..31 })+ "YEARLY" -> Yearly(interval)+ else -> null+ }+ }++ private fun parseDays(raw: String?): Set<DayOfWeek> =+ raw.orEmpty().split(',').mapNotNull { CODE_DAYS[it.trim().takeLast(2).uppercase()] }.toSet()+ }+}++/** Smallest k ≥ 1 with k·interval > elapsed. */+private fun stepsPast(elapsed: Int, interval: Int): Int = elapsed / interval + 1++private fun Recurrence.Weekly.nextWeekly(due: LocalDate, base: LocalDate): LocalDate {+ val wanted = days.ifEmpty { setOf(due.dayOfWeek) }+ val anchorWeek = due.minus(due.dayOfWeek.isoDayNumber - 1, DateTimeUnit.DAY)+ var candidate = base.plus(1, DateTimeUnit.DAY)+ while (true) {+ val weekStart = candidate.minus(candidate.dayOfWeek.isoDayNumber - 1, DateTimeUnit.DAY)+ val weeks = anchorWeek.daysUntil(weekStart) / DAYS_PER_WEEK+ if (candidate.dayOfWeek in wanted && weeks % interval == 0) return candidate+ candidate = candidate.plus(1, DateTimeUnit.DAY)+ }+}++private fun Recurrence.Monthly.nextMonthly(due: LocalDate, base: LocalDate): LocalDate {+ val wantedDay = dayOfMonth ?: due.day+ var k = 0+ while (true) {+ val month = LocalDate(due.year, due.month.number, 1).plus(k * interval, DateTimeUnit.MONTH)+ val last = lengthOfMonth(month)+ val day = if (wantedDay == Recurrence.LAST_DAY) last else wantedDay.coerceAtMost(last)+ val candidate = LocalDate(month.year, month.month.number, day)+ if (candidate > base) return candidate+ k+++ }+}++private fun lengthOfMonth(firstOfMonth: LocalDate): Int =+ firstOfMonth.plus(1, DateTimeUnit.MONTH).minus(1, DateTimeUnit.DAY).day++private const val DAYS_PER_WEEK = 7
todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.ktindex 475563dd08..997364e711 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt@@ -39,7 +39,7 @@ class TodoViewModel( } fun toggleDone(todo: Todo) {- viewModelScope.launch(io) { repository.upsert(todo.copy(done = !todo.done)) }+ viewModelScope.launch(io) { repository.setDone(todo, !todo.done) } } fun delete(todo: Todo) {
todo/src/main/java/com/vayunmathur/todo/sync/RelayEnvelopes.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/RelayEnvelopes.kt b/todo/src/main/java/com/vayunmathur/todo/sync/RelayEnvelopes.ktnew file mode 100644index 0000000000..6a39c3e418--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/sync/RelayEnvelopes.kt@@ -0,0 +1,153 @@+package com.vayunmathur.todo.sync++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.security.MessageDigest++/**+ * Relay envelope for one todo record. Field-for-field mirror of everysync's `RemoteTodo`+ * (the bytes the relay log carries).+ *+ * todo/ must not depend on everysync, so the shape is duplicated here. Both sides decode with+ * `ignoreUnknownKeys` and encode without defaults: a field left at its default is omitted, so+ * the hash of a task that never touched a newer field matches what older builds compute.+ * Never rename a key — the other side would silently drop it.+ */+@Serializable+internal data class RelayTodoJson(+ /** Relay sync identity (opaque 32-char id); maps to [Todo.syncId]. */+ val uid: String = "",+ val title: String = "",+ val notes: String = "",+ val done: Boolean = false,+ val dueAt: Long? = null,+ val position: Double = 0.0,+ /** Epoch ms the task was created; part of the adoption content key. */+ val createdAt: Long = 0L,+ val deleted: Boolean = false,+ /** Last local-or-remote modification (epoch ms); drives relay LWW. */+ val updatedAt: Long = 0L,+ val parentUid: String? = null,+ val listUid: String? = null,+ val section: String? = null,+ val tags: List<String> = emptyList(),+ val priority: Int = 0,+ val dueAllDay: Boolean = true,+ val startAt: Long? = null,+ val recurrence: String? = null,+ val reminderAt: Long? = null,+ val completedAt: Long? = null,+ val estimateMinutes: Int? = null,+ val blockedBy: List<String> = emptyList(),+)++/** Relay envelope for one list. Mirror of everysync's `RemoteTodoList`. */+@Serializable+internal data class RelayTodoListJson(+ val uid: String = "",+ val name: String = "",+ val color: Int? = null,+ val icon: String? = null,+ val position: Double = 0.0,+ val sections: List<String> = emptyList(),+ val createdAt: Long = 0L,+ val deleted: Boolean = false,+ val updatedAt: Long = 0L,+)++internal val relayJson = Json { ignoreUnknownKeys = true }++internal fun Todo.toRelayJson(): RelayTodoJson = RelayTodoJson(+ uid = syncId,+ title = title,+ notes = notes,+ done = done,+ dueAt = dueAt,+ position = position,+ createdAt = createdAt,+ deleted = deleted,+ updatedAt = updatedAt,+ parentUid = parentSyncId,+ listUid = listSyncId,+ section = section,+ tags = tags,+ priority = priority,+ dueAllDay = dueAllDay,+ startAt = startAt,+ recurrence = recurrence,+ reminderAt = reminderAt,+ completedAt = completedAt,+ estimateMinutes = estimateMinutes,+ blockedBy = blockedBy,+)++internal fun RelayTodoJson.toTodo(id: Long): Todo = Todo(+ id = id,+ title = title,+ notes = notes,+ done = done,+ position = position,+ dueAt = dueAt,+ createdAt = createdAt,+ syncId = uid,+ updatedAt = updatedAt,+ deleted = deleted,+ parentSyncId = parentUid,+ listSyncId = listUid,+ section = section,+ tags = tags,+ priority = priority,+ dueAllDay = dueAllDay,+ startAt = startAt,+ recurrence = recurrence,+ reminderAt = reminderAt,+ completedAt = completedAt,+ estimateMinutes = estimateMinutes,+ blockedBy = blockedBy,+)++internal fun TodoList.toRelayJson(): RelayTodoListJson = RelayTodoListJson(+ uid = syncId,+ name = name,+ color = color,+ icon = icon,+ position = position,+ sections = sections,+ createdAt = createdAt,+ deleted = deleted,+ updatedAt = updatedAt,+)++internal fun RelayTodoListJson.toTodoList(id: Long): TodoList = TodoList(+ id = id,+ syncId = uid,+ name = name,+ color = color,+ icon = icon,+ position = position,+ sections = sections,+ createdAt = createdAt,+ updatedAt = updatedAt,+ deleted = deleted,+)++/**+ * Merge-compatible content hash: canonical envelope (`uid`, `position`, `updatedAt`,+ * `deleted` stripped) plus the deleted flag, SHA-256 hexed — the same bytes the relay merge+ * driver hashes, so LWW tiebreaks agree on both sides.+ */+internal fun relayContentHash(e: RelayTodoJson): String = sha256Hex(+ relayJson.encodeToString(e.copy(uid = "", position = 0.0, updatedAt = 0L, deleted = false)) ++ "\u0000deleted=${e.deleted}",+)++internal fun relayContentHash(e: RelayTodoListJson): String = sha256Hex(+ relayJson.encodeToString(e.copy(uid = "", position = 0.0, updatedAt = 0L, deleted = false)) ++ "\u0000deleted=${e.deleted}",+)++private fun sha256Hex(text: String): String =+ MessageDigest.getInstance("SHA-256").digest(text.toByteArray(Charsets.UTF_8))+ .joinToString("") { "%02x".format(it) }
todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt b/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.ktindex 85e2ca3d13..f800fe12aa 100644--- a/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt+++ b/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt@@ -1,6 +1,8 @@ package com.vayunmathur.todo.sync import android.content.ContentProvider+import android.content.ContentProviderOperation+import android.content.ContentProviderResult import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor@@ -8,45 +10,31 @@ import android.database.MatrixCursor import android.net.Uri import android.os.Binder import android.os.Process+import androidx.core.net.toUri import com.vayunmathur.library.log.Log import com.vayunmathur.todo.data.SyncSnapshot-import com.vayunmathur.todo.data.Todo import com.vayunmathur.todo.data.TodoRepository-import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking-import kotlinx.serialization.Serializable-import kotlinx.serialization.encodeToString-import kotlinx.serialization.json.Json /**- * Relay IPC surface for the todo vault, consumed by the everysync app's- * TodoSink (same process signature, different app).+ * Relay IPC surface for the todo vault, consumed by the everysync app's `TodoIpcSink` and+ * `TodoListIpcSink` (same signing key, different app). *- * Exposes `content://com.vayunmathur.todo.relay/vault/<id>/todos` and- * `.../snapshots`. The vault id segment is accepted but ignored: this app- * holds a single vault. Every row carries the relay columns- * `syncId, updatedAt, deleted, payloadJson, contentHash`.- *- * `payloadJson` is [RelayTodoJson] — a field-for-field mirror of the relay- * envelope (`RemoteTodo` in everysync): the bytes the relay log carries, also- * hashed by the merge driver, so this provider emits and accepts that shape- * rather than the native [Todo] JSON. This provider must not depend on- * everysync, so the shape is duplicated here; keep the field names in sync- * with `RemoteTodo` (both sides use `ignoreUnknownKeys`, but a renamed key- * would silently drop data).+ * Exposes `content://com.vayunmathur.todo.relay/vault/<id>/{todos,lists,snapshots}`. The+ * vault id segment is accepted but ignored: this app holds a single vault. Every row carries+ * the relay columns `syncId, updatedAt, deleted, payloadJson, contentHash`, where+ * `payloadJson` is [RelayTodoJson] / [RelayTodoListJson]. * * Ops accept both the base table URIs and the op-suffixed URIs the sinks use- * (`.../todos/querySince?since=<ms>`, `.../todos/upsertRaw`,- * `.../todos/deleteByVault`, same for snapshots):- * - `querySince`: rows with `updatedAt` past the `since` query parameter- * (falling back to `selectionArgs[0]`), including tombstones.- * - `upsertRaw`: insert/update with `payloadJson`, preserving the pulled- * `updatedAt` and relay identity (`uid` -> `syncId`). A payload with- * `deleted = true` tombstones the row instead of hard-deleting it, so the- * deletion propagates via the next `querySince`.+ * (`.../querySince?since=<ms>`, `.../upsertRaw`, `.../deleteByVault`):+ * - `querySince`: rows with `updatedAt` past `since` (falling back to `selectionArgs[0]`),+ * tombstones included.+ * - `upsertRaw` (insert/update/bulkInsert): writes the payload verbatim, preserving the+ * pulled `updatedAt` and relay identity. A `deleted = true` payload tombstones the row. * - single delete (`syncId = ?` selection): tombstones the row.- * - `deleteByVault` (or selection-less delete): purge — drops the whole- * table *and* its snapshots.+ * - `deleteByVault` (or selection-less delete): purge — drops the table and its snapshots.+ *+ * `bulkInsert` and `applyBatch` run in one write transaction. */ class RelayTodoProvider : ContentProvider() { @@ -63,40 +51,42 @@ class RelayTodoProvider : ContentProvider() { val COLUMNS = arrayOf(COL_SYNC_ID, COL_UPDATED_AT, COL_DELETED, COL_PAYLOAD_JSON, COL_CONTENT_HASH) private const val PARAM_SINCE = "since"+ private const val EVERYSYNC = "com.vayunmathur.everysync" private const val CODE_TODOS = 1 private const val CODE_SNAPSHOTS = 2+ private const val CODE_LISTS = 3 private const val CODE_TODOS_QUERY = 11+ private const val CODE_LISTS_QUERY = 13 private const val CODE_TODOS_UPSERT = 21 private const val CODE_SNAPSHOTS_UPSERT = 22+ private const val CODE_LISTS_UPSERT = 23 private const val CODE_TODOS_PURGE = 31 private const val CODE_SNAPSHOTS_PURGE = 32+ private const val CODE_LISTS_PURGE = 33 private const val TAG = "RelayTodoProvider" private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply { addURI(AUTHORITY, "vault/*/todos", CODE_TODOS) addURI(AUTHORITY, "vault/*/snapshots", CODE_SNAPSHOTS)+ addURI(AUTHORITY, "vault/*/lists", CODE_LISTS) addURI(AUTHORITY, "vault/*/todos/querySince", CODE_TODOS_QUERY)+ addURI(AUTHORITY, "vault/*/lists/querySince", CODE_LISTS_QUERY) addURI(AUTHORITY, "vault/*/todos/upsertRaw", CODE_TODOS_UPSERT) addURI(AUTHORITY, "vault/*/snapshots/upsertRaw", CODE_SNAPSHOTS_UPSERT)+ addURI(AUTHORITY, "vault/*/lists/upsertRaw", CODE_LISTS_UPSERT) addURI(AUTHORITY, "vault/*/todos/deleteByVault", CODE_TODOS_PURGE) addURI(AUTHORITY, "vault/*/snapshots/deleteByVault", CODE_SNAPSHOTS_PURGE)+ addURI(AUTHORITY, "vault/*/lists/deleteByVault", CODE_LISTS_PURGE) } - private val json = Json { ignoreUnknownKeys = true }-- fun todosUri(vaultId: String): Uri =- Uri.parse("content://$AUTHORITY/vault/$vaultId/todos")-- fun snapshotsUri(vaultId: String): Uri =- Uri.parse("content://$AUTHORITY/vault/$vaultId/snapshots")+ fun todosUri(vaultId: String): Uri = "content://$AUTHORITY/vault/$vaultId/todos".toUri()+ fun listsUri(vaultId: String): Uri = "content://$AUTHORITY/vault/$vaultId/lists".toUri()+ fun snapshotsUri(vaultId: String): Uri = "content://$AUTHORITY/vault/$vaultId/snapshots".toUri() } - private fun repo(): TodoRepository {- val ctx = context ?: error("RelayTodoProvider context null")- return TodoRepository.get(ctx)- }+ private fun repo(): TodoRepository = TodoRepository.get(context ?: error("RelayTodoProvider context null")) override fun onCreate(): Boolean = true @@ -105,8 +95,21 @@ class RelayTodoProvider : ContentProvider() { private fun enforceRelayCaller() { if (Binder.getCallingUid() == Process.myUid()) return val caller = callingPackage- if (caller != "com.vayunmathur.everysync") {- throw SecurityException("RelayTodoProvider: caller $caller is not everysync")+ if (caller != EVERYSYNC) throw SecurityException("RelayTodoProvider: caller $caller is not everysync")+ }++ private fun <T> guarded(op: String, uri: Uri, fallback: T, block: suspend (TodoRepository) -> T): T {+ enforceRelayCaller()+ return runBlocking(repo().io) {+ try {+ block(repo())+ } catch (e: IllegalArgumentException) {+ Log.error(TAG, "$op failed $uri", e)+ fallback+ } catch (e: android.database.SQLException) {+ Log.error(TAG, "$op failed $uri", e)+ fallback+ } } } @@ -116,150 +119,146 @@ class RelayTodoProvider : ContentProvider() { selection: String?, selectionArgs: Array<out String>?, sortOrder: String?,- ): Cursor? {- enforceRelayCaller()- // querySince: `?since=<ms>` query parameter first, selectionArgs[0] as fallback.+ ): Cursor? = guarded("query", uri, null) { repo -> val since = uri.getQueryParameter(PARAM_SINCE)?.toLongOrNull() ?: selectionArgs?.firstOrNull()?.toLongOrNull() ?: 0L- return runBlocking(Dispatchers.IO) {- try {- when (uriMatcher.match(uri)) {- CODE_TODOS, CODE_TODOS_QUERY -> cursorFromTodos(repo().getUpdatedSince(since))- CODE_SNAPSHOTS -> cursorFromSnapshots(repo().getAllSnapshots())- else -> null- }- } catch (e: IllegalArgumentException) {- Log.error(TAG, "query failed $uri", e)- null- } catch (e: android.database.SQLException) {- Log.error(TAG, "query failed $uri", e)- null+ when (uriMatcher.match(uri)) {+ CODE_TODOS, CODE_TODOS_QUERY -> cursorOf(repo.getUpdatedSince(since).map { it.toRelayJson() }) {+ arrayOf(it.uid, it.updatedAt, it.deleted.toInt(), relayJson.encodeToString(it), relayContentHash(it))+ }+ CODE_LISTS, CODE_LISTS_QUERY -> cursorOf(repo.getListsUpdatedSince(since).map { it.toRelayJson() }) {+ arrayOf(it.uid, it.updatedAt, it.deleted.toInt(), relayJson.encodeToString(it), relayContentHash(it))+ }+ CODE_SNAPSHOTS -> cursorOf(repo.getTodoSnapshots() + repo.getListSnapshots()) {+ arrayOf(it.syncId, it.localUpdatedAt, 0, "", it.contentHash) }+ else -> null } } override fun insert(uri: Uri, values: ContentValues?): Uri? {- enforceRelayCaller() val v = values ?: return null- return runBlocking(Dispatchers.IO) {- try {- when (uriMatcher.match(uri)) {- CODE_TODOS, CODE_TODOS_UPSERT -> applyRelayJson(v)- CODE_SNAPSHOTS, CODE_SNAPSHOTS_UPSERT -> upsertSnapshot(v)- else -> null- }?.let { Uri.withAppendedPath(uri, it) }- } catch (e: IllegalArgumentException) {- Log.error(TAG, "insert failed $uri", e)- null- } catch (e: android.database.SQLException) {- Log.error(TAG, "insert failed $uri", e)- null- }- }+ return guarded("insert", uri, null) { repo -> handleUpsert(repo, uri, v)?.let { Uri.withAppendedPath(uri, it) } } } + override fun bulkInsert(uri: Uri, values: Array<out ContentValues>): Int =+ guarded("bulkInsert", uri, 0) { repo ->+ repo.inTransaction { values.count { handleUpsert(repo, uri, it) != null } }+ }+ override fun update( uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?, ): Int {- enforceRelayCaller() val v = values ?: return 0- return runBlocking(Dispatchers.IO) {- try {- when (uriMatcher.match(uri)) {- CODE_TODOS, CODE_TODOS_UPSERT -> if (applyRelayJson(v) != null) 1 else 0- CODE_SNAPSHOTS, CODE_SNAPSHOTS_UPSERT -> if (upsertSnapshot(v) != null) 1 else 0- else -> 0- }- } catch (e: IllegalArgumentException) {- Log.error(TAG, "update failed $uri", e)- 0- } catch (e: android.database.SQLException) {- Log.error(TAG, "update failed $uri", e)- 0- }- }+ return guarded("update", uri, 0) { repo -> if (handleUpsert(repo, uri, v) != null) 1 else 0 } } - override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {- enforceRelayCaller()- return runBlocking(Dispatchers.IO) {- try {- val repo = repo()- when (uriMatcher.match(uri)) {- CODE_TODOS_PURGE -> {- repo.purge()- repo.deleteAllSnapshots()- 0- }- CODE_SNAPSHOTS_PURGE -> {- repo.deleteAllSnapshots()- 0- }- // Single delete (`syncId = ?`): tombstone the row so the- // deletion propagates via querySince. Selection-less base- // delete is the legacy purge spelling.- CODE_TODOS -> {- val syncId = if (selection != null) selectionArgs?.firstOrNull() else null- if (syncId != null) {- repo.tombstoneBySyncId(syncId)- } else {- repo.purge()- repo.deleteAllSnapshots()- 0+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =+ guarded("delete", uri, 0) { repo -> repo.inTransaction { handleDelete(repo, uri, selection, selectionArgs) } }++ override fun applyBatch(operations: ArrayList<ContentProviderOperation>): Array<ContentProviderResult> =+ guarded("applyBatch", Uri.EMPTY, emptyArray()) { repo ->+ repo.inTransaction {+ val results = ArrayList<ContentProviderResult>(operations.size)+ for ((index, op) in operations.withIndex()) {+ val prior = results.toTypedArray()+ results += when {+ op.isDelete -> {+ val args = op.resolveSelectionArgsBackReferences(prior, index)+ val selection = if (args.isNullOrEmpty()) null else "$COL_SYNC_ID = ?"+ ContentProviderResult(handleDelete(repo, op.uri, selection, args)) }- }- CODE_SNAPSHOTS -> {- val syncId = selectionArgs?.firstOrNull()- if (syncId != null) {- repo.deleteSnapshotBySyncId(syncId)- 1- } else {- repo.deleteAllSnapshots()- 0+ else -> {+ val values: ContentValues = op.resolveValueBackReferences(prior, index) ?: ContentValues()+ val id = handleUpsert(repo, op.uri, values)+ ContentProviderResult(if (id != null) 1 else 0) } }- else -> 0 }- } catch (e: IllegalArgumentException) {- Log.error(TAG, "delete failed $uri", e)- 0- } catch (e: android.database.SQLException) {- Log.error(TAG, "delete failed $uri", e)- 0+ results.toTypedArray() } }- } override fun getType(uri: Uri): String? = when (uriMatcher.match(uri)) { CODE_TODOS, CODE_TODOS_QUERY -> "vnd.android.cursor.dir/vnd.com.vayunmathur.todo.todo"+ CODE_LISTS, CODE_LISTS_QUERY -> "vnd.android.cursor.dir/vnd.com.vayunmathur.todo.list" CODE_SNAPSHOTS -> "vnd.android.cursor.dir/vnd.com.vayunmathur.todo.snapshot" else -> null } - /**- * Applies one pulled relay record. `uid` is the sync identity. A `deleted`- * payload tombstones the row (never hard-deletes) so the deletion- * propagates. Rebinds onto the existing row id so a pull updates in place- * instead of duplicating.- */- private suspend fun applyRelayJson(v: ContentValues): String? {+ private suspend fun handleUpsert(repo: TodoRepository, uri: Uri, v: ContentValues): String? =+ when (uriMatcher.match(uri)) {+ CODE_TODOS, CODE_TODOS_UPSERT -> applyRelayTodo(repo, v)+ CODE_LISTS, CODE_LISTS_UPSERT -> applyRelayList(repo, v)+ CODE_SNAPSHOTS, CODE_SNAPSHOTS_UPSERT -> upsertSnapshot(repo, v)+ else -> null+ }++ private suspend fun handleDelete(+ repo: TodoRepository,+ uri: Uri,+ selection: String?,+ selectionArgs: Array<out String>?,+ ): Int {+ val syncId = selectionArgs?.firstOrNull()?.takeIf { selection != null || uriMatcher.match(uri) == CODE_SNAPSHOTS }+ return when (uriMatcher.match(uri)) {+ CODE_TODOS_PURGE -> purgeTodos(repo)+ CODE_LISTS_PURGE -> purgeLists(repo)+ CODE_SNAPSHOTS_PURGE -> {+ repo.deleteTodoSnapshots()+ repo.deleteListSnapshots()+ 0+ }+ CODE_TODOS -> if (syncId != null) repo.tombstoneBySyncId(syncId) else purgeTodos(repo)+ CODE_LISTS -> if (syncId != null) repo.tombstoneListBySyncId(syncId) else purgeLists(repo)+ CODE_SNAPSHOTS -> if (syncId != null) {+ repo.deleteSnapshotBySyncId(syncId)+ 1+ } else {+ repo.deleteTodoSnapshots()+ repo.deleteListSnapshots()+ 0+ }+ else -> 0+ }+ }++ private suspend fun purgeTodos(repo: TodoRepository): Int {+ repo.purge()+ repo.deleteTodoSnapshots()+ return 0+ }++ private suspend fun purgeLists(repo: TodoRepository): Int {+ repo.purgeLists()+ repo.deleteListSnapshots()+ return 0+ }++ /** Applies one pulled record, rebinding onto the existing row so a pull updates in place. */+ private suspend fun applyRelayTodo(repo: TodoRepository, v: ContentValues): String? {+ val payload = v.getAsString(COL_PAYLOAD_JSON) ?: return null+ val remote = runCatching { relayJson.decodeFromString<RelayTodoJson>(payload) }.getOrNull() ?: return null+ if (remote.uid.isBlank()) return null+ repo.upsertRaw(remote.toTodo(repo.getBySyncId(remote.uid)?.id ?: 0L))+ return remote.uid+ }++ private suspend fun applyRelayList(repo: TodoRepository, v: ContentValues): String? { val payload = v.getAsString(COL_PAYLOAD_JSON) ?: return null- val remote = runCatching { json.decodeFromString<RelayTodoJson>(payload) }.getOrNull()- ?: return null+ val remote = runCatching { relayJson.decodeFromString<RelayTodoListJson>(payload) }.getOrNull() ?: return null if (remote.uid.isBlank()) return null- val repo = repo()- val existing = repo.getBySyncId(remote.uid)- repo.upsertRaw(remote.toTodo(existing?.id ?: 0L))+ repo.upsertListRaw(remote.toTodoList(repo.getListBySyncId(remote.uid)?.id ?: 0L)) return remote.uid } - private suspend fun upsertSnapshot(v: ContentValues): String? {+ private suspend fun upsertSnapshot(repo: TodoRepository, v: ContentValues): String? { val syncId = v.getAsString(COL_SYNC_ID) ?: return null- repo().upsertSnapshot(+ repo.upsertSnapshot( SyncSnapshot( syncId = syncId, kind = v.getAsString("kind").orEmpty(),@@ -272,94 +271,8 @@ class RelayTodoProvider : ContentProvider() { return syncId } - private fun cursorFromTodos(todos: List<Todo>): MatrixCursor {- val c = MatrixCursor(COLUMNS)- for (t in todos) {- val relay = t.toRelayJson()- val payload = json.encodeToString(relay)- c.addRow(- arrayOf<Any?>(- t.syncId,- t.updatedAt,- if (t.deleted) 1 else 0,- payload,- relayContentHash(relay),- ),- )- }- return c- }-- private fun cursorFromSnapshots(snapshots: List<SyncSnapshot>): MatrixCursor {- val c = MatrixCursor(COLUMNS)- for (s in snapshots) {- c.addRow(arrayOf<Any?>(s.syncId, s.localUpdatedAt, 0, "", s.contentHash))- }- return c- }+ private fun <T> cursorOf(rows: List<T>, toRow: (T) -> Array<Any?>): MatrixCursor =+ MatrixCursor(COLUMNS).apply { rows.forEach { addRow(toRow(it)) } } - /**- * Merge-compatible content hash: canonical envelope (`uid`, `position`,- * `updatedAt`, `deleted` stripped) plus the deleted flag, SHA-256 hexed —- * the same bytes the relay merge driver hashes, so LWW tiebreaks agree on- * both sides.- */- private fun relayContentHash(e: RelayTodoJson): String {- val canonical = json.encodeToString(- e.copy(uid = "", position = 0.0, updatedAt = 0L, deleted = false),- ) + "\u0000deleted=${e.deleted}"- val digest = java.security.MessageDigest.getInstance("SHA-256")- return digest.digest(canonical.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }- }+ private fun Boolean.toInt(): Int = if (this) 1 else 0 }--/**- * Relay envelope for one todo record. Field-for-field mirror of everysync's- * `RemoteTodo` (the bytes the relay log carries): title / notes / done /- * dueAt / position / createdAt.- *- * todo/ must not depend on everysync, so the shape is duplicated here.- * Both sides decode with `ignoreUnknownKeys`, but keep the names in sync —- * a renamed key here would silently drop data on the relay side.- */-@Serializable-internal data class RelayTodoJson(- /** Relay sync identity (opaque 32-char id); maps to [Todo.syncId]. */- val uid: String = "",- val title: String = "",- val notes: String = "",- val done: Boolean = false,- /** Epoch ms the task is due, or null. */- val dueAt: Long? = null,- val position: Double = 0.0,- /** Epoch ms the task was created; part of the adoption content key. */- val createdAt: Long = 0L,- val deleted: Boolean = false,- /** Last local-or-remote modification (epoch ms); drives relay LWW. */- val updatedAt: Long = 0L,-)--internal fun Todo.toRelayJson(): RelayTodoJson = RelayTodoJson(- uid = syncId,- title = title,- notes = notes,- done = done,- dueAt = dueAt,- position = position,- createdAt = createdAt,- deleted = deleted,- updatedAt = updatedAt,-)--internal fun RelayTodoJson.toTodo(id: Long): Todo = Todo(- id = id,- title = title,- notes = notes,- done = done,- position = position,- dueAt = dueAt,- createdAt = createdAt,- syncId = uid,- updatedAt = updatedAt,- deleted = deleted,-)
todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.ktindex 9a8731bde1..7ef7e13420 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt@@ -29,6 +29,8 @@ import com.vayunmathur.library.ui.rememberDatePickerState import com.vayunmathur.todo.R import com.vayunmathur.todo.platform.TodoActions import com.vayunmathur.todo.platform.TodoUiState+import com.vayunmathur.todo.domain.DueDates+import kotlinx.datetime.TimeZone import kotlin.time.Instant import com.vayunmathur.library.ui.R as UiR @@ -97,13 +99,16 @@ fun TodoDetailScreen( } if (showDuePicker) {- val pickerState = rememberDatePickerState(initialSelectedDateMillis = state.dueAt)+ val zone = TimeZone.currentSystemDefault()+ val pickerState = rememberDatePickerState(+ initialSelectedDateMillis = state.dueAt?.let { DueDates.toPickerMillis(it, zone) },+ ) DatePickerDialog( onDismissRequest = { showDuePicker = false }, confirmButton = { Button( onClick = {- actions.setDueAt(pickerState.selectedDateMillis)+ actions.setDueAt(pickerState.selectedDateMillis?.let { DueDates.fromPickerMillis(it, zone) }) showDuePicker = false }, enabled = pickerState.selectedDateMillis != null,
todo/src/test/java/com/vayunmathur/todo/data/TodoMigrationTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/data/TodoMigrationTest.kt b/todo/src/test/java/com/vayunmathur/todo/data/TodoMigrationTest.ktnew file mode 100644index 0000000000..33fd3434dc--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/data/TodoMigrationTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.todo.data++import androidx.sqlite.SQLiteConnection+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.sqlite.execSQL+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import java.io.File+import java.util.TimeZone+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Runs the real v2→v3 migration against a v2 database and checks the result matches the+ * exported v3 schema Room validates on open.+ */+class TodoMigrationTest {+ private lateinit var conn: SQLiteConnection+ private val savedZone = TimeZone.getDefault()++ @BeforeTest+ fun setUp() {+ TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"))+ conn = BundledSQLiteDriver().open(":memory:")+ conn.execSQL(+ "CREATE TABLE `Todo` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, " ++ "`done` INTEGER NOT NULL, `position` REAL NOT NULL, `dueAt` INTEGER, `syncId` TEXT NOT NULL, " ++ "`updatedAt` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `notes` TEXT NOT NULL DEFAULT '', " ++ "`createdAt` INTEGER NOT NULL DEFAULT 0)",+ )+ conn.execSQL(+ "CREATE TABLE `SyncSnapshot` (`syncId` TEXT NOT NULL, `kind` TEXT NOT NULL, `contentHash` TEXT NOT NULL, " ++ "`localUpdatedAt` INTEGER NOT NULL, `remoteModified` INTEGER NOT NULL, " ++ "`lastSyncedAt` INTEGER NOT NULL, PRIMARY KEY(`syncId`))",+ )+ }++ @AfterTest+ fun tearDown() {+ conn.close()+ TimeZone.setDefault(savedZone)+ }++ private fun migrate() = runBlocking { TodoMigrations.all.single { it.startVersion == 2 }.migrate(conn) }++ private fun columns(table: String): Set<String> {+ val out = mutableSetOf<String>()+ conn.prepare("PRAGMA table_info(`$table`)").use { while (it.step()) out += it.getText(1) }+ return out+ }++ private fun schemaColumns(table: String): Set<String> {+ val file = File("schemas/com.vayunmathur.todo.data.TodoDatabase/3.json")+ val entities = Json.parseToJsonElement(file.readText()).jsonObject["database"]!!.jsonObject["entities"]!!.jsonArray+ val entity = entities.first { it.jsonObject["tableName"]!!.jsonPrimitive.content == table }.jsonObject+ return entity["fields"]!!.jsonArray.map { it.jsonObject["columnName"]!!.jsonPrimitive.content }.toSet()+ }++ @Test+ fun `migrated tables carry exactly the v3 columns`() {+ migrate()+ assertEquals(schemaColumns("Todo"), columns("Todo"))+ assertEquals(schemaColumns("TodoList"), columns("TodoList"))+ }++ @Test+ fun `existing rows get v3 defaults`() {+ conn.execSQL("INSERT INTO Todo (title, done, position, syncId, updatedAt, deleted) VALUES ('a', 0, 1.0, 's1', 5, 0)")+ migrate()+ conn.prepare("SELECT tags, priority, dueAllDay, blockedBy, listSyncId FROM Todo").use {+ it.step()+ assertEquals("[]", it.getText(0))+ assertEquals(0L, it.getLong(1))+ assertEquals(1L, it.getLong(2))+ assertEquals("[]", it.getText(3))+ assertEquals(true, it.isNull(4))+ }+ }++ @Test+ fun `legacy utc-midnight due dates become local midnight of the same date`() {+ // 2026-10-14T00:00Z, as the old date picker stored it.+ val utcMidnight = 1_791_936_000_000L+ conn.execSQL("INSERT INTO Todo (title, done, position, dueAt, syncId, updatedAt, deleted) VALUES ('a', 0, 1.0, $utcMidnight, 's1', 5, 0)")+ migrate()+ conn.prepare("SELECT dueAt FROM Todo").use {+ it.step()+ // 2026-10-14T00:00-07:00 (PDT).+ assertEquals(utcMidnight + 7 * 3_600_000L, it.getLong(0))+ }+ }++ @Test+ fun `non-midnight due values are left alone`() {+ val odd = 1_791_936_000_123L+ conn.execSQL("INSERT INTO Todo (title, done, position, dueAt, syncId, updatedAt, deleted) VALUES ('a', 0, 1.0, $odd, 's1', 5, 0)")+ migrate()+ conn.prepare("SELECT dueAt FROM Todo").use {+ it.step()+ assertEquals(odd, it.getLong(0))+ }+ }+}
todo/src/test/java/com/vayunmathur/todo/domain/CompletionTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/domain/CompletionTest.kt b/todo/src/test/java/com/vayunmathur/todo/domain/CompletionTest.ktnew file mode 100644index 0000000000..865d478829--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/domain/CompletionTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.todo.domain++import com.vayunmathur.todo.data.Todo+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class CompletionTest {+ private val zone = TimeZone.of("America/Los_Angeles")+ private fun day(y: Int, m: Int, d: Int) = DueDates.startOfDay(LocalDate(y, m, d), zone)+ private fun at(y: Int, m: Int, d: Int, h: Int) = DueDates.at(LocalDate(y, m, d), LocalTime(h, 0), zone)++ @Test+ fun `a one-off task is simply marked done`() {+ val done = Completion.complete(Todo(title = "x", dueAt = day(2026, 3, 1)), now = 5L, zone = zone)+ assertTrue(done.done)+ assertEquals(5L, done.completedAt)+ assertEquals(day(2026, 3, 1), done.dueAt)+ }++ @Test+ fun `a repeating task rolls forward and stays open`() {+ val todo = Todo(title = "x", dueAt = day(2026, 3, 1), recurrence = "FREQ=DAILY")+ val next = Completion.complete(todo, now = at(2026, 3, 1, 10), zone = zone)+ assertFalse(next.done)+ assertEquals(day(2026, 3, 2), next.dueAt)+ assertTrue(Completion.rolledForward(todo, next))+ }++ @Test+ fun `timed occurrences keep their wall-clock time across a DST change`() {+ // DST starts 2026-03-08 in Los Angeles.+ val todo = Todo(title = "x", dueAt = at(2026, 3, 7, 9), dueAllDay = false, recurrence = "FREQ=DAILY")+ val next = Completion.complete(todo, now = at(2026, 3, 7, 9), zone = zone)+ assertEquals(at(2026, 3, 8, 9), next.dueAt)+ }++ @Test+ fun `reminder and start keep their offset from the due date`() {+ val due = at(2026, 3, 2, 9)+ val todo = Todo(+ dueAt = due,+ dueAllDay = false,+ reminderAt = due - 3_600_000L,+ startAt = due - 86_400_000L,+ recurrence = "FREQ=WEEKLY",+ )+ val next = Completion.complete(todo, now = due, zone = zone)+ assertEquals(next.dueAt!! - 3_600_000L, next.reminderAt)+ assertEquals(next.dueAt!! - 86_400_000L, next.startAt)+ }++ @Test+ fun `after-completion repeats work without a due date`() {+ val todo = Todo(recurrence = "FREQ=DAILY;INTERVAL=3;X-FROM=COMPLETION")+ val next = Completion.complete(todo, now = at(2026, 3, 1, 12), zone = zone)+ assertEquals(day(2026, 3, 4), next.dueAt)+ assertFalse(next.done)+ }++ @Test+ fun `a fixed repeat without a due date just completes`() {+ val done = Completion.complete(Todo(recurrence = "FREQ=DAILY"), now = 1L, zone = zone)+ assertTrue(done.done)+ }++ @Test+ fun `uncomplete clears the completion stamp`() {+ val todo = Completion.uncomplete(Todo(done = true, completedAt = 4L))+ assertFalse(todo.done)+ assertEquals(null, todo.completedAt)+ }+}
todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt b/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.ktnew file mode 100644index 0000000000..a0ecdc7641--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.todo.domain++import kotlinx.datetime.DayOfWeek+import kotlinx.datetime.LocalDate+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class RecurrenceTest {+ private fun d(y: Int, m: Int, day: Int) = LocalDate(y, m, day)++ @Test+ fun `daily advances past both the due date and today`() {+ val r = Recurrence.Daily()+ assertEquals(d(2026, 3, 2), r.nextDate(due = d(2026, 3, 1), today = d(2026, 3, 1)))+ // Three days overdue: lands tomorrow, not back in the past.+ assertEquals(d(2026, 3, 5), r.nextDate(due = d(2026, 3, 1), today = d(2026, 3, 4)))+ // Completed early: next is after the due date.+ assertEquals(d(2026, 3, 11), r.nextDate(due = d(2026, 3, 10), today = d(2026, 3, 4)))+ }++ @Test+ fun `every n days stays on the cadence`() {+ val r = Recurrence.Daily(3)+ assertEquals(d(2026, 3, 7), r.nextDate(due = d(2026, 3, 1), today = d(2026, 3, 5)))+ }++ @Test+ fun `weekly on chosen days picks the next matching weekday`() {+ val r = Recurrence.Weekly(1, setOf(DayOfWeek.MONDAY, DayOfWeek.THURSDAY))+ // 2026-03-02 is a Monday.+ assertEquals(d(2026, 3, 5), r.nextDate(due = d(2026, 3, 2), today = d(2026, 3, 2)))+ assertEquals(d(2026, 3, 9), r.nextDate(due = d(2026, 3, 5), today = d(2026, 3, 5)))+ }++ @Test+ fun `every other week skips the off week`() {+ val r = Recurrence.Weekly(2, setOf(DayOfWeek.MONDAY))+ assertEquals(d(2026, 3, 16), r.nextDate(due = d(2026, 3, 2), today = d(2026, 3, 2)))+ }++ @Test+ fun `weekly with no days repeats the due weekday`() {+ assertEquals(d(2026, 3, 9), Recurrence.Weekly().nextDate(d(2026, 3, 2), d(2026, 3, 2)))+ }++ @Test+ fun `monthly clamps to short months and keeps the anchor day afterwards`() {+ val r = Recurrence.Monthly()+ assertEquals(d(2026, 2, 28), r.nextDate(due = d(2026, 1, 31), today = d(2026, 1, 31)))+ assertEquals(d(2026, 3, 31), r.nextDate(due = d(2026, 1, 31), today = d(2026, 2, 28)))+ }++ @Test+ fun `monthly on the last day`() {+ val r = Recurrence.Monthly(1, Recurrence.LAST_DAY)+ assertEquals(d(2028, 2, 29), r.nextDate(due = d(2028, 1, 31), today = d(2028, 1, 31)))+ }++ @Test+ fun `yearly handles leap days`() {+ assertEquals(d(2029, 2, 28), Recurrence.Yearly().nextDate(due = d(2028, 2, 29), today = d(2028, 2, 29)))+ }++ @Test+ fun `after completion counts from today`() {+ val r = Recurrence.AfterCompletion(10)+ assertEquals(d(2026, 3, 14), r.nextDate(due = d(2026, 1, 1), today = d(2026, 3, 4)))+ }++ @Test+ fun `serialize and parse round trip`() {+ val all = listOf(+ Recurrence.Daily(),+ Recurrence.Daily(4),+ Recurrence.Weekly(2, setOf(DayOfWeek.MONDAY, DayOfWeek.FRIDAY)),+ Recurrence.Monthly(1, 15),+ Recurrence.Monthly(3, Recurrence.LAST_DAY),+ Recurrence.Yearly(),+ Recurrence.AfterCompletion(7),+ )+ for (r in all) assertEquals(r, Recurrence.parse(r.serialize()), r.serialize())+ }++ @Test+ fun `serialized forms are standard rrules`() {+ assertEquals("FREQ=WEEKLY;BYDAY=MO,FR", Recurrence.Weekly(1, setOf(DayOfWeek.FRIDAY, DayOfWeek.MONDAY)).serialize())+ assertNull(Recurrence.AfterCompletion(3).toRRule())+ assertEquals("FREQ=MONTHLY;BYMONTHDAY=-1", Recurrence.Monthly(1, -1).toRRule())+ }++ @Test+ fun `garbage parses to null and bad intervals are clamped`() {+ assertNull(Recurrence.parse(null))+ assertNull(Recurrence.parse(""))+ assertNull(Recurrence.parse("FREQ=HOURLY"))+ assertEquals(Recurrence.Daily(1), Recurrence.parse("RRULE:FREQ=DAILY;INTERVAL=0"))+ }+}
todo/src/test/java/com/vayunmathur/todo/sync/RelayEnvelopeCompatTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/sync/RelayEnvelopeCompatTest.kt b/todo/src/test/java/com/vayunmathur/todo/sync/RelayEnvelopeCompatTest.ktnew file mode 100644index 0000000000..a49252f078--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/sync/RelayEnvelopeCompatTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.todo.sync++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.security.MessageDigest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals++/**+ * Cross-version safety for the v3 envelope: tasks that never touch a new field must hash+ * exactly like the pre-v3 envelope did, or every existing task would look edited.+ */+class RelayEnvelopeCompatTest {++ /** The pre-v3 envelope, verbatim. */+ @Serializable+ private data class LegacyEnvelope(+ val uid: String = "",+ val title: String = "",+ val notes: String = "",+ val done: Boolean = false,+ val dueAt: Long? = null,+ val position: Double = 0.0,+ val createdAt: Long = 0L,+ val deleted: Boolean = false,+ val updatedAt: Long = 0L,+ )++ private val json = Json { ignoreUnknownKeys = true }++ private fun legacyHash(e: LegacyEnvelope): String {+ val canonical = json.encodeToString(e.copy(uid = "", position = 0.0, updatedAt = 0L, deleted = false)) ++ "\u0000deleted=${e.deleted}"+ return MessageDigest.getInstance("SHA-256").digest(canonical.toByteArray()).joinToString("") { "%02x".format(it) }+ }++ @Test+ fun `a legacy-shaped task hashes exactly as before`() {+ val todo = Todo(title = "Milk", notes = "2%", done = true, dueAt = 5L, createdAt = 9L, syncId = "u1", updatedAt = 3L)+ val legacy = LegacyEnvelope(uid = "u1", title = "Milk", notes = "2%", done = true, dueAt = 5L, createdAt = 9L, updatedAt = 3L)+ assertEquals(legacyHash(legacy), relayContentHash(todo.toRelayJson()))+ }++ @Test+ fun `a legacy payload decodes with v3 defaults`() {+ val raw = json.encodeToString(LegacyEnvelope(uid = "u1", title = "t", dueAt = 7L))+ val todo = relayJson.decodeFromString<RelayTodoJson>(raw).toTodo(0)+ assertEquals(true, todo.dueAllDay)+ assertEquals(emptyList(), todo.tags)+ assertEquals(null, todo.listSyncId)+ assertEquals(0, todo.priority)+ }++ @Test+ fun `every v3 field survives the round trip`() {+ val todo = Todo(+ syncId = "u1",+ title = "t",+ parentSyncId = "p",+ listSyncId = "l",+ section = "s",+ tags = listOf("home", "errand"),+ priority = 2,+ dueAt = 100L,+ dueAllDay = false,+ startAt = 50L,+ recurrence = "FREQ=WEEKLY;BYDAY=MO",+ reminderAt = 90L,+ completedAt = 80L,+ estimateMinutes = 25,+ blockedBy = listOf("b"),+ )+ val back = relayJson.decodeFromString<RelayTodoJson>(relayJson.encodeToString(todo.toRelayJson())).toTodo(0)+ assertEquals(todo.copy(id = 0), back)+ }++ @Test+ fun `editing a new field changes the hash but reordering does not`() {+ val base = Todo(syncId = "u1", title = "t").toRelayJson()+ assertNotEquals(relayContentHash(base), relayContentHash(base.copy(priority = 1)))+ assertEquals(relayContentHash(base), relayContentHash(base.copy(position = 99.0)))+ }++ @Test+ fun `lists round trip and ignore position in the hash`() {+ val list = TodoList(syncId = "l1", name = "Work", color = 0xFF00FF00.toInt(), icon = "work", sections = listOf("A", "B"))+ val relay = list.toRelayJson()+ assertEquals(list.copy(id = 3), relayJson.decodeFromString<RelayTodoListJson>(relayJson.encodeToString(relay)).toTodoList(3))+ assertEquals(relayContentHash(relay), relayContentHash(relay.copy(position = 7.0)))+ }+}