Modern Apps git

← Modern-Apps.git

everysync: unified E2EE relay sync for contacts, calendars, passwords, notes, todos

Commit
de4ba9de1f4d126543e793d337eaa422b2314fce
Author
vayun-mathur <[email protected]>
When
2026-10-10 02:28 UTC (1 month ago)
Parents
9b04c09

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 50d761807b..571cb69a74 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -62,6 +62,7 @@ body:         - sudoku         - taxi         - things+        - todo         - tools:holidaygen         - translate         - travel
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex f3177467ef..a1079f087b 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -62,6 +62,7 @@ body:         - sudoku         - taxi         - things+        - todo         - tools:holidaygen         - translate         - travel
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex 74d93fe575..e81c3a8265 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['alchemist', 'appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'musicbrainz', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'tools:holidaygen', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['alchemist', 'appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'musicbrainz', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'tools:holidaygen', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
README.md
diff --git a/README.md b/README.mdindex f98ecd867b..8371724147 100644--- a/README.md+++ b/README.md@@ -93,6 +93,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Speech Recognizer** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/speech) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.speech/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Speech%20Recognizer&packageName=com.vayunmathur.speech&apk=speech-release.apk) | | **Taxi (US and Canada only)** | MA-E | [Homepage](https://ma.vayunmathur.com/apps/taxi) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://ma.vayunmathur.com/fdroid) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Taxi&packageName=com.vayunmathur.taxi&apk=taxi-release.apk) | | **Things** | MA-3 | [Homepage](https://ma.vayunmathur.com/apps/things) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.things/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Things&packageName=com.vayunmathur.things&apk=things-release.apk) |+| **Todo** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/todo) | In Progress | In Progress | | **Translate** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/translate) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.translate/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Translate&packageName=com.vayunmathur.translate&apk=translate-release.apk) | | **Travel** | MA-E | [Homepage](https://ma.vayunmathur.com/apps/travel) | In Progress | In Progress | | **Tuner** | MA-3 | [Homepage](https://ma.vayunmathur.com/apps/tuner) | In Progress | In Progress |
everysync/AGENTS.md
diff --git a/everysync/AGENTS.md b/everysync/AGENTS.mdindex 5804ea12e6..4a592a1fe6 100644--- a/everysync/AGENTS.md+++ b/everysync/AGENTS.md@@ -7,7 +7,7 @@ _Install: ./install everysync (dev by default)._ - Gradle: :everysync / dir: everysync/ - Package roots present: ui, data, domain, platform, network, provider, auth, sync - Entry files: MainActivity.kt, Route.kt, Navigation.kt, EverySyncApplication.kt-- Deps: :library:network+- Deps: :library:network, :library:e2ee-p2p - Metadata: metadata_data/everysync.md (present) - Rust: no / screenshotTest: yes @@ -20,42 +20,48 @@ _Install: ./install everysync (dev by default)._ - com/vayunmathur/everysync/auth/AccountConfig.kt - com/vayunmathur/everysync/auth/AccountStore.kt - com/vayunmathur/everysync/auth/Authenticator.kt-- com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt-- com/vayunmathur/everysync/auth/OAuthConfig.kt-- com/vayunmathur/everysync/auth/OAuthManager.kt - com/vayunmathur/everysync/auth/TokenStore.kt - com/vayunmathur/everysync/data/RemoteModels.kt - com/vayunmathur/everysync/data/Settings.kt+- com/vayunmathur/everysync/data/VaultStore.kt - com/vayunmathur/everysync/data/sink/CalendarSink.kt - com/vayunmathur/everysync/data/sink/ContactsSink.kt-- com/vayunmathur/everysync/data/sink/HealthSink.kt+- com/vayunmathur/everysync/data/sink/NoteSink.kt+- com/vayunmathur/everysync/data/sink/PasswordSink.kt+- com/vayunmathur/everysync/data/sink/TodoIpcSink.kt+- com/vayunmathur/everysync/data/sink/TodoSink.kt - com/vayunmathur/everysync/domain/format/ICalendar.kt - com/vayunmathur/everysync/domain/format/VCard.kt-- com/vayunmathur/everysync/network/remote/DavClient.kt-- com/vayunmathur/everysync/network/remote/DavSync.kt-- com/vayunmathur/everysync/network/remote/GoogleHealthClient.kt+- com/vayunmathur/everysync/network/remote/RelayCursorStore.kt+- com/vayunmathur/everysync/network/remote/RelaySync.kt - com/vayunmathur/everysync/platform/BootReceiver.kt - com/vayunmathur/everysync/platform/EverySyncUiContract.kt+- com/vayunmathur/everysync/platform/EverySyncVaults.kt - com/vayunmathur/everysync/platform/EverySyncViewModel.kt - com/vayunmathur/everysync/provider/DataType.kt - com/vayunmathur/everysync/provider/ProviderRegistry.kt - com/vayunmathur/everysync/provider/SyncProvider.kt - com/vayunmathur/everysync/provider/SyncState.kt-- com/vayunmathur/everysync/provider/impl/DavProvider.kt-- com/vayunmathur/everysync/provider/impl/DavProviders.kt-- com/vayunmathur/everysync/provider/impl/GoogleProvider.kt-- com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt-- com/vayunmathur/everysync/sync/EverySyncAdapter.kt+- com/vayunmathur/everysync/provider/impl/E2eeProvider.kt+- com/vayunmathur/everysync/sync/OwnerTransfer.kt+- com/vayunmathur/everysync/sync/RelayBlobStore.kt+- com/vayunmathur/everysync/sync/RelayMerge.kt - com/vayunmathur/everysync/sync/SyncEngine.kt - com/vayunmathur/everysync/sync/SyncScheduler.kt - com/vayunmathur/everysync/sync/SyncStatus.kt - com/vayunmathur/everysync/sync/SyncWorker.kt+- com/vayunmathur/everysync/sync/VaultKeys.kt+- com/vayunmathur/everysync/sync/VaultRoster.kt+- com/vayunmathur/everysync/sync/adapters/CalendarKind.kt+- com/vayunmathur/everysync/sync/adapters/ContactKind.kt+- com/vayunmathur/everysync/sync/adapters/NoteKind.kt+- com/vayunmathur/everysync/sync/adapters/PasswordKind.kt+- com/vayunmathur/everysync/sync/adapters/TodoKind.kt - com/vayunmathur/everysync/ui/AccountDetailScreen.kt - com/vayunmathur/everysync/ui/AccountsScreen.kt - com/vayunmathur/everysync/ui/AddAccountScreen.kt-- com/vayunmathur/everysync/ui/DavLoginScreen.kt-- com/vayunmathur/everysync/ui/PermissionsRationaleActivity.kt - com/vayunmathur/everysync/ui/SettingsScreen.kt+- com/vayunmathur/everysync/ui/VaultSharingSection.kt  ## Verify (this module only) ```
everysync/build.gradle.kts
diff --git a/everysync/build.gradle.kts b/everysync/build.gradle.ktsindex 5c4014d034..018239a18b 100644--- a/everysync/build.gradle.kts+++ b/everysync/build.gradle.kts@@ -13,36 +13,17 @@ launcherIcon { android {     defaultConfig {         applicationId = "com.vayunmathur.everysync"--        // OAuth2 configuration. These are ALL public values (client IDs are-        // identifiers, not secrets) so they can be committed and the build stays-        // reproducible. Override per-build with a -PEVERYSYNC_* gradle property.-        // No client secret is ever shipped: confidential secrets (Withings,-        // optionally Samsung) live behind a *_TOKEN_PROXY_URL backend relay.-        val googleClientId = (project.findProperty("EVERYSYNC_GOOGLE_CLIENT_ID")-            ?: "827025129169-tvph1v4c7b4n36s0prbe3u8dh3kd12t7.apps.googleusercontent.com").toString()--        buildConfigField("String", "GOOGLE_OAUTH_CLIENT_ID", "\"$googleClientId\"")-        // The OAuth redirect is the app-id custom scheme (com.vayunmathur.everysync:/oauth),-        // caught by OAuthCallbackActivity — see OAuthConfig.REDIRECT_URI. It is NOT-        // derived from the client ID.-    }-    buildFeatures {-        buildConfig = true     } }  dependencies {-    // Custom Tabs for OAuth PKCE flow-    implementation(libs.androidx.browser)--    // Health Connect (Withings + Samsung/Google Health bridge)-    implementation(libs.androidx.connect.client)-     // Background sync     implementation(libs.androidx.work.runtime.ktx) -    // HTTP client (custom WebDAV methods + JSON)+    // HTTP client (relay REST + WebSocket)     implementation(project(":library:network")) +    // End-to-end encryption for personal relay vaults (PQC identity + AES content keys)+    implementation(project(":library:e2ee-p2p"))+ }
everysync/src/main/AndroidManifest.xml
diff --git a/everysync/src/main/AndroidManifest.xml b/everysync/src/main/AndroidManifest.xmlindex c794517c8f..48457386cb 100644--- a/everysync/src/main/AndroidManifest.xml+++ b/everysync/src/main/AndroidManifest.xml@@ -11,61 +11,14 @@     <uses-permission android:name="android.permission.READ_CALENDAR" />     <uses-permission android:name="android.permission.WRITE_CALENDAR" /> +    <!-- Relay IPC: query the passwords/notes/todo vault ContentProviders (signature-gated). -->+    <uses-permission android:name="com.vayunmathur.passwords.permission.RELAY" />+    <uses-permission android:name="com.vayunmathur.notes.permission.RELAY" />+    <uses-permission android:name="com.vayunmathur.todo.permission.RELAY" />+     <uses-permission android:name="android.permission.GET_ACCOUNTS" />     <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />     <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />-    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />-    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />--    <uses-permission android:name="android.permission.health.READ_WEIGHT" />-    <uses-permission android:name="android.permission.health.WRITE_WEIGHT" />-    <uses-permission android:name="android.permission.health.READ_HEIGHT" />-    <uses-permission android:name="android.permission.health.WRITE_HEIGHT" />-    <uses-permission android:name="android.permission.health.READ_BODY_FAT" />-    <uses-permission android:name="android.permission.health.WRITE_BODY_FAT" />-    <uses-permission android:name="android.permission.health.READ_LEAN_BODY_MASS" />-    <uses-permission android:name="android.permission.health.WRITE_LEAN_BODY_MASS" />-    <uses-permission android:name="android.permission.health.READ_BONE_MASS" />-    <uses-permission android:name="android.permission.health.WRITE_BONE_MASS" />-    <uses-permission android:name="android.permission.health.READ_BODY_WATER_MASS" />-    <uses-permission android:name="android.permission.health.WRITE_BODY_WATER_MASS" />-    <uses-permission android:name="android.permission.health.READ_HEART_RATE" />-    <uses-permission android:name="android.permission.health.WRITE_HEART_RATE" />-    <uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" />-    <uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />-    <uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION" />-    <uses-permission android:name="android.permission.health.WRITE_OXYGEN_SATURATION" />-    <uses-permission android:name="android.permission.health.READ_STEPS" />-    <uses-permission android:name="android.permission.health.WRITE_STEPS" />-    <uses-permission android:name="android.permission.health.READ_DISTANCE" />-    <uses-permission android:name="android.permission.health.WRITE_DISTANCE" />-    <uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED" />-    <uses-permission android:name="android.permission.health.WRITE_FLOORS_CLIMBED" />-    <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" />-    <uses-permission android:name="android.permission.health.WRITE_ACTIVE_CALORIES_BURNED" />-    <uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED" />-    <uses-permission android:name="android.permission.health.WRITE_TOTAL_CALORIES_BURNED" />-    <uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY" />-    <uses-permission android:name="android.permission.health.WRITE_HEART_RATE_VARIABILITY" />-    <uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE" />-    <uses-permission android:name="android.permission.health.WRITE_RESPIRATORY_RATE" />-    <uses-permission android:name="android.permission.health.READ_BLOOD_GLUCOSE" />-    <uses-permission android:name="android.permission.health.WRITE_BLOOD_GLUCOSE" />-    <uses-permission android:name="android.permission.health.READ_BODY_TEMPERATURE" />-    <uses-permission android:name="android.permission.health.WRITE_BODY_TEMPERATURE" />-    <uses-permission android:name="android.permission.health.READ_VO2_MAX" />-    <uses-permission android:name="android.permission.health.WRITE_VO2_MAX" />-    <uses-permission android:name="android.permission.health.READ_HYDRATION" />-    <uses-permission android:name="android.permission.health.WRITE_HYDRATION" />-    <uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED" />-    <uses-permission android:name="android.permission.health.WRITE_ELEVATION_GAINED" />-    <uses-permission android:name="android.permission.health.READ_EXERCISE" />-    <uses-permission android:name="android.permission.health.WRITE_EXERCISE" />-    <uses-permission android:name="android.permission.health.READ_NUTRITION" />-    <uses-permission android:name="android.permission.health.WRITE_NUTRITION" />-    <uses-permission android:name="android.permission.health.READ_SLEEP" />-    <uses-permission android:name="android.permission.health.WRITE_SLEEP" />-    <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />      <application         android:allowBackup="true"@@ -80,6 +33,7 @@         <activity             android:name=".MainActivity"             android:exported="true"+            android:launchMode="singleTop"             android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"             android:theme="@style/Theme.General">             <intent-filter>@@ -90,38 +44,16 @@                 <action android:name="android.intent.action.APPLICATION_PREFERENCES" />                 <category android:name="android.intent.category.DEFAULT" />             </intent-filter>-        </activity>--        <activity-            android:name=".auth.OAuthCallbackActivity"-            android:exported="true"-            android:launchMode="singleTask"-            android:theme="@android:style/Theme.Translucent.NoTitleBar">+            <!-- everysync://join/<vaultId>?owner=<device>&type=<dataType>: sealed join request (public ids only). -->             <intent-filter>                 <action android:name="android.intent.action.VIEW" />+                 <category android:name="android.intent.category.DEFAULT" />                 <category android:name="android.intent.category.BROWSABLE" />-                <data android:scheme="com.vayunmathur.everysync" />-            </intent-filter>-        </activity> -        <activity-            android:name=".ui.PermissionsRationaleActivity"-            android:exported="true">-            <intent-filter>-                <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />+                <data android:scheme="everysync" android:host="join" />             </intent-filter>         </activity>-        <activity-alias-            android:name="ViewPermissionUsageActivity"-            android:exported="true"-            android:targetActivity=".ui.PermissionsRationaleActivity"-            android:permission="android.permission.START_VIEW_PERMISSION_USAGE">-            <intent-filter>-                <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />-                <category android:name="android.intent.category.HEALTH_PERMISSIONS" />-            </intent-filter>-        </activity-alias>          <service             android:name=".auth.AuthenticatorService"@@ -134,31 +66,6 @@                 android:resource="@xml/authenticator" />         </service> -        <service-            android:name=".sync.ContactsSyncService"-            android:exported="false">-            <intent-filter>-                <action android:name="android.content.SyncAdapter" />-            </intent-filter>-            <meta-data-                android:name="android.content.SyncAdapter"-                android:resource="@xml/syncadapter_contacts" />-            <meta-data-                android:name="android.provider.CONTACTS_STRUCTURE"-                android:resource="@xml/contacts" />-        </service>--        <service-            android:name=".sync.CalendarSyncService"-            android:exported="false">-            <intent-filter>-                <action android:name="android.content.SyncAdapter" />-            </intent-filter>-            <meta-data-                android:name="android.content.SyncAdapter"-                android:resource="@xml/syncadapter_calendar" />-        </service>-         <receiver             android:name=".platform.BootReceiver"             android:exported="true"
everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt b/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.ktindex a19d477cdb..c690b0c135 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt@@ -8,15 +8,15 @@ import com.vayunmathur.library.network.TrustBundle  /**  * Ensures the periodic background sync is scheduled whenever the process starts —- * including when WorkManager or the sync framework spins the app up in the- * background — so syncing keeps running without the user reopening the UI.+ * including when WorkManager spins the app up in the background — so syncing+ * keeps running without the user reopening the UI.  */ class EverySyncApplication : Application() {     override fun onCreate() {         super.onCreate()         Log.init(BuildConfig.DEV_BUILD)-        // EXTENDED covers Google GTS (accounts.google.com, apis) + Apple roots (caldav.icloud.com)-        NetworkClient.init(this, TrustBundle.EXTENDED)+        // FIRST_PARTY covers the relay host (same bundle the office twin uses).+        NetworkClient.init(this, TrustBundle.FIRST_PARTY)         SyncScheduler.schedulePeriodic(this)     } }
everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt b/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.ktindex 63f4e09c8c..194ed1baf0 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt@@ -1,5 +1,6 @@ package com.vayunmathur.everysync +import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent@@ -10,8 +11,10 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.ui.Modifier+import com.vayunmathur.everysync.network.remote.RelayLinks import com.vayunmathur.everysync.platform.EverySyncViewModel import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.OfflineAware  class MainActivity : ComponentActivity() {@@ -20,6 +23,9 @@ class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()+        // everysync://join links request access to someone else's vault — fire a+        // sealed join request (public ids only) and confirm on the snackbar.+        parseJoinLink(intent)?.let { handleJoinLink(it) }         setContent {             DynamicTheme {                 // Paint the theme background behind everything (incl. the status bar strip the@@ -33,4 +39,39 @@ class MainActivity : ComponentActivity() {             }         }     }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        // singleTop: warm-start join links arrive here rather than through a fresh onCreate.+        setIntent(intent)+        parseJoinLink(intent)?.let { handleJoinLink(it) }+    }++    /** Fires a sealed join request to the owner and confirms with a snackbar message. */+    private fun handleJoinLink(link: Triple<String, String, String>) {+        val (vaultId, ownerId, dataType) = link+        AppMessages.show(getString(R.string.join_request_sending))+        viewModel.vaults.requestToJoin(vaultId, ownerId, dataType) { ok ->+            AppMessages.show(+                getString(if (ok) R.string.join_request_sent else R.string.join_request_failed),+                duration = AppMessages.Duration.Long,+            )+        }+    }++    /**+     * Parses `everysync://join/<vaultId>?owner=<ownerDeviceId>&type=<dataType>`;+     * null for any other intent. Mirrors voxels `MenuActivity.parseJoinLink` and+     * office `MainActivity.parseJoinLink`.+     */+    private fun parseJoinLink(intent: Intent?): Triple<String, String, String>? {+        val data = intent?.data ?: return null+        return RelayLinks.parseJoinLink(+            scheme = data.scheme,+            host = data.host,+            vaultId = data.lastPathSegment?.takeIf { it.isNotBlank() },+            ownerId = data.getQueryParameter("owner")?.takeIf { it.isNotBlank() },+            dataType = data.getQueryParameter("type"),+        )+    } }
everysync/src/main/java/com/vayunmathur/everysync/Navigation.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/Navigation.kt b/everysync/src/main/java/com/vayunmathur/everysync/Navigation.ktindex b59cc4065b..e6b95ea142 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/Navigation.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/Navigation.kt@@ -5,7 +5,6 @@ import com.vayunmathur.everysync.platform.EverySyncViewModel import com.vayunmathur.everysync.ui.AccountDetailScreen import com.vayunmathur.everysync.ui.AccountsScreen import com.vayunmathur.everysync.ui.AddAccountScreen-import com.vayunmathur.everysync.ui.DavLoginScreen import com.vayunmathur.everysync.ui.SettingsScreen import com.vayunmathur.library.util.DialogPage import com.vayunmathur.library.util.ListDetailPage@@ -23,9 +22,6 @@ fun Navigation(viewModel: EverySyncViewModel) {     MainNavigation(backStack) {         entry<Route.Accounts>(metadata = ListPage()) { AccountsScreen(backStack, viewModel) }         entry<Route.AddAccount>(metadata = ListPage()) { AddAccountScreen(backStack, viewModel) }-        entry<Route.DavLogin>(metadata = DialogPage()) {-            DavLoginScreen(backStack, viewModel, it.providerId)-        }         entry<Route.AccountDetail>(metadata = ListDetailPage() + MorphPage()) {             AccountDetailScreen(backStack, viewModel, it.accountName)         }
everysync/src/main/java/com/vayunmathur/everysync/Route.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/Route.kt b/everysync/src/main/java/com/vayunmathur/everysync/Route.ktindex 47626cf290..bbe3c23f9e 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/Route.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/Route.kt@@ -7,7 +7,6 @@ import kotlinx.serialization.Serializable sealed interface Route : NavKey {     @Serializable data object Accounts : Route     @Serializable data object AddAccount : Route-    @Serializable data class DavLogin(val providerId: String) : Route     @Serializable data class AccountDetail(val accountName: String) : Route     @Serializable data object Settings : Route }
everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.ktindex e8603b4571..001804473c 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt@@ -1,25 +1,65 @@ package com.vayunmathur.everysync.auth  import com.vayunmathur.everysync.provider.DataType+import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable+import kotlinx.serialization.builtins.SetSerializer+import kotlinx.serialization.builtins.serializer+import kotlinx.serialization.descriptors.SerialDescriptor+import kotlinx.serialization.encoding.Decoder+import kotlinx.serialization.encoding.Encoder+import kotlinx.serialization.json.JsonDecoder+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.jsonPrimitive++/**+ * Tolerant reader for [DataType]: unknown enum names (written by a newer app+ * version, e.g. PASSWORDS/NOTES before this build knew them) decode as absent+ * instead of failing the whole [AccountConfig] list — the version gate for+ * forward-compatible account storage.+ */+object TolerantDataTypeSetSerializer : KSerializer<Set<DataType>> {+    private val delegate = SetSerializer(DataType.serializer())++    override val descriptor: SerialDescriptor = delegate.descriptor++    override fun serialize(encoder: Encoder, value: Set<DataType>) =+        delegate.serialize(encoder, value)++    override fun deserialize(decoder: Decoder): Set<DataType> {+        // JSON path: filter unknown names element-by-element so one future+        // type never drops the stored account. Non-JSON decoders (protobuf,+        // cbor) fall back to strict decode — they version by schema instead.+        val jsonDecoder = decoder as? JsonDecoder ?: return delegate.deserialize(decoder)+        val element = jsonDecoder.decodeJsonElement()+        if (element !is kotlinx.serialization.json.JsonArray) return emptySet()+        return element.mapNotNull { item ->+            val name = (item as? JsonPrimitive)?.takeIf { it.isString }?.content ?: return@mapNotNull null+            runCatching { DataType.valueOf(name) }.getOrNull()+        }.toSet()+    }+}  /**  * A configured EverySync account. Persisted as JSON in [AccountStore]; the  * matching [android.accounts.Account] (type `com.vayunmathur.everysync`) is- * registered with AccountManager so other apps see synced data under it.+ * registered with AccountManager so synced contacts/calendar rows are owned by+ * a real system account — the system providers key rows by (name, type) and+ * some OEMs reject rows whose type has no registered authenticator.  *- * Secrets (OAuth tokens, DAV passwords) live in the encrypted [TokenStore],+ * Secrets (vault keys) live in the encrypted [TokenStore],  * keyed by [accountName] — never in this object.  */ @Serializable data class AccountConfig(-    /** Unique account name, also the AccountManager account name. */+    /** Unique account name, also the system account name owning the local rows. */     val accountName: String,     val providerId: String,-    /** For DAV providers: discovered/base principal URL. */-    val davBaseUrl: String? = null,-    val davUsername: String? = null,-    /** Data types the user enabled for this account. */+    /**+     * Data types the user enabled for this account. Decodes tolerantly: names+     * from a newer version are dropped rather than failing the account.+     */+    @Serializable(with = TolerantDataTypeSetSerializer::class)     val enabledTypes: Set<DataType> = emptySet(),     /** Per-account sync interval override in minutes (null = use global). */     val intervalMinutes: Int? = null,
everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.ktindex fa2d974882..1a01a88a01 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt@@ -12,12 +12,15 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json  /**- * Persists [AccountConfig]s in DataStore and keeps the AccountManager entries in- * sync. All EverySync accounts share the account type `com.vayunmathur.everysync`- * (see [ACCOUNT_TYPE]) so the sync-adapter framework can drive them.+ * Persists [AccountConfig]s in DataStore and keeps the system account entries+ * in sync. All EverySync accounts share the account type+ * `com.vayunmathur.everysync` (see [ACCOUNT_TYPE]) so synced contacts/calendar+ * rows are owned by a real system account — the system providers key rows by+ * (name, type) and some OEMs reject rows whose type has no registered+ * authenticator.  */-class AccountStore private constructor(private val context: Application) {-    private val ds = DataStoreUtils.getInstance(context)+class AccountStore private constructor(private val appContext: Application) {+    private val ds = DataStoreUtils.getInstance(appContext)     private val json = Json { ignoreUnknownKeys = true }      fun accountsFlow(): Flow<List<AccountConfig>> =@@ -37,13 +40,13 @@ class AccountStore private constructor(private val context: Application) {     suspend fun remove(accountName: String) {         val current = getAll().filterNot { it.accountName == accountName }         ds.setString(KEY, json.encodeToString(current))-        TokenStore.getInstance(context).clear(accountName)+        TokenStore.getInstance(appContext).clear(accountName)         removeSystemAccount(accountName)     }      private fun ensureSystemAccount(accountName: String) {         try {-            val am = AccountManager.get(context)+            val am = AccountManager.get(appContext)             val exists = am.getAccountsByType(ACCOUNT_TYPE).any { it.name == accountName }             if (!exists) {                 am.addAccountExplicitly(Account(accountName, ACCOUNT_TYPE), null, null)@@ -55,7 +58,7 @@ class AccountStore private constructor(private val context: Application) {      private fun removeSystemAccount(accountName: String) {         try {-            val am = AccountManager.get(context)+            val am = AccountManager.get(appContext)             am.getAccountsByType(ACCOUNT_TYPE)                 .firstOrNull { it.name == accountName }                 ?.let { am.removeAccountExplicitly(it) }@@ -64,8 +67,6 @@ class AccountStore private constructor(private val context: Application) {         }     } -    fun systemAccount(accountName: String) = Account(accountName, ACCOUNT_TYPE)-     private fun decode(raw: String?): List<AccountConfig> {         if (raw.isNullOrBlank()) return emptyList()         return try {
everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.ktindex 6014c4095b..26e0640cb6 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt@@ -11,9 +11,10 @@ import android.os.IBinder  /**  * Bare authenticator so EverySync accounts (type `com.vayunmathur.everysync`)- * appear to the system and the sync-adapter framework. Account creation happens- * in-app (OAuth / DAV login), not via the system "Add account" flow, so all- * methods are no-ops — mirrors `contacts/.../auth/Authenticator.kt`.+ * appear to the system (contacts/calendar rows are owned by the account).+ * Account creation happens in-app (personal vaults), not via the system+ * "Add account" flow, so all methods are no-ops — mirrors+ * `contacts/.../auth/Authenticator.kt`.  */ class Authenticator(context: Context) : AbstractAccountAuthenticator(context) {     override fun editProperties(
everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.ktdeleted file mode 100644index 242f0f2377..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt+++ /dev/null@@ -1,35 +0,0 @@-package com.vayunmathur.everysync.auth--import android.content.Intent-import android.os.Bundle-import androidx.activity.ComponentActivity-import androidx.lifecycle.lifecycleScope-import com.vayunmathur.everysync.MainActivity-import com.vayunmathur.everysync.sync.SyncScheduler-import kotlinx.coroutines.launch--/**- * Receives the OAuth2 redirect (`com.vayunmathur.everysync:/oauth`), completes the- * PKCE token exchange, then returns to [MainActivity] and kicks off a first sync.- */-class OAuthCallbackActivity : ComponentActivity() {-    override fun onCreate(savedInstanceState: Bundle?) {-        super.onCreate(savedInstanceState)-        val data = intent?.data-        if (data == null) {-            finish()-            return-        }-        lifecycleScope.launch {-            val accountName = OAuthManager.complete(applicationContext, data)-            if (accountName != null) {-                SyncScheduler.syncNow(applicationContext, accountName)-            }-            startActivity(-                Intent(this@OAuthCallbackActivity, MainActivity::class.java)-                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP),-            )-            finish()-        }-    }-}
everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.ktdeleted file mode 100644index 7c3ddb3e20..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt+++ /dev/null@@ -1,62 +0,0 @@-package com.vayunmathur.everysync.auth--import com.vayunmathur.everysync.BuildConfig--/**- * OAuth2 endpoints + scopes for a provider.- *- * Everything here is safe to commit — client IDs are public identifiers, not- * secrets, so builds stay reproducible. All providers are public PKCE clients;- * no client secret is ever shipped.- */-data class OAuthConfig(-    val authEndpoint: String,-    val tokenEndpoint: String,-    val clientId: String,-    val scopes: List<String>,-    /** Extra query params appended to the authorization request. */-    val extraAuthParams: Map<String, String> = emptyMap(),-    /** Redirect URI for this provider (app-id custom scheme by default). */-    val redirectUri: String = REDIRECT_URI,-) {-    val hasClientId: Boolean get() = clientId.isNotBlank()--    companion object {-        // iOS-type Google OAuth client → custom URI scheme redirect. The scheme is-        // the app id (registered as the iOS client's "bundle ID" in Google Cloud).-        // Per Google's installed-app spec the path uses a single slash. iOS clients-        // do NOT accept https redirects (that's Web-client only), and Android-type-        // clients don't allow custom schemes at all — hence the iOS client.-        const val REDIRECT_URI = "com.vayunmathur.everysync:/oauth"--        val GOOGLE = OAuthConfig(-            authEndpoint = "https://accounts.google.com/o/oauth2/v2/auth",-            tokenEndpoint = "https://oauth2.googleapis.com/token",-            clientId = BuildConfig.GOOGLE_OAUTH_CLIENT_ID,-            scopes = listOf(-                "openid",-                "email",-                "https://www.googleapis.com/auth/carddav",-                "https://www.googleapis.com/auth/calendar",-            ),-            // Force a refresh token to be returned on first consent.-            extraAuthParams = mapOf("access_type" to "offline", "prompt" to "consent"),-        )--        // Google Health via the Google Health API v4 (health.googleapis.com) —-        // same Google OAuth client, read-only Google Health scopes. Replaces the-        // wound-down Google Fitness REST API and its fitness.* scopes.-        val GOOGLE_HEALTH = OAuthConfig(-            authEndpoint = "https://accounts.google.com/o/oauth2/v2/auth",-            tokenEndpoint = "https://oauth2.googleapis.com/token",-            clientId = BuildConfig.GOOGLE_OAUTH_CLIENT_ID,-            scopes = listOf(-                "https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly",-                "https://www.googleapis.com/auth/googlehealth.health_metrics_and_measurements.readonly",-                "https://www.googleapis.com/auth/googlehealth.sleep.readonly",-                "https://www.googleapis.com/auth/googlehealth.nutrition.readonly",-            ),-            extraAuthParams = mapOf("access_type" to "offline", "prompt" to "consent"),-        )-    }-}
everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.ktdeleted file mode 100644index 80dce9c477..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt+++ /dev/null@@ -1,229 +0,0 @@-package com.vayunmathur.everysync.auth--import android.content.Context-import android.net.Uri-import com.vayunmathur.library.log.Log-import androidx.browser.customtabs.CustomTabsIntent-import androidx.core.net.toUri-import com.vayunmathur.everysync.provider.ProviderRegistry-import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.util.DataStoreUtils-import java.security.MessageDigest-import java.security.SecureRandom-import kotlin.io.encoding.Base64-import kotlinx.serialization.Serializable-import kotlinx.serialization.encodeToString-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.jsonPrimitive-import kotlinx.serialization.json.longOrNull--/**- * OAuth2 Authorization Code + PKCE (RFC 7636). The authorization request opens in- * a Custom Tab; the redirect (`com.vayunmathur.everysync:/oauth`) is caught by- * [OAuthCallbackActivity], which calls [complete] to exchange the code for tokens.- */-object OAuthManager {-    private const val TAG = "OAuthManager"-    private const val PENDING_KEY = "everysync_pending_oauth"-    private const val REFRESH_SKEW_MILLIS = 60_000L-    private const val TOKEN_EXPIRY_UNKNOWN = 0L-    private const val MILLIS_PER_SECOND = 1000L-    private val json = Json { ignoreUnknownKeys = true }--    @Serializable-    private data class Pending(val providerId: String, val verifier: String, val state: String)--    suspend fun start(context: Context, providerId: String) {-        val provider = ProviderRegistry.get(providerId) ?: return-        val config = provider.oauthConfig() ?: return-        if (!config.hasClientId) return // No client ID configured for this build.-        val verifier = randomUrlSafe(64)-        val challenge = codeChallenge(verifier)-        val state = randomUrlSafe(24)-        DataStoreUtils.getInstance(context)-            .setString(PENDING_KEY, json.encodeToString(Pending(providerId, verifier, state)))--        val url = config.authEndpoint.toUri().buildUpon()-            .appendQueryParameter("client_id", config.clientId)-            .appendQueryParameter("redirect_uri", config.redirectUri)-            .appendQueryParameter("response_type", "code")-            .appendQueryParameter("scope", config.scopes.joinToString(" "))-            .appendQueryParameter("code_challenge", challenge)-            .appendQueryParameter("code_challenge_method", "S256")-            .appendQueryParameter("state", state)-            .apply { config.extraAuthParams.forEach { (k, v) -> appendQueryParameter(k, v) } }-            .build()--        // Launched from an application context (the ViewModel), so the Custom Tab-        // intent needs NEW_TASK or startActivity throws. Guarded so a device with-        // no browser/Custom Tabs handler doesn't crash the app.-        val customTabs = CustomTabsIntent.Builder().build()-        customTabs.intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)-        try {-            customTabs.launchUrl(context, url)-        } catch (expected: Exception) {-            Log.error(TAG, "Failed to launch OAuth Custom Tab", expected)-        }-    }--    /** Handle the OAuth redirect. Returns the created account name on success. */-    suspend fun complete(context: Context, redirect: Uri): String? {-        val pending = readPending(context)-        val code = redirect.getQueryParameter("code")-        val provider = pending?.let { ProviderRegistry.get(it.providerId) }-        val config = provider?.oauthConfig()-        if (!isResolvable(pending, code, provider, config)) return null-        if (redirect.getQueryParameter("state") != pending?.state) {-            Log.error(TAG, "OAuth state mismatch")-            return null-        }--        val tokens = exchangeCode(config!!, code!!, pending!!.verifier) ?: return null-        val accountName = resolveName(context, provider!!, tokens)-        persistAccount(context, provider, accountName, tokens)-        DataStoreUtils.getInstance(context).setString(PENDING_KEY, "")-        return accountName-    }--    private fun isResolvable(-        pending: Pending?,-        code: String?,-        provider: com.vayunmathur.everysync.provider.SyncProvider?,-        config: OAuthConfig?,-    ): Boolean = pending != null && code != null && provider != null && config != null--    private suspend fun readPending(context: Context): Pending? {-        val raw = DataStoreUtils.getInstance(context).getString(PENDING_KEY) ?: return null-        return runCatching { json.decodeFromString<Pending>(raw) }.getOrNull()-    }--    private suspend fun resolveName(-        context: Context,-        provider: com.vayunmathur.everysync.provider.SyncProvider,-        tokens: OAuthTokens,-    ): String = try {-        provider.resolveAccountName(context, tokens)-    } catch (expected: Exception) {-        Log.error(TAG, "resolveAccountName failed", expected)-        "${provider.displayName} account"-    }--    private suspend fun persistAccount(-        context: Context,-        provider: com.vayunmathur.everysync.provider.SyncProvider,-        accountName: String,-        tokens: OAuthTokens,-    ) {-        TokenStore.getInstance(context).putTokens(accountName, tokens)-        AccountStore.getInstance(context).upsert(-            AccountConfig(-                accountName = accountName,-                providerId = provider.id,-                enabledTypes = provider.capabilities,-            ),-        )-    }--    /** Return a valid access token, refreshing it first if it has expired. */-    suspend fun validAccessToken(-        context: Context,-        accountName: String,-        providerId: String,-    ): String? {-        val store = TokenStore.getInstance(context)-        val tokens = store.getTokens(accountName) ?: return null-        val fresh = if (isExpired(tokens)) {-            refresh(context, accountName, providerId, tokens) ?: tokens-        } else {-            tokens-        }-        return fresh.accessToken-    }--    private fun isExpired(tokens: OAuthTokens): Boolean =-        tokens.expiresAtMs != TOKEN_EXPIRY_UNKNOWN &&-            tokens.expiresAtMs < System.currentTimeMillis() + REFRESH_SKEW_MILLIS--    private suspend fun refresh(-        context: Context,-        accountName: String,-        providerId: String,-        tokens: OAuthTokens,-    ): OAuthTokens? {-        val refreshToken = tokens.refreshToken ?: return null-        val config = ProviderRegistry.get(providerId)?.oauthConfig() ?: return null-        val form = buildMap {-            put("client_id", config.clientId)-            put("grant_type", "refresh_token")-            put("refresh_token", refreshToken)-        }-        val parsed = postForm(config, form) ?: return null-        val updated = tokens.copy(-            accessToken = parsed.accessToken,-            refreshToken = parsed.refreshToken ?: tokens.refreshToken,-            expiresAtMs = parsed.expiresAtMs,-        )-        TokenStore.getInstance(context).putTokens(accountName, updated)-        return updated-    }--    private suspend fun exchangeCode(-        config: OAuthConfig,-        code: String,-        verifier: String,-    ): OAuthTokens? {-        val form = buildMap {-            put("client_id", config.clientId)-            put("grant_type", "authorization_code")-            put("code", code)-            put("redirect_uri", config.redirectUri)-            put("code_verifier", verifier)-        }-        return postForm(config, form)-    }--    private suspend fun postForm(config: OAuthConfig, form: Map<String, String>): OAuthTokens? {-        return try {-            val body = form.entries.joinToString("&") {-                "${Uri.encode(it.key)}=${Uri.encode(it.value)}"-            }-            val resp = NetworkClient.performRequest(-                config.tokenEndpoint,-                "POST",-                mapOf("Content-Type" to "application/x-www-form-urlencoded"),-                body,-            )-            val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return null-            val access = root["access_token"]?.jsonPrimitive?.contentOrNullSafe() ?: return null-            val refresh = root["refresh_token"]?.jsonPrimitive?.contentOrNullSafe()-            val expiresIn = root["expires_in"]?.jsonPrimitive?.longOrNull ?: TOKEN_EXPIRY_UNKNOWN-            OAuthTokens(-                accessToken = access,-                refreshToken = refresh,-                expiresAtMs = if (expiresIn > 0) {-                    System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND-                } else {-                    TOKEN_EXPIRY_UNKNOWN-                },-            )-        } catch (expected: Exception) {-            Log.error(TAG, "token endpoint call failed", expected)-            null-        }-    }--    private fun kotlinx.serialization.json.JsonPrimitive.contentOrNullSafe(): String? =-        runCatching { this.content }.getOrNull()?.ifBlank { null }--    private fun randomUrlSafe(bytes: Int): String {-        val buf = ByteArray(bytes)-        SecureRandom().nextBytes(buf)-        return Base64.UrlSafe.encode(buf).replace("=", "")-    }--    private fun codeChallenge(verifier: String): String {-        val digest = MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray())-        return Base64.UrlSafe.encode(digest).replace("=", "")-    }-}
everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.ktindex 2f6e56418b..32b7cdffe8 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt@@ -10,27 +10,8 @@ import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec-import kotlinx.serialization.Serializable-import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json -/** OAuth token triple persisted (encrypted) per account. */-@Serializable-data class OAuthTokens(-    val accessToken: String,-    val refreshToken: String? = null,-    /** Absolute expiry (epoch ms). 0 = unknown. */-    val expiresAtMs: Long = 0L,-)--/** DAV credentials persisted (encrypted) per account. */-@Serializable-data class DavCredentials(-    val baseUrl: String,-    val username: String,-    val password: String,-)- /**  * Encrypted secret storage. Secrets are AES-GCM encrypted with a non-exportable  * key held in the Android Keystore, then the ciphertext is stored as a byte@@ -76,28 +57,20 @@ class TokenStore private constructor(context: Context) {         return cipher.doFinal(ct)     } -    suspend fun putTokens(accountName: String, tokens: OAuthTokens) {-        store("$OAUTH_PREFIX$accountName", json.encodeToString(tokens))-    }--    fun getTokens(accountName: String): OAuthTokens? =-        load("$OAUTH_PREFIX$accountName")?.let {-            runCatching { json.decodeFromString<OAuthTokens>(it) }.getOrNull()-        }--    suspend fun putDav(accountName: String, creds: DavCredentials) {-        store("$DAV_PREFIX$accountName", json.encodeToString(creds))+    suspend fun putSyncKey(accountName: String, dataType: String, keyB64: String) {+        store("$SYNC_KEY_PREFIX$accountName:$dataType", keyB64)     } -    fun getDav(accountName: String): DavCredentials? =-        load("$DAV_PREFIX$accountName")?.let {-            runCatching { json.decodeFromString<DavCredentials>(it) }.getOrNull()-        }+    fun getSyncKey(accountName: String, dataType: String): String? =+        load("$SYNC_KEY_PREFIX$accountName:$dataType")      suspend fun clear(accountName: String) {         // Overwrite with empty blobs; DataStore has no per-key delete here.-        ds.setByteArray("$OAUTH_PREFIX$accountName", ByteArray(0))-        ds.setByteArray("$DAV_PREFIX$accountName", ByteArray(0))+        // Vault keys are per (account, type); clear the known relay types. Personal+        // vaults use the five relay data types below.+        for (type in SYNC_KEY_TYPES) {+            ds.setByteArray("$SYNC_KEY_PREFIX$accountName:$type", ByteArray(0))+        }     }      private suspend fun store(key: String, value: String) {@@ -125,8 +98,9 @@ class TokenStore private constructor(context: Context) {         private const val TRANSFORMATION = "AES/GCM/NoPadding"         private const val GCM_IV_LEN = 12         private const val GCM_TAG_BITS = 128-        private const val OAUTH_PREFIX = "tok_oauth_"-        private const val DAV_PREFIX = "tok_dav_"+        private const val SYNC_KEY_PREFIX = "tok_synckey_"+        /** Relay data types with per-type vault keys (mirrors the five relay channels). */+        private val SYNC_KEY_TYPES = listOf("contacts", "calendar", "passwords", "notes", "todos")         private const val TAG = "TokenStore"          @Volatile
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 0a2e43f760..0e79997dde 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt@@ -1,10 +1,13 @@ package com.vayunmathur.everysync.data -/** A contact resolved from a remote source (CardDAV vCard or Google People). */+import kotlinx.serialization.Serializable++/** A contact resolved from a relay vault record. */+@Serializable data class RemoteContact(-    /** Stable remote identifier (vCard UID or People resourceName). */+    /** Stable relay sync identity (opaque 32-char id). */     val uid: String,-    /** Server ETag for change detection, if known. */+    /** Relay updatedAt stamp as a string, for change detection; null when unknown. */     val etag: String? = null,     val displayName: String = "",     val prefix: String = "",@@ -20,27 +23,21 @@ data class RemoteContact(     val addresses: List<TypedValue> = emptyList(),     /** ISO-8601 birthday (yyyy-MM-dd) or null. */     val birthday: String? = null,-    /** For CardDAV: the resource path on the server (collection-relative). */+    /** Relay sync identity of the vault this record belongs to. */     val href: String? = null,     val deleted: Boolean = false,+    /** Last local-or-remote modification (epoch ms); drives relay LWW. */+    val updatedAt: Long = 0L, ) +@Serializable data class TypedValue(val value: String, val type: Int) -/** A calendar collection (CalDAV collection or Google calendarList entry). */-data class RemoteCalendar(-    val id: String,-    val displayName: String,-    val color: Int? = null,-    /** CalDAV collection ctag for cheap change detection. */-    val ctag: String? = null,-    /** CalDAV collection URL. */-    val url: String? = null,-)--/** A calendar event resolved from a remote source. */+/** A calendar event resolved from a relay vault record. */+@Serializable data class RemoteEvent(     val uid: String,+    /** Relay updatedAt stamp as a string, for change detection; null when unknown. */     val etag: String? = null,     val calendarId: String,     val summary: String = "",@@ -52,82 +49,91 @@ data class RemoteEvent(     val timezone: String = "UTC",     /** Raw RRULE line (without the "RRULE:" prefix), or null. */     val rrule: String? = null,+    /** RECURRENCE-ID of an overridden instance; null for the master. */+    val recurrenceId: String? = null,+    /** Relay sync identity of the vault this record belongs to. */     val href: String? = null,     val deleted: Boolean = false,+    /** Last local-or-remote modification (epoch ms); drives relay LWW. */+    val updatedAt: Long = 0L, ) -/** A health measurement destined for Health Connect. */-data class RemoteMeasurement(-    /** Provider-scoped stable id, used as Health Connect clientRecordId. */-    val clientRecordId: String,-    val type: MeasurementType,-    /** Primary value in the type's canonical unit (see [MeasurementType]). */-    val value: Double = 0.0,-    /** Start instant; equals [endMillis] for instantaneous sample/daily records. */-    val startMillis: Long,-    /** End instant for interval/session records (steps, distance, sleep, ...). */-    val endMillis: Long = startMillis,-    /** Sleep-stage segments; populated only for [MeasurementType.SLEEP]. */-    val sleepStages: List<RemoteSleepStage> = emptyList(),-    /** Health Connect `ExerciseSessionRecord.EXERCISE_TYPE_*`; only for [MeasurementType.EXERCISE]. */-    val exerciseType: Int = 0,-    /** Session title (exercise) or food name (nutrition). */-    val title: String? = null,-    /** Free-form notes; only for [MeasurementType.EXERCISE]. */-    val notes: String? = null,-    /** Nutrition payload; populated only for [MeasurementType.NUTRITION]. */-    val nutrition: RemoteNutrition? = null,-)--/** One sleep-stage segment. [stage] is a Health Connect `SleepSessionRecord.STAGE_TYPE_*` value. */-data class RemoteSleepStage(-    val startMillis: Long,-    val endMillis: Long,-    val stage: Int,+/**+ * A password or passkey record for the encrypted relay. Mirrors the native+ * vault fields so no KDBX mapping is needed: passwords use the name/username/+ * email/password/note/totp/websites half, passkeys ([isPasskey]) use the+ * rp/credential half. The relay envelope is the JSON of this class.+ */+@Serializable+data class RemotePassword(+    /** Relay sync identity (opaque 32-char id). */+    val uid: String,+    /** True for a passkey record, false for a password record. */+    val isPasskey: Boolean = false,+    val name: String = "",+    val username: String = "",+    val email: String = "",+    val password: String = "",+    val note: String = "",+    val totpSecret: String? = null,+    val websites: List<String> = emptyList(),+    // Passkey half (empty for passwords).+    val rpId: String = "",+    val rpName: String = "",+    val credentialId: String = "",+    val userId: String = "",+    val userName: String = "",+    val userDisplayName: String = "",+    /** Base64 of the private-key bytes. */+    val privateKeyB64: String = "",+    val creationTime: Long = 0L,+    val lastUsedTime: Long = 0L,+    val signCount: Int = 0,+    val linkedPasswordSyncId: String? = null,+    val deleted: Boolean = false,+    /** Last local-or-remote modification (epoch ms); drives relay LWW. */+    val updatedAt: Long = 0L, )  /**- * A logged food / nutrition entry. Energy is in kilocalories; [nutrientGrams] holds- * each nutrient's mass in grams keyed by Google Health nutrient name (e.g. "PROTEIN",- * "SODIUM"), plus the synthetic keys "TOTAL_FAT" and "TOTAL_CARBOHYDRATE".+ * A note record for the encrypted relay. [blocksJson] is the stored+ * NoteBody JSON (text / image / ink blocks); image bytes themselves live in+ * the blob channel (see RelayBlobStore) and are referenced by file name.+ * The relay envelope is the JSON of this class.  */-data class RemoteNutrition(-    val energyKcal: Double? = null,-    val nutrientGrams: Map<String, Double> = emptyMap(),+@Serializable+data class RemoteNote(+    /** Relay sync identity (opaque 32-char id). */+    val uid: String,+    val title: String = "",+    val content: String = "",+    /** Serialized NoteBody, or null for legacy text-only notes. */+    val blocksJson: String? = null,+    val position: Double = 0.0,+    val deleted: Boolean = false,+    /** Last local-or-remote modification (epoch ms); drives relay LWW. */+    val updatedAt: Long = 0L, )  /**- * Health metrics synced from Google Health into Health Connect. Each maps to one- * Health Connect record type; the trailing comment is the canonical unit stored in- * [RemoteMeasurement.value].+ * A todo task record for the encrypted relay. The relay envelope is the JSON+ * of this class on the `todos:<vaultId>` channel. The todo/ app owns on-device+ * storage; this shape is the contract between RelayMerge and its TodoSink.  */-enum class MeasurementType {-    // Body composition (instantaneous samples)-    WEIGHT, // kilograms-    HEIGHT, // meters-    BODY_FAT, // percent (0-100)--    // Vitals (instantaneous)-    HEART_RATE, // beats/min-    RESTING_HEART_RATE, // beats/min-    HEART_RATE_VARIABILITY, // milliseconds (RMSSD)-    OXYGEN_SATURATION, // percent (0-100)-    RESPIRATORY_RATE, // breaths/min-    BLOOD_GLUCOSE, // mg/dL-    BODY_TEMPERATURE, // degrees Celsius-    VO2_MAX, // mL/kg/min--    // Activity (intervals)-    STEPS, // count-    DISTANCE, // meters-    FLOORS, // count-    ELEVATION, // meters gained-    ACTIVE_CALORIES, // kilocalories-    TOTAL_CALORIES, // kilocalories--    // Sessions / lifestyle-    HYDRATION, // liters-    SLEEP, // session (start/end + sleepStages)-    EXERCISE, // session (exerciseType/title)-    NUTRITION, // logged food (nutrition payload)-}+@Serializable+data class RemoteTodo(+    /** Relay sync identity (opaque 32-char id). */+    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,+    /** Sort position; excluded from the merge hash so reorder is not an edit. */+    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,+)
everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.ktnew file mode 100644index 0000000000..5da86f6447--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt@@ -0,0 +1,60 @@+package com.vayunmathur.everysync.data++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * A personal E2EE vault this device owns or has joined: everything needed to+ * sync its record log and to invite others, without ever holding another+ * device's secrets.+ *+ * Key material ([keyB64]) is the AES vault key; for joined vaults it arrives+ * sealed in a [RelaySync.Invite](com.vayunmathur.everysync.network.remote.RelaySync.Invite).+ * [ownerKeyB64] is the owner's PQC public bundle, used to verify roster, key+ * epoch, ownership and title signatures client-side — the relay is a pure log.+ */+@Serializable+data class VaultMeta(+    /** Relay record-log id, e.g. `contacts:<uuid>` lives under [vaultId]. */+    val vaultId: String,+    /** One of `contacts`, `calendar`, `passwords`, `notes`. */+    val dataType: String,+    val title: String,+    val keyB64: String,+    val ownerDeviceId: String,+    val ownerKeyB64: String = "",+    val epoch: Int = 0,+    val isOwner: Boolean = true,+)++/** Persists owned + joined [VaultMeta]s as JSON in DataStore (mirrors office's docs index). */+object VaultStore {+    private const val KEY = "everysync_vaults"+    private val json = Json { ignoreUnknownKeys = true }++    fun getAll(context: Context): List<VaultMeta> {+        val raw = DataStoreUtils.getInstance(context).getString(KEY)+        if (raw.isNullOrBlank()) return emptyList()+        return runCatching { json.decodeFromString<List<VaultMeta>>(raw) }.getOrDefault(emptyList())+    }++    fun get(context: Context, vaultId: String): VaultMeta? =+        getAll(context).firstOrNull { it.vaultId == vaultId }++    suspend fun upsert(context: Context, meta: VaultMeta) {+        val current = getAll(context).filterNot { it.vaultId == meta.vaultId }+        DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(current + meta))+    }++    suspend fun remove(context: Context, vaultId: String) {+        val current = getAll(context).filterNot { it.vaultId == vaultId }+        DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(current))+    }++    suspend fun saveAll(context: Context, vaults: List<VaultMeta>) {+        DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(vaults))+    }+}
everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.ktindex ef2252e6bb..bf29f4657b 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/CalendarSink.kt@@ -19,9 +19,10 @@ data class LocalEventChange( )  /**- * Creates one CalendarContract calendar per remote collection under the EverySync- * account and writes events via sync-adapter URIs. The remote UID goes in- * Events._SYNC_ID, the ETag in SYNC_DATA1 and the href in SYNC_DATA2.+ * Creates one CalendarContract calendar per relay vault under the EverySync+ * account and writes events via caller-is-syncadapter URIs. The relay UID goes+ * in Events._SYNC_ID, the relay updatedAt stamp in SYNC_DATA1 and the vault id+ * in SYNC_DATA2.  */ object CalendarSink {     private const val TAG = "CalendarSink"@@ -136,6 +137,69 @@ object CalendarSink {         return out     } +    /**+     * Every live event in one calendar in relay form, for the merge's local+     * side. `updatedAt` comes from SYNC_DATA1 (the relay stamp mirrors into+     * `etag` on every relay write); rows that predate relay sync carry no+     * stamp and merge as fresh local creates via the adoption path.+     */+    fun listLocal(context: Context, localCalendarId: Long): List<RemoteEvent> {+        val out = mutableListOf<RemoteEvent>()+        // Local column positions for the projection below (not the shared+        // CURSOR_INDEX_* constants, which map a different 12-column query).+        val colUid = 0+        val colStamp = 1+        val colTitle = 2+        val colDesc = 3+        val colLoc = 4+        val colStart = 5+        val colEnd = 6+        val colAllDay = 7+        val colTz = 8+        val colRrule = 9+        try {+            context.contentResolver.query(+                CalendarContract.Events.CONTENT_URI,+                arrayOf(+                    CalendarContract.Events._SYNC_ID,+                    CalendarContract.Events.SYNC_DATA1,+                    CalendarContract.Events.TITLE,+                    CalendarContract.Events.DESCRIPTION,+                    CalendarContract.Events.EVENT_LOCATION,+                    CalendarContract.Events.DTSTART,+                    CalendarContract.Events.DTEND,+                    CalendarContract.Events.ALL_DAY,+                    CalendarContract.Events.EVENT_TIMEZONE,+                    CalendarContract.Events.RRULE,+                ),+                "${CalendarContract.Events.CALENDAR_ID} = ? AND ${CalendarContract.Events.DELETED} = 0",+                arrayOf(localCalendarId.toString()),+                null,+            )?.use { c ->+                while (c.moveToNext()) {+                    val uid = c.getStringOrNull(colUid).orEmpty()+                    out += RemoteEvent(+                        uid = uid,+                        etag = c.getStringOrNull(colStamp),+                        calendarId = localCalendarId.toString(),+                        summary = c.getStringOrNull(colTitle) ?: "",+                        description = c.getStringOrNull(colDesc) ?: "",+                        location = c.getStringOrNull(colLoc) ?: "",+                        startMillis = c.getLong(colStart),+                        endMillis = c.getLong(colEnd),+                        allDay = c.getInt(colAllDay) == 1,+                        timezone = c.getStringOrNull(colTz) ?: "UTC",+                        rrule = c.getStringOrNull(colRrule),+                        updatedAt = c.getStringOrNull(colStamp)?.toLongOrNull() ?: 0L,+                    )+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "listLocal failed", expected)+        }+        return out+    }+     private fun eventId(context: Context, localCalendarId: Long, uid: String): Long? =         try {             context.contentResolver.query(@@ -213,7 +277,7 @@ object CalendarSink {      * Removes every calendar (and, by cascade, its events) for this account from      * the on-device provider. Used when the user turns calendar sync off; the      * account itself stays, so a later re-enable can repopulate it from a fresh-     * pull. Deleting via the sync-adapter URI hard-removes the rows.+     * pull. Deleting via the caller-is-syncadapter URI hard-removes the rows.      */     fun purge(context: Context, accountName: String) {         try {
everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.ktindex 9bb11784a4..e6febcfccf 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/ContactsSink.kt@@ -27,9 +27,11 @@ data class LocalContactChange( )  /**- * Writes [RemoteContact]s into ContactsContract under the EverySync account using- * sync-adapter URIs (so our writes don't get flagged DIRTY). The remote UID is- * stored in RawContacts.SOURCE_ID, the ETag in SYNC1 and the server href in SYNC2.+ * Writes [RemoteContact]s into ContactsContract under the EverySync account.+ * Writes go through URIs carrying the `CALLER_IS_SYNCADAPTER` + account query+ * params (so our writes don't get flagged DIRTY). The relay UID is stored in+ * RawContacts.SOURCE_ID, the relay updatedAt stamp in SYNC1 and the vault id+ * in SYNC2.  */ object ContactsSink {     private const val TAG = "ContactsSink"@@ -77,6 +79,42 @@ object ContactsSink {         return result     } +    /**+     * Every live contact for this account in relay form, for the merge's+     * local side. `updatedAt` comes from SYNC1 (the relay stamp mirrors into+     * `etag` on every relay write); rows that predate relay sync carry no+     * stamp and merge as fresh local creates via the adoption path.+     */+    fun listLocal(context: Context, accountName: String): List<RemoteContact> {+        val out = mutableListOf<RemoteContact>()+        try {+            context.contentResolver.query(+                ContactsContract.RawContacts.CONTENT_URI,+                arrayOf(+                    ContactsContract.RawContacts._ID,+                    ContactsContract.RawContacts.SOURCE_ID,+                    ContactsContract.RawContacts.SYNC1,+                ),+                "${ContactsContract.RawContacts.ACCOUNT_NAME} = ? AND " ++                    "${ContactsContract.RawContacts.ACCOUNT_TYPE} = ? AND " ++                    "${ContactsContract.RawContacts.DELETED} = 0",+                arrayOf(accountName, ACCOUNT_TYPE),+                null,+            )?.use { c ->+                while (c.moveToNext()) {+                    val rawId = c.getLong(CURSOR_RAW_ID)+                    val uid = c.getStringOrNull(CURSOR_SOURCE_ID).orEmpty()+                    val stamp = c.getStringOrNull(CURSOR_SYNC1)?.toLongOrNull() ?: 0L+                    val contact = readContact(context, rawId, uid.ifBlank { null })+                    out += contact.copy(uid = uid, updatedAt = stamp)+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "listLocal failed", expected)+        }+        return out+    }+     private fun rawContactId(context: Context, accountName: String, uid: String): Long? {         return try {             context.contentResolver.query(@@ -147,7 +185,8 @@ object ContactsSink {      * Removes every raw contact for this account from the on-device provider.      * Used when the user turns contact sync off; the account itself stays, so a      * later re-enable can repopulate it from a fresh pull. Deleting via the-     * sync-adapter URI hard-removes the rows rather than marking them DELETED.+     * caller-is-syncadapter URI hard-removes the rows rather than marking them+     * DELETED.      */     fun purge(context: Context, accountName: String) {         try {
everysync/src/main/java/com/vayunmathur/everysync/data/sink/HealthSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/HealthSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/HealthSink.ktdeleted file mode 100644index 4fa5f280b0..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/HealthSink.kt+++ /dev/null@@ -1,463 +0,0 @@-package com.vayunmathur.everysync.data.sink--import android.content.Context-import com.vayunmathur.library.log.Log-import androidx.health.connect.client.HealthConnectClient-import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord-import androidx.health.connect.client.records.BloodGlucoseRecord-import androidx.health.connect.client.records.BodyFatRecord-import androidx.health.connect.client.records.BodyTemperatureRecord-import androidx.health.connect.client.records.DistanceRecord-import androidx.health.connect.client.records.ElevationGainedRecord-import androidx.health.connect.client.records.ExerciseSessionRecord-import androidx.health.connect.client.records.FloorsClimbedRecord-import androidx.health.connect.client.records.HeartRateRecord-import androidx.health.connect.client.records.HeartRateVariabilityRmssdRecord-import androidx.health.connect.client.records.HeightRecord-import androidx.health.connect.client.records.HydrationRecord-import androidx.health.connect.client.records.NutritionRecord-import androidx.health.connect.client.records.OxygenSaturationRecord-import androidx.health.connect.client.records.Record-import androidx.health.connect.client.records.RespiratoryRateRecord-import androidx.health.connect.client.records.RestingHeartRateRecord-import androidx.health.connect.client.records.SleepSessionRecord-import androidx.health.connect.client.records.StepsRecord-import androidx.health.connect.client.records.TotalCaloriesBurnedRecord-import androidx.health.connect.client.records.Vo2MaxRecord-import androidx.health.connect.client.records.WeightRecord-import androidx.health.connect.client.records.metadata.Metadata-import androidx.health.connect.client.units.BloodGlucose-import androidx.health.connect.client.units.Energy-import androidx.health.connect.client.units.Length-import androidx.health.connect.client.units.Mass-import androidx.health.connect.client.units.Percentage-import androidx.health.connect.client.units.Temperature-import androidx.health.connect.client.units.Volume-import com.vayunmathur.everysync.data.MeasurementType-import com.vayunmathur.everysync.data.RemoteMeasurement-import com.vayunmathur.everysync.data.RemoteNutrition-import java.time.Instant-import java.time.ZoneId-import kotlinx.coroutines.async-import kotlinx.coroutines.awaitAll-import kotlinx.coroutines.coroutineScope-import kotlinx.coroutines.sync.Semaphore-import kotlinx.coroutines.sync.withPermit--/**- * Writes [RemoteMeasurement]s into Health Connect. Uses a stable `clientRecordId`- * per measurement so re-running a sync upserts rather than duplicating. Mirrors the- * record-construction patterns in `health`'s HealthAPI / HealthSyncWorker.- */-object HealthSink {-    private const val TAG = "HealthSink"-    private const val INSERT_BATCH = 1000-    private const val INSERT_CONCURRENCY = 4-    private const val HR_SAMPLES_PER_RECORD = 1000-    private const val HR_RECORDS_PER_INSERT = 50 // bounds samples-per-insert (~50k)-    private val zone = ZoneId.systemDefault()--    suspend fun upsert(context: Context, measurements: List<RemoteMeasurement>) {-        if (measurements.isEmpty()) return-        val client = HealthConnectClient.getOrCreate(context)-        // Heart rate is a *series* record: collapse the many per-second/minute-        // samples into a handful of multi-sample records instead of one record-        // each. Same resolution, but ~1000x fewer records to insert.-        val (heartRate, other) = measurements.partition { it.type == MeasurementType.HEART_RATE }-        val hrRecords = heartRateSeries(heartRate)-        Log.status(-            TAG,-            "upsert: ${measurements.size} measurements " +-                "(${heartRate.size} HR samples -> ${hrRecords.size} HR series); " +-                measurements.groupingBy { it.type }.eachCount(),-        )-        // Batch sizes: HR series records each carry up to HR_SAMPLES_PER_RECORD-        // samples, so a batch of them is far larger than a batch of scalar records.-        // Keep HR batches small so a single insert doesn't blow past Health-        // Connect's per-transaction limits (which silently fails the whole call).-        // Build scalar records defensively: Health Connect validates value ranges-        // at construction (e.g. HRV RMSSD must be <= 200 ms), and a single bad-        // datapoint must never abort the whole sync — just skip it.-        val scalar = other.mapNotNull { safeRecord(it) }-        val batches = scalar.chunked(INSERT_BATCH) + hrRecords.chunked(HR_RECORDS_PER_INSERT)-        val semaphore = Semaphore(INSERT_CONCURRENCY)-        var inserted = 0-        coroutineScope {-            batches.map { batch ->-                async {-                    semaphore.withPermit {-                        try {-                            client.insertRecords(batch)-                            synchronized(this@HealthSink) { inserted += batch.size }-                        } catch (expected: Exception) {-                            Log.error(TAG, "insertRecords failed (${batch.size} records)", expected)-                        }-                    }-                }-            }.awaitAll()-        }-        Log.status(TAG, "upsert: inserted $inserted / ${scalar.size + hrRecords.size} records")-    }--    /**-     * Group heart-rate samples into series [HeartRateRecord]s (bucketed by civil-     * day, capped at [HR_SAMPLES_PER_RECORD] samples each). Deterministic-     * clientRecordIds keep re-syncing an overlapping window an idempotent upsert.-     */-    private fun heartRateSeries(measurements: List<RemoteMeasurement>): List<Record> {-        if (measurements.isEmpty()) return emptyList()-        val out = mutableListOf<Record>()-        measurements.groupBy { Instant.ofEpochMilli(it.startMillis).atZone(zone).toLocalDate() }-            .forEach { (day, dayMeasurements) ->-                dayMeasurements.sortedBy { it.startMillis }-                    .chunked(HR_SAMPLES_PER_RECORD)-                    .forEachIndexed { bucket, chunk ->-                        val samples = chunk.mapNotNull {-                            val bpm = it.value.toLong()-                            if (bpm in 1..300) HeartRateRecord.Sample(Instant.ofEpochMilli(it.startMillis), bpm)-                            else null-                        }-                        if (samples.isEmpty()) return@forEachIndexed-                        val startInst = samples.first().time-                        var endInst = samples.last().time-                        if (!endInst.isAfter(startInst)) endInst = startInst.plusMillis(1)-                        out += HeartRateRecord(-                            startTime = startInst,-                            startZoneOffset = zone.rules.getOffset(startInst),-                            endTime = endInst,-                            endZoneOffset = zone.rules.getOffset(endInst),-                            samples = samples,-                            metadata = Metadata.manualEntry(-                                clientRecordId = "googlehealth:HEART_RATE:$day:$bucket",-                            ),-                        )-                    }-            }-        return out-    }--    /** Construct a record, skipping (not crashing) on Health Connect range violations. */-    private fun safeRecord(m: RemoteMeasurement): Record? = try {-        toRecord(m)-    } catch (expected: Exception) {-        Log.status(TAG, "skipping ${m.type} (${m.value}) @ ${m.startMillis}: ${expected.message}")-        null-    }--    private fun toRecord(m: RemoteMeasurement): Record? {-        val start = Instant.ofEpochMilli(m.startMillis)-        val end = Instant.ofEpochMilli(m.endMillis)-        val startOffset = zone.rules.getOffset(start)-        val endOffset = zone.rules.getOffset(end)-        val meta = Metadata.manualEntry(clientRecordId = m.clientRecordId)-        val ctx = RecordContext(m, start, startOffset, end, endOffset, meta)-        return when (m.type) {-            MeasurementType.WEIGHT,-            MeasurementType.HEIGHT,-            MeasurementType.BODY_FAT,-            -> bodyCompositionRecord(ctx)-            MeasurementType.OXYGEN_SATURATION,-            MeasurementType.RESTING_HEART_RATE,-            MeasurementType.HEART_RATE_VARIABILITY,-            MeasurementType.RESPIRATORY_RATE,-            MeasurementType.BLOOD_GLUCOSE,-            MeasurementType.BODY_TEMPERATURE,-            MeasurementType.VO2_MAX,-            MeasurementType.HEART_RATE,-            -> vitalsRecord(ctx)-            MeasurementType.STEPS,-            MeasurementType.DISTANCE,-            MeasurementType.FLOORS,-            MeasurementType.ELEVATION,-            MeasurementType.ACTIVE_CALORIES,-            MeasurementType.TOTAL_CALORIES,-            MeasurementType.HYDRATION,-            -> activityRecord(ctx)-            MeasurementType.SLEEP,-            MeasurementType.EXERCISE,-            MeasurementType.NUTRITION,-            -> sessionRecord(ctx)-        }-    }--    private data class RecordContext(-        val m: RemoteMeasurement,-        val start: Instant,-        val startOffset: java.time.ZoneOffset,-        val end: Instant,-        val endOffset: java.time.ZoneOffset,-        val meta: Metadata,-    )--    private fun bodyCompositionRecord(ctx: RecordContext): Record {-        val m = ctx.m-        return when (m.type) {-            MeasurementType.WEIGHT ->-                WeightRecord(-                    time = ctx.start,-                    zoneOffset = ctx.startOffset,-                    weight = Mass.kilograms(m.value),-                    metadata = ctx.meta,-                )-            MeasurementType.HEIGHT ->-                HeightRecord(-                    time = ctx.start,-                    zoneOffset = ctx.startOffset,-                    height = Length.meters(m.value),-                    metadata = ctx.meta,-                )-            else ->-                BodyFatRecord(-                    time = ctx.start,-                    zoneOffset = ctx.startOffset,-                    percentage = Percentage(m.value),-                    metadata = ctx.meta,-                )-        }-    }--    private fun vitalsRecord(ctx: RecordContext): Record {-        val m = ctx.m-        return when (m.type) {-            MeasurementType.OXYGEN_SATURATION -> oxygenSaturation(ctx)-            MeasurementType.RESTING_HEART_RATE -> restingHeartRate(ctx)-            MeasurementType.HEART_RATE_VARIABILITY -> heartRateVariability(ctx)-            MeasurementType.RESPIRATORY_RATE -> respiratoryRate(ctx)-            MeasurementType.BLOOD_GLUCOSE -> bloodGlucose(ctx)-            MeasurementType.BODY_TEMPERATURE -> bodyTemperature(ctx)-            MeasurementType.VO2_MAX -> vo2Max(ctx)-            else -> heartRateSeries(ctx)-        }-    }--    private fun oxygenSaturation(ctx: RecordContext) = OxygenSaturationRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        percentage = Percentage(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun restingHeartRate(ctx: RecordContext) = RestingHeartRateRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        beatsPerMinute = ctx.m.value.toLong(),-        metadata = ctx.meta,-    )--    private fun heartRateVariability(ctx: RecordContext) = HeartRateVariabilityRmssdRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        heartRateVariabilityMillis = ctx.m.value,-        metadata = ctx.meta,-    )--    private fun respiratoryRate(ctx: RecordContext) = RespiratoryRateRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        rate = ctx.m.value,-        metadata = ctx.meta,-    )--    private fun bloodGlucose(ctx: RecordContext) = BloodGlucoseRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        level = BloodGlucose.milligramsPerDeciliter(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun bodyTemperature(ctx: RecordContext) = BodyTemperatureRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        temperature = Temperature.celsius(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun vo2Max(ctx: RecordContext) = Vo2MaxRecord(-        time = ctx.start,-        zoneOffset = ctx.startOffset,-        vo2MillilitersPerMinuteKilogram = ctx.m.value,-        metadata = ctx.meta,-    )--    private fun heartRateSeries(ctx: RecordContext) = HeartRateRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        samples = listOf(HeartRateRecord.Sample(ctx.start, ctx.m.value.toLong())),-        metadata = ctx.meta,-    )--    private fun activityRecord(ctx: RecordContext): Record {-        val m = ctx.m-        return when (m.type) {-            MeasurementType.STEPS -> steps(ctx)-            MeasurementType.DISTANCE -> distance(ctx)-            MeasurementType.FLOORS -> floors(ctx)-            MeasurementType.ELEVATION -> elevation(ctx)-            MeasurementType.ACTIVE_CALORIES -> activeCalories(ctx)-            MeasurementType.TOTAL_CALORIES -> totalCalories(ctx)-            else -> hydration(ctx)-        }-    }--    private fun steps(ctx: RecordContext) = StepsRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        count = ctx.m.value.toLong().coerceAtLeast(1),-        metadata = ctx.meta,-    )--    private fun distance(ctx: RecordContext) = DistanceRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        distance = Length.meters(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun floors(ctx: RecordContext) = FloorsClimbedRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        floors = ctx.m.value,-        metadata = ctx.meta,-    )--    private fun elevation(ctx: RecordContext) = ElevationGainedRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        elevation = Length.meters(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun activeCalories(ctx: RecordContext) = ActiveCaloriesBurnedRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        energy = Energy.kilocalories(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun totalCalories(ctx: RecordContext) = TotalCaloriesBurnedRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        energy = Energy.kilocalories(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun hydration(ctx: RecordContext) = HydrationRecord(-        startTime = ctx.start,-        startZoneOffset = ctx.startOffset,-        endTime = ctx.end,-        endZoneOffset = ctx.endOffset,-        volume = Volume.liters(ctx.m.value),-        metadata = ctx.meta,-    )--    private fun sessionRecord(ctx: RecordContext): Record {-        val m = ctx.m-        return when (m.type) {-            MeasurementType.SLEEP -> SleepSessionRecord(-                startTime = ctx.start,-                startZoneOffset = ctx.startOffset,-                endTime = ctx.end,-                endZoneOffset = ctx.endOffset,-                stages = m.sleepStages.map {-                    SleepSessionRecord.Stage(-                        startTime = Instant.ofEpochMilli(it.startMillis),-                        endTime = Instant.ofEpochMilli(it.endMillis),-                        stage = it.stage,-                    )-                },-                metadata = ctx.meta,-            )-            MeasurementType.EXERCISE -> ExerciseSessionRecord(-                startTime = ctx.start,-                startZoneOffset = ctx.startOffset,-                endTime = ctx.end,-                endZoneOffset = ctx.endOffset,-                exerciseType = m.exerciseType,-                title = m.title,-                notes = m.notes,-                metadata = ctx.meta,-            )-            else -> nutritionRecord(-                m,-                ctx.start,-                ctx.startOffset,-                ctx.end,-                ctx.endOffset,-                ctx.meta,-            )-        }-    }--    private fun nutritionRecord(-        m: RemoteMeasurement,-        start: Instant,-        startOffset: java.time.ZoneOffset,-        end: Instant,-        endOffset: java.time.ZoneOffset,-        meta: Metadata,-    ): NutritionRecord {-        val n: RemoteNutrition = m.nutrition ?: RemoteNutrition()-        fun g(key: String) = n.nutrientGrams[key]?.let { Mass.grams(it) }-        return NutritionRecord(-            startTime = start, startZoneOffset = startOffset,-            endTime = end, endZoneOffset = endOffset,-            name = m.title,-            energy = n.energyKcal?.let { Energy.kilocalories(it) },-            totalFat = g("TOTAL_FAT"),-            totalCarbohydrate = g("TOTAL_CARBOHYDRATE"),-            protein = g("PROTEIN"),-            dietaryFiber = g("DIETARY_FIBER"),-            sugar = g("SUGAR"),-            sodium = g("SODIUM"),-            biotin = g("BIOTIN"),-            caffeine = g("CAFFEINE"),-            calcium = g("CALCIUM"),-            chloride = g("CHLORIDE"),-            cholesterol = g("CHOLESTEROL"),-            chromium = g("CHROMIUM"),-            copper = g("COPPER"),-            folate = g("FOLATE"),-            folicAcid = g("FOLIC_ACID"),-            iodine = g("IODINE"),-            iron = g("IRON"),-            magnesium = g("MAGNESIUM"),-            manganese = g("MANGANESE"),-            molybdenum = g("MOLYBDENUM"),-            monounsaturatedFat = g("MONOUNSATURATED_FAT"),-            niacin = g("NIACIN"),-            pantothenicAcid = g("PANTOTHENIC_ACID"),-            phosphorus = g("PHOSPHORUS"),-            polyunsaturatedFat = g("POLYUNSATURATED_FAT"),-            potassium = g("POTASSIUM"),-            riboflavin = g("RIBOFLAVIN"),-            saturatedFat = g("SATURATED_FAT"),-            selenium = g("SELENIUM"),-            thiamin = g("THIAMIN"),-            transFat = g("TRANS_FAT"),-            unsaturatedFat = g("UNSATURATED_FAT"),-            vitaminA = g("VITAMIN_A"),-            vitaminB12 = g("VITAMIN_B12"),-            vitaminB6 = g("VITAMIN_B6"),-            vitaminC = g("VITAMIN_C"),-            vitaminD = g("VITAMIN_D"),-            vitaminE = g("VITAMIN_E"),-            vitaminK = g("VITAMIN_K"),-            zinc = g("ZINC"),-            metadata = meta,-        )-    }-}
everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.ktnew file mode 100644index 0000000000..ffe816320b--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/NoteSink.kt@@ -0,0 +1,305 @@+package com.vayunmathur.everysync.data.sink++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import androidx.core.database.getLongOrNull+import androidx.core.database.getStringOrNull+import com.vayunmathur.everysync.data.RemoteNote+import com.vayunmathur.everysync.sync.adapters.NoteKind+import com.vayunmathur.library.log.Log+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/** A locally-changed note row detected via the app provider's timestamp watermark. */+data class LocalNoteChange(+    val syncId: String,+    val updatedAt: Long,+    val deleted: Boolean,+    val note: RemoteNote?,+)++/**+ * Reads/writes note records through the notes app's relay ContentProvider+ * (owned by task 3 — the `notes/` app). The contract mirrors the provider+ * exactly:+ *+ * - authority: `com.vayunmathur.notes.relay` (signature-protected)+ * - URIs: base table URIs (`.../vault/<id>/notes`, `.../snapshots`) plus the+ *   op-suffixed forms (`.../notes/querySince`, `.../notes/upsertRaw`,+ *   `.../notes/deleteByVault`, same for snapshots). The vault id segment is+ *   accepted but ignored: the app holds a single vault.+ * - query: `?since=<ms>` query parameter first, `selectionArgs[0]` as+ *   fallback, for deltas (tombstones included — notes soft-delete); no bound+ *   lists the current full state.+ * - `payloadJson` is the **envelope JSON** ([RemoteNote] bytes via+ *   [NoteKind.toJson] — the exact relay-log bytes, with `uid` identity).+ *   The provider emits envelopes and accepts envelopes primarily; the native+ *   row shape is accepted as fallback. Reads accept both via [fromPayload]+ *   (envelope first, native fallback) so no row is ever silently dropped.+ * - upsert: `insert`/`update` with `ContentValues(payloadJson)` carrying the+ *   **envelope JSON**, preserving the pulled timestamp and relay identity+ *   (`uid` -> `syncId`). A `deleted` envelope tombstones the row instead of+ *   hard-deleting it, so the deletion propagates via the next `querySince`.+ * - delete: a non-null selection with `selectionArgs[0]` = syncId tombstones+ *   one row; `deleteByVault` (or selection-less base delete) purges the whole+ *   table *and* its snapshots.+ * - columns: `syncId`, `updatedAt`, `deleted` (0/1), `payloadJson`,+ *   `contentHash` (payload SHA-256 hex; the merge driver recomputes+ *   canonical hashes itself via [NoteKind] and ignores this column on read).+ */+object NoteSink {+    private const val TAG = "NoteSink"++    const val AUTHORITY = "com.vayunmathur.notes.relay"+    const val PATH_NOTES = "notes"+    const val PATH_SNAPSHOTS = "snapshots"+    const val OP_QUERY_SINCE = "querySince"+    const val OP_UPSERT_RAW = "upsertRaw"+    const val OP_DELETE_BY_VAULT = "deleteByVault"+    const val COL_SYNC_ID = "syncId"+    const val COL_UPDATED_AT = "updatedAt"+    const val COL_DELETED = "deleted"+    const val COL_PAYLOAD_JSON = "payloadJson"+    const val COL_CONTENT_HASH = "contentHash"+    const val PARAM_SINCE = "since"++    private val json = Json { ignoreUnknownKeys = true }++    fun notesUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_NOTES")++    fun snapshotsUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_SNAPSHOTS")++    fun queryUri(vaultId: String): Uri =+        notesUri(vaultId).buildUpon().appendPath(OP_QUERY_SINCE).build()++    fun upsertUri(vaultId: String): Uri =+        notesUri(vaultId).buildUpon().appendPath(OP_UPSERT_RAW).build()++    fun purgeUri(vaultId: String, table: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$table")+            .buildUpon().appendPath(OP_DELETE_BY_VAULT).build()++    /** Relay envelope for [note] (adapter bytes — what the relay log carries). */+    fun toRelayJson(note: RemoteNote): String = NoteKind.toJson(note)++    /** Native row JSON for [note] (what the provider persists verbatim). */+    fun toNativeJson(note: RemoteNote): String =+        json.encodeToString(+            NativeNote(+                title = note.title,+                content = note.content,+                position = note.position,+                blocks = note.blocksJson,+                syncId = note.uid,+                updatedAt = note.updatedAt,+                deleted = note.deleted,+            ),+        )++    /**+     * Parses a `payloadJson` value back into relay form. Accepts the envelope+     * shape first (what the provider emits) and the native row shape as+     * fallback; null skips corrupt/foreign rows.+     */+    fun fromPayload(payload: String): RemoteNote? {+        fromRelayJson(payload)?.let { return it }+        return fromNativeJson(payload)+    }++    /** Parses a native row payload; null skips non-native rows. */+    fun fromNativeJson(payload: String): RemoteNote? = runCatching {+        val n = json.decodeFromString<NativeNote>(payload)+        RemoteNote(+            uid = n.syncId,+            title = n.title,+            content = n.content,+            blocksJson = n.blocks,+            position = n.position,+            deleted = n.deleted,+            updatedAt = n.updatedAt,+        )+    }.getOrNull()?.takeIf { it.uid.isNotBlank() }++    /** Parses an envelope payload back; null skips corrupt/foreign rows. */+    fun fromRelayJson(payload: String): RemoteNote? =+        NoteKind.fromJson(payload)?.takeIf { it.uid.isNotBlank() }++    /** Map of relay syncId → updatedAt currently present locally for this vault. */+    fun localUidToEtag(context: Context, vaultId: String): Map<String, Long?> {+        val result = mutableMapOf<String, Long?>()+        // Full state, live rows only (tombstones are filtered — the merge+        // reads them via listLocal).+        try {+            context.contentResolver.query(+                notesUri(vaultId),+                arrayOf(COL_SYNC_ID, COL_UPDATED_AT),+                "$COL_DELETED = 0",+                null,+                null,+            )?.use { c ->+                val idIdx = c.getColumnIndex(COL_SYNC_ID)+                val tsIdx = c.getColumnIndex(COL_UPDATED_AT)+                while (c.moveToNext()) {+                    val uid = (if (idIdx >= 0) c.getStringOrNull(idIdx) else null) ?: continue+                    result[uid] = if (tsIdx >= 0) c.getLongOrNull(tsIdx) else null+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "localUidToEtag failed", expected)+        }+        return result+    }++    /** All local rows in relay form, tombstones included (notes soft-delete). */+    fun listLocal(context: Context, vaultId: String): List<RemoteNote> {+        val out = mutableListOf<RemoteNote>()+        try {+            context.contentResolver.query(+                notesUri(vaultId),+                arrayOf(COL_PAYLOAD_JSON),+                null,+                null,+                null,+            )?.use { c ->+                val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                while (c.moveToNext()) {+                    val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                    if (!payload.isNullOrBlank()) {+                        fromPayload(payload)?.let { out += it }+                    }+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "listLocal failed", expected)+        }+        return out+    }++    /** Idempotent upsert keyed on [RemoteNote.uid]; preserves the relay identity + timestamp. */+    fun upsert(context: Context, vaultId: String, note: RemoteNote) {+        try {+            context.contentResolver.insert(+                upsertUri(vaultId),+                ContentValues().apply { put(COL_PAYLOAD_JSON, toRelayJson(note)) },+            )+        } catch (expected: Exception) {+            Log.error(TAG, "upsert failed", expected)+        }+    }++    /** Bulk upsert for merge results; one IPC call per row like the single form. */+    fun upsertAll(context: Context, vaultId: String, notes: List<RemoteNote>) {+        for (note in notes) upsert(context, vaultId, note)+    }++    /**+     * Applies a pulled relay tombstone (or a local delete ack) by tombstoning+     * the row: non-null selection + syncId deletes (tombstones) exactly one row.+     */+    fun delete(context: Context, vaultId: String, uid: String) {+        try {+            context.contentResolver.delete(+                notesUri(vaultId),+                "$COL_SYNC_ID = ?",+                arrayOf(uid),+            )+        } catch (expected: Exception) {+            Log.error(TAG, "delete failed", expected)+        }+    }++    /** Bulk tombstone for merge garbage collection. */+    fun deleteAll(context: Context, vaultId: String, uids: List<String>) {+        for (uid in uids) delete(context, vaultId, uid)+    }++    /**+     * Removes every note row (and snapshots) for this vault from the app+     * provider. Used when the user turns note sync off; the vault itself+     * stays, so a later re-enable repopulates it from a fresh pull.+     */+    fun purge(context: Context, accountName: String, vaultId: String) {+        for (table in listOf(PATH_NOTES, PATH_SNAPSHOTS)) {+            try {+                context.contentResolver.delete(purgeUri(vaultId, table), null, null)+            } catch (expected: Exception) {+                Log.error(TAG, "purge failed for $table", expected)+            }+        }+    }++    /** Back-compat overload for account-scoped callers that track a single vault per account. */+    fun purge(context: Context, accountName: String) {+        purge(context, accountName, accountName)+    }++    /**+     * Rows changed locally since [since] (via `?since=`), tombstones included+     * (notes soft-delete, so deletes propagate as rows with `deleted=1`).+     */+    fun getLocalChanges(context: Context, vaultId: String, since: Long = 0L): List<LocalNoteChange> {+        val changes = mutableListOf<LocalNoteChange>()+        try {+            context.contentResolver.query(+                queryUri(vaultId).buildUpon()+                    .appendQueryParameter(PARAM_SINCE, since.toString()).build(),+                arrayOf(COL_SYNC_ID, COL_UPDATED_AT, COL_DELETED, COL_PAYLOAD_JSON),+                null,+                null,+                null,+            )?.use { c ->+                val idIdx = c.getColumnIndex(COL_SYNC_ID)+                val tsIdx = c.getColumnIndex(COL_UPDATED_AT)+                val delIdx = c.getColumnIndex(COL_DELETED)+                val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                while (c.moveToNext()) {+                    val uid = (if (idIdx >= 0) c.getStringOrNull(idIdx) else null) ?: continue+                    val deleted = delIdx >= 0 && c.getInt(delIdx) == 1+                    val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                    changes += LocalNoteChange(+                        syncId = uid,+                        updatedAt = if (tsIdx >= 0) c.getLong(tsIdx) else 0L,+                        deleted = deleted,+                        note = if (deleted || payload.isNullOrBlank()) {+                            null+                        } else {+                            fromPayload(payload)+                        },+                    )+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "getLocalChanges failed", expected)+        }+        return changes+    }++    /**+     * Marks locally-pushed rows clean after a successful relay append. No-op:+     * rows applied via `upsertRaw` keep their remote `updatedAt`, which sits+     * at or below the push watermark, so fresh pulls never look dirty.+     */+    fun clearDirty(context: Context, vaultId: String, syncId: String) {+        // Timestamp-watermark providers need no explicit clean bit; kept for+        // API parity with ContactsSink/CalendarSink.+    }++    /**+     * Native `Note` JSON shape (mirrors the notes app's model without+     * depending on its module: `id` is per-device so it is never synced).+     */+    @Serializable+    internal data class NativeNote(+        val title: String = "",+        val content: String = "",+        val position: Double = 0.0,+        val blocks: String? = null,+        val syncId: String = "",+        val updatedAt: Long = 0L,+        val deleted: Boolean = false,+    )+}
everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.ktnew file mode 100644index 0000000000..9c70d25f6f--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/PasswordSink.kt@@ -0,0 +1,398 @@+package com.vayunmathur.everysync.data.sink++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import androidx.core.database.getLongOrNull+import androidx.core.database.getStringOrNull+import com.vayunmathur.everysync.data.RemotePassword+import com.vayunmathur.everysync.sync.adapters.PasswordKind+import com.vayunmathur.library.log.Log+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/** A locally-changed password/passkey row detected via the app provider's timestamp watermark. */+data class LocalPasswordChange(+    val syncId: String,+    val isPasskey: Boolean,+    val updatedAt: Long,+    val deleted: Boolean,+    val password: RemotePassword?,+)++/**+ * Passkey payload carrier for the native row JSON. The passwords app's+ * `Passkey` is not `@Serializable`, so it crosses IPC as this plain carrier+ * with base64 bytes — field names mirror the provider side (`syncId`, and+ * `privateKeyBase64` for the key bytes).+ */+@Serializable+internal data class PasskeyPayload(+    val id: Long = 0,+    val rpId: String = "",+    val rpName: String = "",+    val credentialId: String = "",+    val userId: String = "",+    val userName: String = "",+    val userDisplayName: String = "",+    val privateKeyBase64: String = "",+    val creationTime: Long = 0,+    val lastUsedTime: Long = 0,+    val signCount: Int = 0,+    val linkedPasswordSyncId: String? = null,+    val syncId: String = "",+    val updatedAt: Long = 0,+)++/**+ * Reads/writes password + passkey records through the passwords app's relay+ * ContentProvider (owned by task 3 — the `passwords/` app). The contract+ * mirrors the provider exactly:+ *+ * - authority: `com.vayunmathur.passwords.relay` (signature-protected)+ * - URIs: base table URIs (`.../vault/<id>/passwords`, `.../passkeys`,+ *   `.../snapshots`) plus the op-suffixed forms (`.../passwords/querySince`,+ *   `.../passwords/upsertRaw`, `.../passwords/deleteByVault`, same for+ *   passkeys/snapshots). The vault id segment is accepted but ignored: the+ *   app holds a single vault.+ * - query: `?since=<ms>` query parameter first, `selectionArgs[0]` as+ *   fallback, for deltas; no bound lists the current full state.+ * - `payloadJson` is the **envelope JSON** ([RemotePassword] bytes via+ *   [PasswordKind.toJson] — the exact relay-log bytes, with `uid` identity).+ *   The provider emits envelopes and accepts envelopes primarily; native row+ *   shapes are accepted as fallback for older sinks. Reads accept both via+ *   [fromPayload] (envelope first, native fallback) so no row is ever+ *   silently dropped.+ * - upsert: `insert`/`update` with `ContentValues(payloadJson)` carrying the+ *   **envelope JSON**, preserving the pulled timestamp and relay identity+ *   (`uid` -> `syncId`). A `deleted` envelope hard-deletes the row instead+ *   (snapshot retained app-side so the merge reads it as a deletion).+ * - delete: a `syncId = ?` selection hard-deletes one row (snapshot kept);+ *   `deleteByVault` (or selection-less base delete) purges the whole table+ *   *and* its snapshots.+ * - columns: `syncId`, `updatedAt`, `deleted`, `payloadJson`, `contentHash`+ *   (payload SHA-256 hex; the merge driver recomputes canonical hashes+ *   itself via [PasswordKind] and ignores this column on read).+ * - deletes: passwords/passkeys hard-delete locally (`deleted` is always 0 in+ *   query results); tombstones live only on the relay side.+ *+ * `RemotePassword.uid` is the relay sync identity; passkeys (`isPasskey`)+ * ride the same `passwords:<vaultId>` channel and are told apart by the flag+ * (see `PasswordKind`).+ */+object PasswordSink {+    private const val TAG = "PasswordSink"++    const val AUTHORITY = "com.vayunmathur.passwords.relay"+    const val PATH_PASSWORDS = "passwords"+    const val PATH_PASSKEYS = "passkeys"+    const val PATH_SNAPSHOTS = "snapshots"+    const val OP_QUERY_SINCE = "querySince"+    const val OP_UPSERT_RAW = "upsertRaw"+    const val OP_DELETE_BY_VAULT = "deleteByVault"+    const val COL_SYNC_ID = "syncId"+    const val COL_UPDATED_AT = "updatedAt"+    const val COL_DELETED = "deleted"+    const val COL_PAYLOAD_JSON = "payloadJson"+    const val COL_CONTENT_HASH = "contentHash"+    const val PARAM_SINCE = "since"++    private val json = Json { ignoreUnknownKeys = true }++    fun passwordsUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_PASSWORDS")++    fun passkeysUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_PASSKEYS")++    fun snapshotsUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_SNAPSHOTS")++    fun queryUri(vaultId: String, isPasskey: Boolean): Uri =+        tableUri(vaultId, isPasskey).buildUpon()+            .appendPath(OP_QUERY_SINCE).build()++    fun upsertUri(vaultId: String, isPasskey: Boolean): Uri =+        tableUri(vaultId, isPasskey).buildUpon()+            .appendPath(OP_UPSERT_RAW).build()++    fun purgeUri(vaultId: String, table: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$table")+            .buildUpon().appendPath(OP_DELETE_BY_VAULT).build()++    private fun tableUri(vaultId: String, isPasskey: Boolean): Uri =+        if (isPasskey) passkeysUri(vaultId) else passwordsUri(vaultId)++    /** Relay envelope for [password] (adapter bytes — what the relay log carries). */+    fun toRelayJson(password: RemotePassword): String = PasswordKind.toJson(password)++    /** Native row JSON for [password] (what the provider persists verbatim). */+    fun toNativeJson(password: RemotePassword): String =+        if (password.isPasskey) {+            json.encodeToString(+                PasskeyPayload(+                    rpId = password.rpId,+                    rpName = password.rpName,+                    credentialId = password.credentialId,+                    userId = password.userId,+                    userName = password.userName,+                    userDisplayName = password.userDisplayName,+                    privateKeyBase64 = password.privateKeyB64,+                    creationTime = password.creationTime,+                    lastUsedTime = password.lastUsedTime,+                    signCount = password.signCount,+                    linkedPasswordSyncId = password.linkedPasswordSyncId,+                    syncId = password.uid,+                    updatedAt = password.updatedAt,+                ),+            )+        } else {+            json.encodeToString(+                NativePassword(+                    name = password.name,+                    username = password.username,+                    email = password.email,+                    password = password.password,+                    note = password.note,+                    totpSecret = password.totpSecret,+                    websites = password.websites,+                    syncId = password.uid,+                    updatedAt = password.updatedAt,+                ),+            )+        }++    /**+     * Parses a `payloadJson` value back into relay form. Accepts the envelope+     * shape first (what the provider emits) and the native row shapes as+     * fallback; null skips corrupt/foreign rows.+     */+    fun fromPayload(payload: String, isPasskey: Boolean): RemotePassword? {+        fromRelayJson(payload)?.let { return it }+        return fromNativeJson(payload, isPasskey)+    }++    /** Parses a native row payload; null skips non-native rows. */+    fun fromNativeJson(payload: String, isPasskey: Boolean): RemotePassword? = runCatching {+        if (isPasskey) {+            val p = json.decodeFromString<PasskeyPayload>(payload)+            RemotePassword(+                uid = p.syncId,+                isPasskey = true,+                rpId = p.rpId,+                rpName = p.rpName,+                credentialId = p.credentialId,+                userId = p.userId,+                userName = p.userName,+                userDisplayName = p.userDisplayName,+                privateKeyB64 = p.privateKeyBase64,+                creationTime = p.creationTime,+                lastUsedTime = p.lastUsedTime,+                signCount = p.signCount,+                linkedPasswordSyncId = p.linkedPasswordSyncId,+                updatedAt = p.updatedAt,+            )+        } else {+            val p = json.decodeFromString<NativePassword>(payload)+            RemotePassword(+                uid = p.syncId,+                name = p.name,+                username = p.username,+                email = p.email,+                password = p.password,+                note = p.note,+                totpSecret = p.totpSecret,+                websites = p.websites,+                updatedAt = p.updatedAt,+            )+        }+    }.getOrNull()?.takeIf { it.uid.isNotBlank() }++    /** Parses an envelope payload back; null skips corrupt/foreign rows. */+    fun fromRelayJson(payload: String): RemotePassword? =+        PasswordKind.fromJson(payload)?.takeIf { it.uid.isNotBlank() }++    /** Map of relay syncId → updatedAt currently present locally for this vault. */+    fun localUidToEtag(context: Context, vaultId: String): Map<String, Long?> {+        val result = mutableMapOf<String, Long?>()+        // Full state, no bound: live rows only (passwords hard-delete, so no+        // tombstone filtering needed).+        for (uri in listOf(passwordsUri(vaultId), passkeysUri(vaultId))) {+            try {+                context.contentResolver.query(+                    uri,+                    arrayOf(COL_SYNC_ID, COL_UPDATED_AT),+                    null,+                    null,+                    null,+                )?.use { c ->+                    val idIdx = c.getColumnIndex(COL_SYNC_ID)+                    val tsIdx = c.getColumnIndex(COL_UPDATED_AT)+                    while (c.moveToNext()) {+                        val uid = (if (idIdx >= 0) c.getStringOrNull(idIdx) else null) ?: continue+                        result[uid] = if (tsIdx >= 0) c.getLongOrNull(tsIdx) else null+                    }+                }+            } catch (expected: Exception) {+                Log.error(TAG, "localUidToEtag failed for $uri", expected)+            }+        }+        return result+    }++    /** All local rows in relay form (tombstones never occur locally — hard deletes). */+    fun listLocal(context: Context, vaultId: String): List<RemotePassword> {+        val out = mutableListOf<RemotePassword>()+        for ((uri, isPasskey) in listOf(passwordsUri(vaultId) to false, passkeysUri(vaultId) to true)) {+            try {+                context.contentResolver.query(+                    uri,+                    arrayOf(COL_PAYLOAD_JSON),+                    null,+                    null,+                    null,+                )?.use { c ->+                    val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                    while (c.moveToNext()) {+                        val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                        if (!payload.isNullOrBlank()) {+                            fromPayload(payload, isPasskey)?.let { out += it }+                        }+                    }+                }+            } catch (expected: Exception) {+                Log.error(TAG, "listLocal failed for $uri", expected)+            }+        }+        return out+    }++    /** Idempotent upsert keyed on [RemotePassword.uid]; preserves the relay identity + timestamp. */+    fun upsert(context: Context, vaultId: String, password: RemotePassword) {+        try {+            context.contentResolver.insert(+                upsertUri(vaultId, password.isPasskey),+                ContentValues().apply { put(COL_PAYLOAD_JSON, toRelayJson(password)) },+            )+        } catch (expected: Exception) {+            Log.error(TAG, "upsert failed", expected)+        }+    }++    /** Bulk upsert for merge results; one IPC call per row like the single form. */+    fun upsertAll(context: Context, vaultId: String, passwords: List<RemotePassword>) {+        for (password in passwords) upsert(context, vaultId, password)+    }++    /**+     * Applies a pulled relay tombstone (or a local delete ack) by hard-deleting+     * the row: `syncId = ?` selection deletes exactly one row (snapshot kept+     * app-side so the merge reads it as a deletion).+     */+    fun delete(context: Context, vaultId: String, uid: String, isPasskey: Boolean = false) {+        try {+            context.contentResolver.delete(+                tableUri(vaultId, isPasskey),+                "$COL_SYNC_ID = ?",+                arrayOf(uid),+            )+        } catch (expected: Exception) {+            Log.error(TAG, "delete failed", expected)+        }+    }++    /** Bulk hard-delete for merge garbage collection. */+    fun deleteAll(context: Context, vaultId: String, uids: List<Pair<String, Boolean>>) {+        for ((uid, isPasskey) in uids) delete(context, vaultId, uid, isPasskey)+    }++    /**+     * Removes every password + passkey row (and snapshots) for this vault from+     * the app provider. Used when the user turns password sync off; the vault+     * itself stays, so a later re-enable repopulates it from a fresh pull.+     */+    fun purge(context: Context, accountName: String, vaultId: String) {+        for (table in listOf(PATH_PASSWORDS, PATH_PASSKEYS, PATH_SNAPSHOTS)) {+            try {+                context.contentResolver.delete(purgeUri(vaultId, table), null, null)+            } catch (expected: Exception) {+                Log.error(TAG, "purge failed for $table", expected)+            }+        }+    }++    /** Back-compat overload for account-scoped callers that track a single vault per account. */+    fun purge(context: Context, accountName: String) {+        purge(context, accountName, accountName)+    }++    /**+     * Rows changed locally since [since] (`updatedAt > since`, via `?since=`).+     * Passwords never report tombstones (hard deletes); a delete is observed+     * as "present at baseline, absent now" by the merge.+     */+    fun getLocalChanges(context: Context, vaultId: String, since: Long = 0L): List<LocalPasswordChange> {+        val changes = mutableListOf<LocalPasswordChange>()+        for ((table, isPasskey) in listOf(PATH_PASSWORDS to false, PATH_PASSKEYS to true)) {+            try {+                context.contentResolver.query(+                    queryUri(vaultId, isPasskey).buildUpon()+                        .appendQueryParameter(PARAM_SINCE, since.toString()).build(),+                    arrayOf(COL_SYNC_ID, COL_UPDATED_AT, COL_PAYLOAD_JSON),+                    null,+                    null,+                    null,+                )?.use { c ->+                    val idIdx = c.getColumnIndex(COL_SYNC_ID)+                    val tsIdx = c.getColumnIndex(COL_UPDATED_AT)+                    val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                    while (c.moveToNext()) {+                        val uid = (if (idIdx >= 0) c.getStringOrNull(idIdx) else null) ?: continue+                        val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                        // Table determines the half; the parsed flag is+                        // authoritative when present, table otherwise.+                        val parsed = if (payload.isNullOrBlank()) null else fromPayload(payload, isPasskey)+                        changes += LocalPasswordChange(+                            syncId = uid,+                            isPasskey = parsed?.isPasskey ?: isPasskey,+                            updatedAt = if (tsIdx >= 0) c.getLong(tsIdx) else 0L,+                            deleted = false,+                            password = parsed,+                        )+                    }+                }+            } catch (expected: Exception) {+                Log.error(TAG, "getLocalChanges failed for $table", expected)+            }+        }+        return changes+    }++    /**+     * Marks locally-pushed rows clean after a successful relay append. No-op:+     * rows applied via `upsertRaw` keep their remote `updatedAt`, which sits+     * at or below the push watermark, so fresh pulls never look dirty.+     */+    fun clearDirty(context: Context, vaultId: String, syncId: String) {+        // Timestamp-watermark providers need no explicit clean bit; kept for+        // API parity with ContactsSink/CalendarSink.+    }++    /**+     * Native `Password` JSON shape (mirrors the passwords app's model without+     * depending on its module: `id` is per-device so it is never synced).+     */+    @Serializable+    internal data class NativePassword(+        val name: String = "",+        val username: String = "",+        val email: String = "",+        val password: String = "",+        val note: String = "",+        val totpSecret: String? = null,+        val websites: List<String> = emptyList(),+        val syncId: String = "",+        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.ktnew file mode 100644index 0000000000..1aa2b9fd33--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/sink/TodoIpcSink.kt@@ -0,0 +1,237 @@+package com.vayunmathur.everysync.data.sink++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import androidx.core.database.getLongOrNull+import androidx.core.database.getStringOrNull+import com.vayunmathur.everysync.data.RemoteTodo+import com.vayunmathur.everysync.sync.adapters.TodoKind+import com.vayunmathur.library.log.Log++/** A locally-changed todo row detected via the app provider's timestamp watermark. */+data class LocalTodoChange(+    val syncId: String,+    val updatedAt: Long,+    val deleted: Boolean,+    val todo: RemoteTodo?,+)++/**+ * Reads/writes todo records through the todo app's relay ContentProvider+ * (owned by the `todo/` app). The contract mirrors the provider exactly:+ *+ * - authority: `com.vayunmathur.todo.relay` (signature-protected)+ * - URIs: base table URIs (`.../vault/<id>/todos`, `.../snapshots`) plus the+ *   op-suffixed forms (`.../todos/querySince`, `.../todos/upsertRaw`,+ *   `.../todos/deleteByVault`, same for snapshots). The vault id segment is+ *   accepted but ignored: the app holds a single vault.+ * - query: `?since=<ms>` query parameter first, `selectionArgs[0]` as+ *   fallback, for deltas (tombstones included — todos soft-delete); no bound+ *   lists the current full state.+ * - upsert: `insert`/`update` with `ContentValues(payloadJson)` carrying the+ *   **envelope JSON** ([RemoteTodo] bytes via [TodoKind.toJson]), preserving+ *   the pulled timestamp 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`.+ * - delete: a non-null selection with `selectionArgs[0]` = syncId tombstones+ *   one row; `deleteByVault` (or selection-less base delete) purges the whole+ *   table *and* its snapshots.+ * - columns: `syncId`, `updatedAt`, `deleted` (0/1), `payloadJson`,+ *   `contentHash` (canonical-envelope SHA-256 hex, merge-compatible with+ *   [TodoKind]).+ *+ * API mirrors [NoteSink] (`localUidToEtag` / `upsert` / `delete` / `purge` /+ * `getLocalChanges`) so the relay driver treats all app vault types uniformly.+ * `RemoteTodo.uid` is the relay sync identity. Distinct from the [TodoSink]+ * merge-driver interface, which is keyed on typed lists rather than IPC.+ */+object TodoIpcSink {+    private const val TAG = "TodoIpcSink"++    const val AUTHORITY = "com.vayunmathur.todo.relay"+    const val PATH_TODOS = "todos"+    const val PATH_SNAPSHOTS = "snapshots"+    const val OP_QUERY_SINCE = "querySince"+    const val OP_UPSERT_RAW = "upsertRaw"+    const val OP_DELETE_BY_VAULT = "deleteByVault"+    const val COL_SYNC_ID = "syncId"+    const val COL_UPDATED_AT = "updatedAt"+    const val COL_DELETED = "deleted"+    const val COL_PAYLOAD_JSON = "payloadJson"+    const val COL_CONTENT_HASH = "contentHash"+    const val PARAM_SINCE = "since"++    fun todosUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_TODOS")++    fun snapshotsUri(vaultId: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$PATH_SNAPSHOTS")++    fun queryUri(vaultId: String): Uri =+        todosUri(vaultId).buildUpon().appendPath(OP_QUERY_SINCE).build()++    fun upsertUri(vaultId: String): Uri =+        todosUri(vaultId).buildUpon().appendPath(OP_UPSERT_RAW).build()++    fun purgeUri(vaultId: String, table: String): Uri =+        Uri.parse("content://$AUTHORITY/vault/$vaultId/$table")+            .buildUpon().appendPath(OP_DELETE_BY_VAULT).build()++    /** Relay envelope for [todo] (adapter bytes — what the relay log carries). */+    fun toRelayJson(todo: RemoteTodo): String = TodoKind.toJson(todo)++    /** Parses an envelope payload back; null skips corrupt/foreign rows. */+    fun fromRelayJson(payload: String): RemoteTodo? =+        TodoKind.fromJson(payload)?.takeIf { it.uid.isNotBlank() }++    /** Map of relay syncId → updatedAt currently present locally for this vault. */+    fun localUidToEtag(context: Context, vaultId: String): Map<String, Long?> {+        val result = mutableMapOf<String, Long?>()+        // Full state, live rows only (tombstones are filtered — the merge+        // reads them via listLocal).+        try {+            context.contentResolver.query(+                todosUri(vaultId),+                arrayOf(COL_SYNC_ID, COL_UPDATED_AT),+                "$COL_DELETED = 0",+                null,+                null,+            )?.use { c ->+                val idIdx = c.getColumnIndex(COL_SYNC_ID)+                val tsIdx = c.getColumnIndex(COL_UPDATED_AT)+                while (c.moveToNext()) {+                    val uid = (if (idIdx >= 0) c.getStringOrNull(idIdx) else null) ?: continue+                    result[uid] = if (tsIdx >= 0) c.getLongOrNull(tsIdx) else null+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "localUidToEtag failed", expected)+        }+        return result+    }++    /** All local rows in relay form, tombstones included (todos soft-delete). */+    fun listLocal(context: Context, vaultId: String): List<RemoteTodo> {+        val out = mutableListOf<RemoteTodo>()+        try {+            context.contentResolver.query(+                todosUri(vaultId),+                arrayOf(COL_PAYLOAD_JSON),+                null,+                null,+                null,+            )?.use { c ->+                val payloadIdx = c.getColumnIndex(COL_PAYLOAD_JSON)+                while (c.moveToNext()) {+                    val payload = if (payloadIdx >= 0) c.getStringOrNull(payloadIdx) else null+                    if (!payload.isNullOrBlank()) {+                        fromRelayJson(payload)?.let { out += it }+                    }+                }+            }+        } catch (expected: Exception) {+            Log.error(TAG, "listLocal failed", expected)+        }+        return out+    }++    /** Idempotent upsert keyed on [RemoteTodo.uid]; preserves the relay identity + timestamp. */+    fun upsert(context: Context, vaultId: String, todo: RemoteTodo) {+        try {+            context.contentResolver.insert(+                upsertUri(vaultId),+                ContentValues().apply { put(COL_PAYLOAD_JSON, toRelayJson(todo)) },+            )+        } catch (expected: Exception) {+            Log.error(TAG, "upsert failed", expected)+        }+    }++    /** Bulk upsert for merge results; one IPC call per row like the single form. */+    fun upsertAll(context: Context, vaultId: String, todos: List<RemoteTodo>) {+        for (todo in todos) upsert(context, vaultId, todo)+    }++    /**+     * Applies a pulled relay tombstone (or a local delete ack) by tombstoning+     * the row: non-null selection + syncId deletes (tombstones) exactly one row.+     */+    fun delete(context: Context, vaultId: String, uid: String) {+        try {+            context.contentResolver.delete(+                todosUri(vaultId),+                "$COL_SYNC_ID = ?",+                arrayOf(uid),+            )+        } catch (expected: Exception) {+            Log.error(TAG, "delete failed", expected)+        }+    }++    /** Bulk tombstone for merge garbage collection. */+    fun deleteAll(con

Diff truncated.