Modern Apps git

← Modern-Apps.git

wear: notes companion on first-party WearLink

Commit
65ec1f76946f1b65b5bb9bb54c4d5317edeba5dd
Author
Vayun Mathur <[email protected]>
When
2026-11-24 18:51 UTC (11 days ago)
Parents
cbbf7ec
New :notes-wear module (same package/signing as phone
Notes): watch list/view/create/edit from a persisted
snapshot (50 most recent, body <= 4,000 chars, 90 KB
cap, honest truncation); watch create/edit/delete ops
queue pending until a phone snapshot reflects them;
conflicts last-writer-wins per note (tombstone wins
ties), no text merging; non-text phone notes are
view+delete only on watch, enforced phone-side.

Swept in: the WearLink library's landed API used by
this app (putData, acked sendMessage, state) - zero
Play services. Later commits complete the migration
of appstore/calendar/contacts onto the same library.

Verified: notes 238 phone tests + 9 wear tests + phone
lint green; wear APK assembles.

Diff

library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdnew file mode 100644index 0000000000..8bdbab2f88--- /dev/null+++ b/library/wearlink/AGENTS.md@@ -0,0 +1,18 @@+# AGENTS.md — library/wearlink/ (':library:wearlink')++> Scoped supplement. Global rules in root `AGENTS.md` apply.++- Gradle: :library:wearlink / dir: library/wearlink/+- Package: `com.vayunmathur.library.wearlink` (single package, like :library:log)+- Entry: `WearLinkNode.kt` (Android), `WearLinkProtocol.kt` (pure wire)++## Purpose+First-party replacement for the proprietary Play-services Wearable Data+Layer. RFCOMM over already-bonded Bluetooth, both sides listen + dial,+cert-bound handshake. No Play services, no BLE scan/advertise, no location.++## Verify+```+./gradlew :library:wearlink:testDebugUnitTest+./gradlew :library:wearlink:lint+```
library/wearlink/README.md
diff --git a/library/wearlink/README.md b/library/wearlink/README.mdnew file mode 100644index 0000000000..81403dfbf8--- /dev/null+++ b/library/wearlink/README.md@@ -0,0 +1,93 @@+# WearLink — first-party Wear Data Layer replacement++The Google Wearable Data Layer is proprietary Play services. WearLink+reimplements the parts Modern-Apps actually used, over platform Bluetooth,+with no Play services anywhere.++## Transport choice++**Bluetooth Classic RFCOMM for everything, over the existing bond.**++- Wear OS watches are already BT-bonded to the phone by the system+  companion, but third-party apps cannot ride that system link — we open+  our own RFCOMM service (UUID `4d41574c-0001-…`, name+  `ModernApps WearLink`) on top of the same bond.+- Candidates come from `BluetoothManager.adapter.bondedDevices`+  (`getBondedDevices()`); RFCOMM connect is+  `createRfcommSocketToServiceRecord`, accept is+  `listenUsingRfcommWithServiceRecord` (both verified against the local+  android-37 SDK). Secure/bonded sockets only.+- **Both sides listen and both sides dial**, so either side can initiate.+  When both dial at once, the handshake's per-process instance ids break+  the tie: the pair initiated by the smaller instance id survives, on both+  ends, deterministically.+- Why not BLE GATT as primary: a GATT design (watch = server advertising,+  phone = central) would need BLUETOOTH_ADVERTISE/SCAN, MTU negotiation+  and characteristic chunking — workable for messages, but APK-sized+  streams become slow, fiddly MTU plumbing. RFCOMM is an ordered stream+  socket with socket flow control: bulk is just bytes. BLE's only win+  would be lower idle power for discovery, and we do not discover at all+  (bonded lookup instead), so BLE is not used.++## Layer mapping (vs Data Layer)++| Data Layer | WearLink |+|---|---|+| CapabilityClient | Bonded-set candidates + HELLO handshake for `appId` (the old capability string, reused verbatim). `WearLinkState` replaces node reachability. |+| MessageClient | `MESSAGE` frames: fire-and-forget, optional `MESSAGE_ACK`, or `RESPONSE`-correlated requests (ids + timeout + duplicate suppression). Same paths/payloads as before. |+| DataClient (DataItem) | `DATA` frames: path-keyed document, generation + chunk index/count + total size + SHA-256; applied only when complete and verified. No 100 KB cap; replaces contacts' hand-rolled chunk paths and appstore/calendar's DataMap JSON. |+| ChannelClient | `STREAM_OPEN/CHUNK/CLOSE` on the same session: total size + SHA-256 header, receiver `STREAM_ACK` carries its durable offset, sender seeks — **resumable** across reconnects when the sink kept its partial file. |+| WearableListenerService | *Nothing.* See degradations. |++Golden-JSON payloads inside messages/data items are unchanged — only the+transport underneath them changed.++## Framing & reliability++`[u32 length][u8 type][u64 id][u16 path len][path][body]`, capped at+64 KiB per frame, 256 KiB per message, 4 MiB per data item, 200 MiB per+stream. Corrupt length/type fails the session closed. All IO runs on+`Dispatchers.IO` inside `WearLinkNode`; reconnects back off 1 s → 30 s.+Failure is surfaced through `WearLinkState` into each app's existing+phone/watch sync states (no fake "synced").++## Trust++Bonding proves the paired device and encrypts the link; it does not prove+the peer *app*. The handshake also requires: equal `appId`, and a token+`SHA-256(signingCertHash ‖ peerNonce ‖ appId)` where each side derives the+expected hash from its **own** PackageManager signing certificate+(`GET_SIGNING_CERTIFICATES`). A differently-signed peer fails; the nonce+binding stops replay. Honest limitation: an APK certificate is public, so+a malicious app already on the already-bonded watch could compute a token+— WearLink proves *same-signed app on the paired device*, not more, and+no more is available to third-party apps (the signing private key is not+accessible to app code).++## Permissions++Library manifest declares only `BLUETOOTH_CONNECT` (API 31+) plus+`BLUETOOTH`/`BLUETOOTH_ADMIN` capped at API 30. No scan/advertise (we+never scan or advertise), and no location permission or+`neverForLocation` workaround. The hosting activity requests+`BLUETOOTH_CONNECT` at runtime; until granted the node reports+`PermissionMissing` instead of crashing.++## What degrades vs GMS (honest)++- **No background system wakeups.** `WearableListenerService` woke a dead+  app on every message/data change; WearLink listeners live and die with+  the app process. A watch request that arrives while the phone app is+  dead is not delivered until the phone app next runs and reconnects+  (then state documents republish/reconcile as before).+- **No store-and-forward.** DataItems were persisted by Play services and+  reconciled whenever devices met; WearLink data items are delivered on+  a live session and each app persists what it receives (all three wear+  apps already did). Publishing while disconnected is a no-op reported+  through state, not queued by the system.+- **Presence is session presence**, not system reachability: "watch+  connected" now means "our handshake completed", which is stricter and+  slower to become true (a connect attempt), not instantaneous.+- Same-package + same-signing is no longer a *transport* requirement+  (any of our app pairs could share WearLink), but all three pairs keep+  it: the handshake token still requires the same signing certificate.
library/wearlink/build.gradle.kts
diff --git a/library/wearlink/build.gradle.kts b/library/wearlink/build.gradle.ktsnew file mode 100644index 0000000000..f017af81a6--- /dev/null+++ b/library/wearlink/build.gradle.kts@@ -0,0 +1,14 @@+plugins {+    id("common-conventions-library")+}++android {+    namespace = "com.vayunmathur.library.wearlink"+}++dependencies {+    implementation(libs.kotlinx.coroutines.android)+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+    testImplementation(libs.kotlinx.coroutines.test)+}
library/wearlink/src/main/AndroidManifest.xml
diff --git a/library/wearlink/src/main/AndroidManifest.xml b/library/wearlink/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..ab4e32708c--- /dev/null+++ b/library/wearlink/src/main/AndroidManifest.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+    <!-- WearLink is RFCOMM-over-bonded-Bluetooth only: no discovery scan and+         no BLE advertising, so BLUETOOTH_SCAN / BLUETOOTH_ADVERTISE are+         deliberately NOT declared (declaring them would ask the user for+         permissions the transport never exercises) and no location permission+         or neverForLocation workaround is needed. Connecting to / accepting+         on a bonded device needs BLUETOOTH_CONNECT on API 31+. -->+    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />+    <!-- Pre-API-31 equivalents, capped so they are not requested on 31+. -->+    <uses-permission+        android:name="android.permission.BLUETOOTH"+        android:maxSdkVersion="30" />+    <uses-permission+        android:name="android.permission.BLUETOOTH_ADMIN"+        android:maxSdkVersion="30" />+</manifest>
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.ktnew file mode 100644index 0000000000..a2ce59cbfb--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt@@ -0,0 +1,105 @@+package com.vayunmathur.library.wearlink++import android.Manifest+import android.annotation.SuppressLint+import android.bluetooth.BluetoothManager+import android.bluetooth.BluetoothServerSocket as BtServerSocket+import android.bluetooth.BluetoothSocket as BtSocket+import android.content.Context+import android.content.pm.PackageManager+import androidx.core.content.ContextCompat+import java.io.InputStream+import java.io.OutputStream+import java.util.UUID++/**+ * RFCOMM transport over the platform Bluetooth stack, verified against the+ * local SDK (android-37): `BluetoothManager.adapter`,+ * `adapter.bondedDevices`, `device.createRfcommSocketToServiceRecord(uuid)`,+ * `adapter.listenUsingRfcommWithServiceRecord(name, uuid)`. Secure (bonded,+ * encrypted) sockets only — no insecure RFCOMM.+ *+ * The Wear OS watch is already bonded to the phone by the system companion;+ * third-party apps cannot ride that system link, so this is our own RFCOMM+ * service on top of the same bond. No scanning: candidates come from the+ * bonded set, which is also why no BLUETOOTH_SCAN/location is ever needed.+ */+/** Runtime-permission entry for hosting activities (API 31+ runtime model). */+object WearLinkPermissions {+    /** True when WearLink may connect/accept; request [WearLinkNode.REQUIRED_PERMISSIONS] otherwise. */+    fun isGranted(context: Context): Boolean =+        ContextCompat.checkSelfPermission(+            context, Manifest.permission.BLUETOOTH_CONNECT,+        ) == PackageManager.PERMISSION_GRANTED++    /** Call from an Activity's onCreate; no-ops once granted. */+    fun requestIfNeeded(activity: android.app.Activity) {+        if (!isGranted(activity)) {+            activity.requestPermissions(WearLinkNode.REQUIRED_PERMISSIONS, 0x574C)+        }+    }+}++class AndroidBluetoothTransport(private val context: Context) : WearLinkTransport {++    private val adapter get() = runCatching {+        (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter+    }.getOrNull()++    fun hasConnectPermission(): Boolean =+        ContextCompat.checkSelfPermission(+            context, Manifest.permission.BLUETOOTH_CONNECT,+        ) == PackageManager.PERMISSION_GRANTED++    override fun isAvailable(): Boolean = adapter?.isEnabled == true++    @SuppressLint("MissingPermission") // guarded by hasConnectPermission() below+    override fun bondedPeers(): List<BondedPeer> {+        if (!hasConnectPermission()) return emptyList()+        val bonded = runCatching { adapter?.bondedDevices }.getOrNull() ?: return emptyList()+        return bonded.map { device ->+            @Suppress("MissingPermission")+            BondedPeer(device.address, device.name ?: device.address)+        }+    }++    @Suppress("MissingPermission") // checked by caller via hasConnectPermission / node state+    override fun connect(peer: BondedPeer, serviceUuid: UUID): WearLinkSocket {+        val device = adapter?.getRemoteDevice(peer.address)+            ?: throw IllegalStateException("no bluetooth adapter")+        val socket = device.createRfcommSocketToServiceRecord(serviceUuid)+        // Discovery would fight the connect; we never start it, but cancel a+        // system-started one defensively (cheap, documented in the SDK).+        runCatching { adapter?.cancelDiscovery() }+        socket.connect()+        return BtSocketWrapper(socket, peer.label)+    }++    @Suppress("MissingPermission")+    override fun listen(serviceUuid: UUID, serviceName: String): WearLinkServerSocket {+        val server = adapter?.listenUsingRfcommWithServiceRecord(serviceName, serviceUuid)+            ?: throw IllegalStateException("no bluetooth adapter")+        return BtServerWrapper(server)+    }++    private class BtSocketWrapper(+        private val socket: BtSocket,+        override val peerLabel: String,+    ) : WearLinkSocket {+        override val input: InputStream get() = socket.inputStream+        override val output: OutputStream get() = socket.outputStream+        override fun close() = runCatching { socket.close() }.let { Unit }+    }++    private class BtServerWrapper(private val server: BtServerSocket) : WearLinkServerSocket {+        @Suppress("MissingPermission")+        override fun accept(): WearLinkSocket {+            val socket = server.accept()+            @Suppress("MissingPermission")+            val label = socket.remoteDevice?.name ?: socket.remoteDevice?.address ?: "peer"+            return BtSocketWrapper(socket, label)+        }++        override fun close() = runCatching { server.close() }.let { Unit }+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.ktnew file mode 100644index 0000000000..6719a9c017--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt@@ -0,0 +1,147 @@+package com.vayunmathur.library.wearlink++import java.io.ByteArrayOutputStream+import java.security.MessageDigest++/**+ * Path-keyed state documents (the DataClient replacement). A document is+ * chunked into DATA frames carrying generation + index + count + total size+ * + SHA-256 — the same generation/chunk discipline the contacts snapshot+ * already used over DataItems. The receiver applies a document only when+ * every chunk of one generation is present and the hash verifies; partial+ * or stale generations change nothing. Unlike DataItems there is no 100 KB+ * per-item cap and no system-side persistence: the document lives only+ * while a session delivers it, and each app persists what it receives+ * itself (as all three wear apps already do).+ */+data class DataChunk(+    val generation: Long,+    val index: Int,+    val count: Int,+    val totalSize: Long,+    val sha256: String,+    val bytes: ByteArray,+) {+    fun encodeBody(): ByteArray {+        val sha = sha256.encodeToByteArray()+        val out = ByteArrayOutputStream()+        val fixed = ByteArray(8 + 4 + 4 + 8 + 2)+        FrameCodec.writeLong(fixed, 0, generation)+        writeInt(fixed, 8, index); writeInt(fixed, 12, count)+        FrameCodec.writeLong(fixed, 16, totalSize)+        fixed[24] = ((sha.size ushr 8) and 0xFF).toByte()+        fixed[25] = (sha.size and 0xFF).toByte()+        out.write(fixed); out.write(sha); out.write(bytes)+        return out.toByteArray()+    }++    override fun equals(other: Any?): Boolean =+        other is DataChunk && generation == other.generation && index == other.index &&+            count == other.count && bytes.contentEquals(other.bytes)++    override fun hashCode(): Int = (generation * 31 + index).hashCode()++    companion object {+        fun decodeBody(body: ByteArray): DataChunk? = runCatching {+            if (body.size < 26) return null+            val generation = FrameCodec.readLong(body, 0)+            val index = readInt(body, 8)+            val count = readInt(body, 12)+            val total = FrameCodec.readLong(body, 16)+            val shaLen = ((body[24].toInt() and 0xFF) shl 8) or (body[25].toInt() and 0xFF)+            if (26 + shaLen > body.size) return null+            val sha = body.decodeToString(26, 26 + shaLen)+            DataChunk(generation, index, count, total, sha, body.copyOfRange(26 + shaLen, body.size))+        }.getOrNull()++        internal fun writeInt(bytes: ByteArray, offset: Int, value: Int) {+            for (i in 0 until 4) bytes[offset + i] = ((value ushr (24 - i * 8)) and 0xFF).toByte()+        }++        internal fun readInt(bytes: ByteArray, offset: Int): Int {+            var v = 0+            for (i in 0 until 4) v = (v shl 8) or (bytes[offset + i].toInt() and 0xFF)+            return v+        }+    }+}++object DataItemCodec {+    fun chunk(path: String, generation: Long, payload: ByteArray): List<WearLinkFrame> {+        require(payload.size <= WearLinkProtocol.MAX_DATA_ITEM_BYTES) { "data item too large" }+        val sha = WearLinkHandshake.sha256Hex(payload)+        val count = maxOf(1, (payload.size + WearLinkProtocol.DATA_CHUNK_BYTES - 1) /+            WearLinkProtocol.DATA_CHUNK_BYTES)+        return (0 until count).map { index ->+            val from = index * WearLinkProtocol.DATA_CHUNK_BYTES+            val slice = payload.copyOfRange(+                from, minOf(payload.size, from + WearLinkProtocol.DATA_CHUNK_BYTES),+            )+            WearLinkFrame(+                FrameType.DATA, generation, path,+                DataChunk(generation, index, count, payload.size.toLong(), sha, slice).encodeBody(),+            )+        }+    }+}++/** Per-path reassembler. Pure; feed DATA frames, get complete documents. */+class DataReassembler {+    private class Pending(+        val generation: Long,+        val count: Int,+        val totalSize: Long,+        val sha256: String,+    ) {+        val chunks = mutableMapOf<Int, ByteArray>()+    }++    private val pending = mutableMapOf<String, Pending>()+    private val appliedGeneration = mutableMapOf<String, Long>()++    /** Completed payload for [path], or null while incomplete/stale/corrupt. */+    fun onFrame(frame: WearLinkFrame): ByteArray? {+        if (frame.type != FrameType.DATA) return null+        val chunk = DataChunk.decodeBody(frame.body) ?: return null+        if (chunk.count <= 0 || chunk.index !in 0 until chunk.count) return null+        if (chunk.totalSize < 0 || chunk.totalSize > WearLinkProtocol.MAX_DATA_ITEM_BYTES) return null+        val last = appliedGeneration[frame.path] ?: Long.MIN_VALUE+        if (chunk.generation < last) return null+        val current = pending[frame.path]+        val state = if (current == null || current.generation != chunk.generation) {+            Pending(chunk.generation, chunk.count, chunk.totalSize, chunk.sha256)+                .also { pending[frame.path] = it }+        } else {+            current+        }+        if (state.count != chunk.count || state.sha256 != chunk.sha256) return null+        state.chunks[chunk.index] = chunk.bytes+        if (state.chunks.size < state.count) return null+        val assembled = ByteArrayOutputStream()+        for (i in 0 until state.count) assembled.write(state.chunks[i] ?: return null)+        val bytes = assembled.toByteArray()+        pending.remove(frame.path)+        if (bytes.size.toLong() != state.totalSize) return null+        if (WearLinkHandshake.sha256Hex(bytes) != state.sha256) return null+        appliedGeneration[frame.path] = chunk.generation+        return bytes+    }++    fun lastAppliedGeneration(path: String): Long? = appliedGeneration[path]+}++/** SHA-256 streaming helper shared by stream send/receive. */+object Sha256 {+    fun hex(bytes: ByteArray): String = WearLinkHandshake.sha256Hex(bytes)++    fun hex(input: java.io.InputStream): String {+        val digest = MessageDigest.getInstance("SHA-256")+        val buffer = ByteArray(64 * 1024)+        while (true) {+            val n = input.read(buffer)+            if (n < 0) break+            if (n > 0) digest.update(buffer, 0, n)+        }+        return digest.digest().joinToString("") { "%02x".format(it) }+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/FrameCodec.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/FrameCodec.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/FrameCodec.ktnew file mode 100644index 0000000000..3684367251--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/FrameCodec.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.wearlink++import java.io.DataInputStream+import java.io.EOFException+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream++/**+ * Length-prefixed framing: `[u32 BE payload length][payload]`, payload is+ * `[u8 type][u64 id][u16 path length][path UTF-8][body]`. Length-prefixing+ * (not delimiter scanning) so binary bodies need no escaping, and a corrupt+ * length fails closed instead of desynchronising the stream silently.+ */+object FrameCodec {+    private const val HEADER_BYTES = 4+    private const val FIXED_PAYLOAD = 1 + 8 + 2++    fun encode(frame: WearLinkFrame, out: OutputStream) {+        val pathBytes = frame.path.encodeToByteArray()+        require(pathBytes.size <= 0xFFFF) { "path too long" }+        val payloadSize = FIXED_PAYLOAD + pathBytes.size + frame.body.size+        require(payloadSize <= WearLinkProtocol.MAX_FRAME_PAYLOAD) {+            "frame payload $payloadSize exceeds ${WearLinkProtocol.MAX_FRAME_PAYLOAD}"+        }+        val header = ByteArray(HEADER_BYTES)+        header[0] = (payloadSize ushr 24).toByte()+        header[1] = (payloadSize ushr 16).toByte()+        header[2] = (payloadSize ushr 8).toByte()+        header[3] = payloadSize.toByte()+        out.write(header)+        out.write(frame.type.code)+        writeLong(out, frame.id)+        out.write((pathBytes.size ushr 8) and 0xFF)+        out.write(pathBytes.size and 0xFF)+        out.write(pathBytes)+        out.write(frame.body)+        out.flush()+    }++    /** Encoded frame bytes (tests, in-memory transports). */+    fun encodeToBytes(frame: WearLinkFrame): ByteArray {+        val out = java.io.ByteArrayOutputStream()+        encode(frame, out)+        return out.toByteArray()+    }++    /** Next frame, or null on clean EOF before a header. Throws on corruption. */+    fun decode(input: InputStream): WearLinkFrame? {+        val data = DataInputStream(input)+        val header = ByteArray(HEADER_BYTES)+        var read = 0+        while (read < HEADER_BYTES) {+            val n = data.read(header, read, HEADER_BYTES - read)+            if (n < 0) {+                if (read == 0) return null+                throw EOFException("eof inside frame header")+            }+            read += n+        }+        val length = ((header[0].toInt() and 0xFF) shl 24) or+            ((header[1].toInt() and 0xFF) shl 16) or+            ((header[2].toInt() and 0xFF) shl 8) or+            (header[3].toInt() and 0xFF)+        if (length < FIXED_PAYLOAD || length > WearLinkProtocol.MAX_FRAME_PAYLOAD) {+            throw IOException("invalid frame length $length")+        }+        val payload = ByteArray(length)+        data.readFully(payload)+        val type = FrameType.fromCode(payload[0].toInt() and 0xFF)+            ?: throw IOException("unknown frame type ${payload[0]}")+        var offset = 1+        val id = readLong(payload, offset); offset += 8+        val pathLength = ((payload[offset].toInt() and 0xFF) shl 8) or+            (payload[offset + 1].toInt() and 0xFF); offset += 2+        if (offset + pathLength > payload.size) throw IOException("path overruns frame")+        val path = payload.decodeToString(offset, offset + pathLength)+        val body = payload.copyOfRange(offset + pathLength, payload.size)+        return WearLinkFrame(type, id, path, body)+    }++    private fun writeLong(out: OutputStream, value: Long) {+        for (shift in 56 downTo 0 step 8) out.write(((value ushr shift) and 0xFF).toInt())+    }++    internal fun readLong(bytes: ByteArray, offset: Int): Long {+        var value = 0L+        for (i in 0 until 8) value = (value shl 8) or (bytes[offset + i].toLong() and 0xFF)+        return value+    }++    internal fun writeLong(bytes: ByteArray, offset: Int, value: Long) {+        for (i in 0 until 8) bytes[offset + i] = ((value ushr (56 - i * 8)) and 0xFF).toByte()+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/Reliability.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/Reliability.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/Reliability.ktnew file mode 100644index 0000000000..93162b84f0--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/Reliability.kt@@ -0,0 +1,72 @@+package com.vayunmathur.library.wearlink++import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicLong++/** Exponential reconnect backoff: 1s doubling to a 30s ceiling, no jitter deps. */+class WearLinkBackoff(+    private val baseMillis: Long = 1_000L,+    private val maxMillis: Long = 30_000L,+) {+    private var failures = 0++    fun nextDelayMillis(): Long {+        val delay = minOf(maxMillis, baseMillis shl minOf(failures, 15))+        failures+++        return delay+    }++    fun reset() {+        failures = 0+    }+}++/** Monotonic frame/message ids for one node. */+class IdGenerator(start: Long = System.currentTimeMillis()) {+    private val counter = AtomicLong(start)+    fun next(): Long = counter.incrementAndGet()+}++/**+ * Correlates requests with responses and MESSAGE_ACKs. Registration is+ * bounded: a caller that never gets an answer removes its entry on timeout+ * (the Android node does), so a dead peer cannot grow this map.+ */+class RequestTracker<T> {+    private val pending = ConcurrentHashMap<Long, T>()++    fun register(id: Long, value: T) {+        pending[id] = value+    }++    fun complete(id: Long): T? = pending.remove(id)++    fun remove(id: Long): T? = pending.remove(id)++    fun failAll(): List<T> {+        val values = pending.values.toList()+        pending.clear()+        return values+    }++    val size: Int get() = pending.size+}++/**+ * Duplicate suppression for request messages: a retried request (sender+ * reconnected mid-flight) must not execute twice. Bounded LRU of seen ids.+ */+class SeenMessageIds(private val capacity: Int = 256) {+    private val seen = object : LinkedHashMap<Long, Boolean>(16, 0.75f, true) {+        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, Boolean>?) =+            size > capacity+    }++    /** True when [id] is new (and now recorded); false when already seen. */+    @Synchronized+    fun markIfNew(id: Long): Boolean {+        if (seen.containsKey(id)) return false+        seen[id] = true+        return true+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/SigningTrust.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/SigningTrust.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/SigningTrust.ktnew file mode 100644index 0000000000..9c7bd52df7--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/SigningTrust.kt@@ -0,0 +1,40 @@+package com.vayunmathur.library.wearlink++import android.content.Context+import android.content.pm.PackageManager+import android.os.Build++/** PackageManager signing-certificate facts for the handshake trust check. */+object SigningTrust {++    /**+     * SHA-256 hex of this app's first APK signing certificate, or null when+     * it cannot be read (the node then refuses to connect rather than+     * connecting unauthenticated).+     */+    fun localCertHashHex(context: Context): String? = runCatching {+        val info = context.packageManager.getPackageInfo(+            context.packageName, PackageManager.GET_SIGNING_CERTIFICATES,+        )+        val signers = info.signingInfo?.apkContentsSigners+        val cert = signers?.firstOrNull() ?: return null+        WearLinkHandshake.certHashHex(cert.toByteArray())+    }.getOrNull()++    /**+     * True when [otherPackage] is installed and signed with the same+     * certificate as this app — the local half of the trust check (the+     * remote half is the nonce-bound handshake token). Kept for consumers+     * that also talk to a same-package sibling locally.+     */+    fun sameSignature(context: Context, otherPackage: String): Boolean = runCatching {+        if (Build.VERSION.SDK_INT >= 28) {+            context.packageManager.checkSignatures(context.packageName, otherPackage) ==+                PackageManager.SIGNATURE_MATCH+        } else {+            @Suppress("DEPRECATION")+            context.packageManager.checkSignatures(context.packageName, otherPackage) ==+                PackageManager.SIGNATURE_MATCH+        }+    }.getOrDefault(false)+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/StreamTransfer.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/StreamTransfer.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/StreamTransfer.ktnew file mode 100644index 0000000000..12685c0c72--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/StreamTransfer.kt@@ -0,0 +1,140 @@+package com.vayunmathur.library.wearlink++import java.io.ByteArrayOutputStream+import java.security.MessageDigest++/**+ * Large byte streams (the ChannelClient replacement): an offer precedes the+ * stream, raw chunks follow on the same RFCOMM session (no separate channel+ * socket needed — frames multiplex over one stream, ordered by TCP-like+ * RFCOMM delivery), and the receiver completes only when size + SHA-256+ * match the header.+ *+ * Resumability — yes, cheaply, and included: the receiver reports its+ * durable received offset in STREAM_ACK (once on open, then periodically),+ * and the sender seeks its source to that offset. The sink owns the partial+ * file, so an interrupted APK transfer resumes where it stopped across a+ * reconnect instead of restarting, provided the sink kept the `.partial`.+ * The hash is verified over the *whole* stream at close; a resumed receiver+ * re-reads its retained prefix into the digest (see [StreamReceiver]).+ */+data class StreamHeader(+    val totalSize: Long,+    val sha256: String,+    /** Offset the sender proposes to start from (usually 0; ack overrides). */+    val startOffset: Long = 0L,+) {+    fun encodeBody(): ByteArray {+        val sha = sha256.encodeToByteArray()+        val out = ByteArrayOutputStream()+        val fixed = ByteArray(8 + 8 + 2)+        FrameCodec.writeLong(fixed, 0, totalSize)+        FrameCodec.writeLong(fixed, 8, startOffset)+        fixed[16] = ((sha.size ushr 8) and 0xFF).toByte()+        fixed[17] = (sha.size and 0xFF).toByte()+        out.write(fixed); out.write(sha)+        return out.toByteArray()+    }++    companion object {+        fun decodeBody(body: ByteArray): StreamHeader? = runCatching {+            if (body.size < 18) return null+            val total = FrameCodec.readLong(body, 0)+            val start = FrameCodec.readLong(body, 8)+            val shaLen = ((body[16].toInt() and 0xFF) shl 8) or (body[17].toInt() and 0xFF)+            if (18 + shaLen > body.size) return null+            StreamHeader(total, body.decodeToString(18, 18 + shaLen), start)+        }.getOrNull()+    }+}++fun encodeOffsetBody(offset: Long): ByteArray =+    ByteArray(8).also { FrameCodec.writeLong(it, 0, offset) }++fun decodeOffsetBody(body: ByteArray): Long? =+    if (body.size >= 8) FrameCodec.readLong(body, 0) else null++/**+ * Receiver state machine. Sequential offsets only (RFCOMM is ordered): an+ * out-of-order chunk fails the transfer rather than buffering unboundedly.+ */+class StreamReceiver(+    val header: StreamHeader,+    initialOffset: Long = 0L,+    prefixStream: java.io.InputStream? = null,+) {+    private val digest = MessageDigest.getInstance("SHA-256")++    var received: Long = initialOffset+        private set++    var failed: Boolean = false+        private set++    init {+        require(initialOffset in 0..header.totalSize) { "bad resume offset" }+        // Fold the retained prefix into the digest so close-verification+        // covers the whole stream, not only the resumed tail. Streamed in+        // chunks: an APK prefix is never held in memory whole.+        if (prefixStream != null) {+            var read = 0L+            val buffer = ByteArray(64 * 1024)+            prefixStream.use { input ->+                while (true) {+                    val n = input.read(buffer)+                    if (n < 0) break+                    if (n > 0) { digest.update(buffer, 0, n); read += n }+                }+            }+            require(read == initialOffset) { "prefix/offset mismatch" }+        }+    }++    /** Offset to advertise in STREAM_ACK. */+    val ackOffset: Long get() = received++    /** Accept the next sequential chunk; false means abort the transfer. */+    fun onChunk(offset: Long, bytes: ByteArray): Boolean {+        if (failed) return false+        if (offset != received) { failed = true; return false }+        if (received + bytes.size > header.totalSize) { failed = true; return false }+        digest.update(bytes)+        received += bytes.size+        return true+    }++    /** True only when every byte arrived and the announced hash matches. */+    fun verifyComplete(): Boolean {+        if (failed || received != header.totalSize) return false+        val actual = digest.digest().joinToString("") { "%02x".format(it) }+        return actual.equals(header.sha256, ignoreCase = true)+    }+}++/** Sender state machine: chunk slicing + resume seek over a byte source. */+class StreamSender(+    val header: StreamHeader,+    private val sourceSize: Long,+) {+    var nextOffset: Long = header.startOffset+        private set++    /** Honour the receiver's durable offset (STREAM_ACK) before/while sending. */+    fun seekTo(offset: Long) {+        require(offset in 0..sourceSize) { "resume offset out of range" }+        nextOffset = offset+    }++    /** Next slice of [source] (a random-access read at [nextOffset]), or null at end. */+    fun nextChunk(readAt: (offset: Long, length: Int) -> ByteArray): ByteArray? {+        if (nextOffset >= sourceSize) return null+        val length = minOf(+            WearLinkProtocol.STREAM_CHUNK_BYTES.toLong(), sourceSize - nextOffset,+        ).toInt()+        val bytes = readAt(nextOffset, length)+        nextOffset += bytes.size+        return bytes+    }++    val complete: Boolean get() = nextOffset >= sourceSize+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.ktnew file mode 100644index 0000000000..54f836fb9f--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt@@ -0,0 +1,167 @@+package com.vayunmathur.library.wearlink++import java.security.MessageDigest+import java.security.SecureRandom++/**+ * Capability/presence discovery + trust handshake.+ *+ * Discovery replaces CapabilityClient: a bonded peer is a candidate merely+ * by accepting our RFCOMM UUID; presence is only proven when the handshake+ * completes for our [appId]. The string that used to be a GMS capability+ * (`appstore_wear_store`, `calendar_wear_companion`, …) is reused verbatim as+ * the WearLink appId, so per-app isolation is unchanged.+ *+ * Trust model (honest): Bluetooth bonding proves *this paired device* and+ * encrypts the link; it does not prove which app is on the other end. So the+ * handshake additionally requires (a) equal appId, (b) a token bound to the+ * APK signing certificate: `SHA-256(certHashBytes || peerNonce || appId)`.+ * Each side derives its expected token from *its own* PackageManager signing+ * certificate, so a peer signed by a different key (or unsigned/spoofed with+ * no knowledge of the session nonce) fails. The nonce binding stops replay+ * of a captured hello into a later session. Limitation, stated plainly: an+ * APK's certificate is public, so a malicious app already installed on the+ * already-bonded watch could compute a token — the handshake is app+ * identity + anti-cross-talk/anti-replay, not a substitute for the bonded,+ * user-paired device trust underneath it. No stronger proof is available to+ * a third-party app: the APK signing *private* key is not accessible to app+ * code, so challenge-signing is impossible.+ */+object WearLinkHandshake {+    const val NONCE_BYTES = 16++    fun newNonce(random: SecureRandom = SecureRandom()): ByteArray =+        ByteArray(NONCE_BYTES).also { random.nextBytes(it) }++    /** SHA-256 hex of the DER signing certificate. */+    fun certHashHex(certBytes: ByteArray): String = sha256Hex(certBytes)++    fun token(certHashHex: String, peerNonce: ByteArray, appId: String): String {+        val digest = MessageDigest.getInstance("SHA-256")+        digest.update(hexToBytes(certHashHex))+        digest.update(peerNonce)+        digest.update(appId.encodeToByteArray())+        return digest.digest().joinToString("") { "%02x".format(it) }+    }++    fun sha256Hex(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes)+            .joinToString("") { "%02x".format(it) }++    fun hexToBytes(hex: String): ByteArray {+        val clean = hex.lowercase()+        require(clean.length % 2 == 0) { "odd hex" }+        return ByteArray(clean.length / 2) {+            clean.substring(it * 2, it * 2 + 2).toInt(16).toByte()+        }+    }+}++/** HELLO / HELLO_ACK body. */+data class HelloMessage(+    val version: Int,+    val appId: String,+    val packageName: String,+    /** Random per-process id; simultaneous-dial tie-break key. */+    val instanceId: String,+    val nonce: ByteArray,+    val token: String,+) {+    fun encode(): ByteArray {+        val app = appId.encodeToByteArray()+        val pkg = packageName.encodeToByteArray()+        val inst = instanceId.encodeToByteArray()+        val tok = token.encodeToByteArray()+        val out = java.io.ByteArrayOutputStream()+        out.write(version)+        writeField(out, app); writeField(out, pkg); writeField(out, inst)+        writeField(out, nonce); writeField(out, tok)+        return out.toByteArray()+    }++    override fun equals(other: Any?): Boolean {+        if (other !is HelloMessage) return false+        return version == other.version && appId == other.appId &&+            packageName == other.packageName && instanceId == other.instanceId &&+            nonce.contentEquals(other.nonce) && token == other.token+    }++    override fun hashCode(): Int = appId.hashCode() * 31 + nonce.contentHashCode()++    companion object {+        fun decode(bytes: ByteArray): HelloMessage? = runCatching {+            val input = java.io.ByteArrayInputStream(bytes)+            val version = input.read()+            val app = readField(input) ?: return null+            val pkg = readField(input) ?: return null+            val inst = readField(input) ?: return null+            val nonce = readField(input) ?: return null+            val tok = readField(input) ?: return null+            HelloMessage(+                version, app.decodeToString(), pkg.decodeToString(),+                inst.decodeToString(), nonce, tok.decodeToString(),+            )+        }.getOrNull()++        private fun writeField(out: java.io.ByteArrayOutputStream, bytes: ByteArray) {+            out.write((bytes.size ushr 8) and 0xFF); out.write(bytes.size and 0xFF)+            out.write(bytes)+        }++        private fun readField(input: java.io.ByteArrayInputStream): ByteArray? {+            val hi = input.read(); val lo = input.read()+            if (hi < 0 || lo < 0) return null+            val size = (hi shl 8) or lo+            if (size > 4096) return null+            val bytes = ByteArray(size)+            var off = 0+            while (off < size) {+                val n = input.read(bytes, off, size - off)+                if (n < 0) return null+                off += n+            }+            return bytes+        }+    }+}++/** Pure handshake verification + simultaneous-dial tie-break. */+object HandshakeVerifier {+    sealed interface Result {+        data class Accepted(val peer: HelloMessage) : Result+        data class Rejected(val reason: String) : Result+    }++    /**+     * Verify a peer HELLO against our identity. [peerNonceForToken] is the+     * nonce *we* sent (for HELLO_ACK) or the peer's own nonce (for HELLO):+     * HELLO token binds the sender's nonce, ACK token binds both — here the+     * caller supplies the nonce the token was computed over.+     */+    fun verify(+        hello: HelloMessage,+        expectedAppId: String,+        ownCertHashHex: String,+        tokenNonce: ByteArray,+    ): Result {+        if (hello.version != WearLinkProtocol.PROTOCOL_VERSION) {+            return Result.Rejected("protocol version ${hello.version}")+        }+        if (hello.appId != expectedAppId) return Result.Rejected("app mismatch")+        val expected = WearLinkHandshake.token(ownCertHashHex, tokenNonce, expectedAppId)+        val ok = MessageDigest.isEqual(+            expected.encodeToByteArray(), hello.token.encodeToByteArray(),+        )+        return if (ok) Result.Accepted(hello) else Result.Rejected("signing token mismatch")+    }++    /**+     * When both sides dialled at once there are two socket pairs. Keep the+     * pair initiated by the smaller instanceId — both ends compute the same+     * winner from the two instance ids they know (their own + the peer's).+     */+    fun keepInitiatedBySmallerInstance(+        existingInitiatorInstance: String,+        candidateInitiatorInstance: String,+    ): Boolean = candidateInitiatorInstance < existingInitiatorInstance+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.ktnew file mode 100644index 0000000000..ced6a07827--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt@@ -0,0 +1,476 @@+package com.vayunmathur.library.wearlink++import android.content.Context+import com.vayunmathur.library.log.Log+import java.io.File+import java.io.RandomAccessFile+import java.util.UUID+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull++/** Callbacks for one WearLink peer session. All run off the main thread. */+interface WearLinkListener {+    /** Fire-and-forget message (or acked message) from the peer. */+    fun onMessage(path: String, body: ByteArray) {}++    /** Request message; return a response body, or null for no reply. */+    fun onRequest(path: String, body: ByteArray): ByteArray? = null++    /** A complete, hash-verified data item arrived for [path]. */+    fun onData(path: String, body: ByteArray) {}++    /**+     * A stream is opening for [path]. Return the sink to write it into, or+     * null to refuse. [StreamSink.resumeOffset]/[StreamSink.prefix] let a+     * retained partial resume instead of restarting.+     */+    fun onStreamOpen(path: String, header: StreamHeader): StreamSink? = null+}++/** Receiving end of one incoming stream. */+interface StreamSink {+    val resumeOffset: Long get() = 0L++    /** Stream of bytes already held for [resumeOffset] (fed into the hash). */+    fun prefixStream(): java.io.InputStream? = null++    fun write(bytes: ByteArray, offset: Long)++    /** Stream ended; [verified] is the library's size+SHA-256 verdict. */+    fun close(verified: Boolean)+}++/** Random-access byte source for outgoing streams. */+interface StreamSource {+    val size: Long+    val sha256: String+    fun readAt(offset: Long, length: Int): ByteArray+}++class FileStreamSource(private val file: File, override val sha256: String) : StreamSource {+    override val size: Long get() = file.length()++    override fun readAt(offset: Long, length: Int): ByteArray {+        val bytes = ByteArray(length)+        RandomAccessFile(file, "r").use { raf ->+            raf.seek(offset)+            raf.readFully(bytes)+        }+        return bytes+    }+}++/**+ * One peer link for one app. Owns accept + dial loops (either side may+ * initiate), the handshake, framing, data-item reassembly, stream transfers+ * and reconnect/backoff. Listeners become app-lifecycle-bound: unlike the+ * old GMS WearableListenerService, nothing wakes a dead process when a+ * message arrives — sync resumes on next start() and state documents are+ * republished then. That is the honest cost of dropping Play services.+ */+class WearLinkNode(+    context: Context,+    private val appId: String,+    private val listener: WearLinkListener,+    private val transport: WearLinkTransport = AndroidBluetoothTransport(context.applicationContext),+    private val certHashHex: String? = SigningTrust.localCertHashHex(context.applicationContext),+    private val packageName: String = context.applicationContext.packageName,+    parentScope: CoroutineScope? = null,+) {+    companion object {+        private const val TAG = "WearLink"+        private const val STREAM_ACK_WAIT_MS = 5_000L++        /** Runtime permissions the hosting activity must grant before start. */+        val REQUIRED_PERMISSIONS = arrayOf(android.Manifest.permission.BLUETOOTH_CONNECT)+    }++    private val scope = parentScope ?: CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private val instanceId = UUID.randomUUID().toString()+    private val ids = IdGenerator()+    private val reassembler = DataReassembler()+    private val seen = SeenMessageIds()+    private val responses = RequestTracker<CompletableDeferred<ByteArray?>>()+    private val acks = RequestTracker<CompletableDeferred<Boolean>>()+    private val streamAcks = RequestTracker<CompletableDeferred<Long>>()++    private val _state = MutableStateFlow<WearLinkState>(WearLinkState.Stopped)+    val state: StateFlow<WearLinkState> = _state.asStateFlow()+    val isConnected: Boolean get() = activeSession != null++    @Volatile private var activeSession: Session? = null+    @Volatile private var running = false+    private var acceptJob: Job? = null+    private var connectJob: Job? = null+    private var lastGeneration = 0L+    private val receiving = mutableMapOf<Long, ReceivingStream>()++    private inner class Session(+        val socket: WearLinkSocket,+        val initiatorInstance: String,+    ) {+        private val writeLock = Any()++        @Volatile var open = true++        fun send(frame: WearLinkFrame) {+            synchronized(writeLock) {+                if (!open) throw java.io.IOException("session closed")+                FrameCodec.encode(frame, socket.output)+            }+        }++        fun close() {+            open = false+            runCatching { socket.close() }+        }+    }++    private class ReceivingStream(val sink: StreamSink, val receiver: StreamReceiver)++    fun start() {+        if (running) return+        if (transport is AndroidBluetoothTransport && !transport.hasConnectPermission()) {+            _state.value = WearLinkState.PermissionMissing+            Log.status(TAG, "BLUETOOTH_CONNECT not granted")+            return+        }+        if (!transport.isAvailable()) {+            _state.value = WearLinkState.BluetoothOff+            return+        }+        if (certHashHex == null) {+            _state.value = WearLinkState.Failed("signing certificate unavailable")+            return+        }+        running = true+        acceptJob = scope.launch { acceptLoop() }+        connectJob = scope.launch { connectLoop() }+    }++    fun stop() {+        running = false+        acceptJob?.cancel(); connectJob?.cancel()+        activeSession?.close(); activeSession = null+        failPending()+        _state.value = WearLinkState.Stopped+    }++    // -- Sending -------------------------------------------------------------++    /** Fire-and-forget, or acked when [requireAck]. False when not connected. */+    suspend fun sendMessage(path: String, body: ByteArray, requireAck: Boolean = false): Boolean {+        val session = activeSession ?: return false+        if (body.size > WearLinkProtocol.MAX_MESSAGE_BYTES) return false+        val id = ids.next()+        if (requireAck) {+            val deferred = CompletableDeferred<Boolean>()+            acks.register(id, deferred)+            return try {+                session.send(WearLinkFrame(FrameType.MESSAGE, id, path, body))+                withTimeoutOrNull(10_000) { deferred.await() } ?: false+            } catch (expected: Exception) {+                Log.status(TAG, "send $path failed: ${expected.message}"); false+            } finally {+                acks.remove(id)+            }+        }+        return runCatching {+            session.send(WearLinkFrame(FrameType.MESSAGE, id, path, body)); true+        }.getOrDefault(false)+    }++    /** Correlated request/response over MESSAGE/RESPONSE frames. */+    suspend fun request(path: String, body: ByteArray, timeoutMillis: Long = 10_000): ByteArray? {+        val session = activeSession ?: return null+        val id = ids.next()+        val deferred = CompletableDeferred<ByteArray?>()+        responses.register(id, deferred)+        return try {+            session.send(WearLinkFrame(FrameType.MESSAGE, id, path, body))+            withTimeoutOrNull(timeoutMillis) { deferred.await() }+        } catch (expected: Exception) {+            Log.status(TAG, "request $path failed: ${expected.message}"); null+        } finally {+            responses.remove(id)+        }+    }++    /** Publish a path-keyed state document (chunked, generation-ordered). */+    suspend fun putData(path: String, body: ByteArray): Boolean {+        val session = activeSession ?: return false+        if (body.size > WearLinkProtocol.MAX_DATA_ITEM_BYTES) return false+        val generation = synchronized(this) {+            lastGeneration = maxOf(lastGeneration + 1, System.currentTimeMillis())+            lastGeneration+        }+        return runCatching {+            for (frame in DataItemCodec.chunk(path, generation, body)) session.send(frame)+            true+        }.getOrDefault(false)+    }++    /**+     * Stream [source] to [path]. Sends STREAM_OPEN, honours the receiver's+     * STREAM_ACK resume offset, then chunks + STREAM_CLOSE. The preceding+     * per-app offer message (size/hash contract) stays the app's job, as it+     * was over the old channel API.+     */+    suspend fun sendStream(path: String, source: StreamSource): Boolean {+        val session = activeSession ?: return false+        if (source.size > WearLinkProtocol.MAX_STREAM_BYTES) return false+        val transferId = ids.next()+        val header = StreamHeader(source.size, source.sha256)+        val deferred = CompletableDeferred<Long>()+        streamAcks.register(transferId, deferred)+        return try {+            session.send(WearLinkFrame(FrameType.STREAM_OPEN, transferId, path, header.encodeBody()))+            val resume = withTimeoutOrNull(STREAM_ACK_WAIT_MS) { deferred.await() } ?: 0L+            val sender = StreamSender(header, source.size)+            sender.seekTo(resume.coerceIn(0, source.size))+            while (true) {+                val chunk = sender.nextChunk(source::readAt) ?: break+                val offset = sender.nextOffset - chunk.size+                session.send(WearLinkFrame(FrameType.STREAM_CHUNK, transferId, path, chunk))+                // Offset is implicit (sequential delivery), kept in sync by sender state.+                check(offset >= 0)+            }+            session.send(WearLinkFrame(FrameType.STREAM_CLOSE, transferId, path, ByteArray(0)))+            true+        } catch (expected: Exception) {+            Log.status(TAG, "stream $path failed: ${expected.message}"); false+        } finally {+            streamAcks.remove(transferId)+        }+    }++    // -- Connection loops ----------------------------------------------------++    private suspend fun acceptLoop() {+        while (running) {+            try {+                val server = transport.listen(WearLinkProtocol.SERVICE_UUID, WearLinkProtocol.SERVICE_NAME)+                try {+                    while (running) {+                        val socket = server.accept()+                        scope.launch { handshakeAndAdopt(socket, isInitiator = false) }+                    }+                } finally {+                    runCatching { server.close() }+                }+            } catch (expected: Exception) {+                if (running) delay(1_000)+            }+        }+    }++    private suspend fun connectLoop() {+        val backoff = WearLinkBackoff()+        while (running) {+            if (activeSession != null) {+                backoff.reset()+                delay(2_000)+                continue+            }+            val peers = transport.bondedPeers()+            if (peers.isEmpty()) {+                _state.value = WearLinkState.NoBondedPeer+                delay(backoff.nextDelayMillis())+                continue+            }+            var connected = false+            for (peer in peers) {+                if (activeSession != null) break+                _state.value = WearLinkState.Connecting(peer.label)+                runCatching {+                    val socket = transport.connect(peer, WearLinkProtocol.SERVICE_UUID)+                    connected = handshakeAndAdopt(socket, isInitiator = true)+                }.onFailure { Log.status(TAG, "connect ${peer.label} failed: ${it.message}") }+                if (connected) break+            }+            if (!connected && activeSession == null) {+                _state.value = WearLinkState.Failed("no bonded peer runs $appId")+                delay(backoff.nextDelayMillis())+            }+        }+    }++    /** Run the handshake on [socket]; adopt if it wins. Returns adoption. */+    private fun handshakeAndAdopt(socket: WearLinkSocket, isInitiator: Boolean): Boolean {+        val cert = certHashHex ?: run { socket.close(); return false }+        return try {+            val session: Session+            if (isInitiator) {+                val nonce = WearLinkHandshake.newNonce()+                val hello = HelloMessage(+                    WearLinkProtocol.PROTOCOL_VERSION, appId, packageName, instanceId,+                    nonce, WearLinkHandshake.token(cert, nonce, appId),+                )+                FrameCodec.encode(WearLinkFrame(FrameType.HELLO, 0, "", hello.encode()), socket.output)+                val ackFrame = FrameCodec.decode(socket.input)+                    ?: throw java.io.IOException("eof in handshake")+                val ack = HelloMessage.decode(ackFrame.body)+                    ?: throw java.io.IOException("bad hello ack")+                val combined = nonce + ack.nonce+                when (val result = HandshakeVerifier.verify(ack, appId, cert, combined)) {+                    is HandshakeVerifier.Result.Rejected ->+                        throw java.io.IOException("handshake rejected: ${result.reason}")+                    is HandshakeVerifier.Result.Accepted -> Unit+                }+                session = Session(socket, instanceId)+            } else {+                val helloFrame = FrameCodec.decode(socket.input)+                    ?: throw java.io.IOException("eof in handshake")+                val hello = HelloMessage.decode(helloFrame.body)+                    ?: throw java.io.IOException("bad hello")+                when (val result = HandshakeVerifier.verify(hello, appId, cert, hello.nonce)) {+                    is HandshakeVerifier.Result.Rejected ->+                        throw java.io.IOException("handshake rejected: ${result.reason}")+                    is HandshakeVerifier.Result.Accepted -> Unit+                }+                val ackNonce = WearLinkHandshake.newNonce()+                val ack = HelloMessage(+                    WearLinkProtocol.PROTOCOL_VERSION, appId, packageName, instanceId,+                    ackNonce,+                    WearLinkHandshake.token(cert, hello.nonce + ackNonce, appId),+                )+                FrameCodec.encode(+                    WearLinkFrame(FrameType.HELLO_ACK, 0, "", ack.encode()), socket.output,+                )+                session = Session(socket, hello.instanceId)+            }+            adopt(session, socket.peerLabel)+        } catch (expected: Exception) {+            Log.status(TAG, "handshake failed: ${expected.message}")+            runCatching { socket.close() }+            false+        }+    }++    @Synchronized+    private fun adopt(session: Session, peerLabel: String): Boolean {+        val existing = activeSession+        if (existing != null && existing.open) {+            val keepCandidate = HandshakeVerifier.keepInitiatedBySmallerInstance(+                existing.initiatorInstance, session.initiatorInstance,+            )+            if (!keepCandidate) {+                session.close()+                return false+            }+            existing.close()+        }+        activeSession = session+        _state.value = WearLinkState.Connected(peerLabel)+        scope.launch { readLoop(session, peerLabel) }+        return true+    }++    private fun readLoop(session: Session, peerLabel: String) {+        try {+            while (running && session.open) {+                val frame = FrameCodec.decode(session.socket.input) ?: break+                dispatch(session, frame)+            }+        } catch (expected: Exception) {+            Log.status(TAG, "session ended: ${expected.message}")+        } finally {+            session.close()+            synchronized(this) {+                if (activeSession === session) {+                    activeSession = null+                    if (running) _state.value = WearLinkState.Failed("peer disconnected")+                }+            }+            failPending()+            synchronized(receiving) {+                receiving.values.forEach { runCatching { it.sink.close(false) } }+                receiving.clear()+            }+        }+    }++    private fun failPending() {+        responses.failAll().forEach { it.complete(null) }+        acks.failAll().forEach { it.complete(false) }+        streamAcks.failAll().forEach { it.complete(0L) }+    }++    private fun dispatch(session: Session, frame: WearLinkFrame) {+        when (frame.type) {+            FrameType.PING -> runCatching {+                session.send(WearLinkFrame(FrameType.PONG, frame.id))+            }+            FrameType.MESSAGE -> {+                session.send(WearLinkFrame(FrameType.MESSAGE_ACK, frame.id))+                if (!seen.markIfNew(frame.id)) return+                val response = listener.onRequest(frame.path, frame.body)+                if (response != null) {+                    runCatching {+                        session.send(WearLinkFrame(FrameType.RESPONSE, frame.id, frame.path, response))+                    }+                } else {+                    listener.onMessage(frame.path, frame.body)+                }+            }+            FrameType.RESPONSE -> responses.complete(frame.id)?.complete(frame.body)+            FrameType.MESSAGE_ACK -> acks.complete(frame.id)?.complete(true)+            FrameType.DATA -> reassembler.onFrame(frame)?.let { listener.onData(frame.path, it) }+            FrameType.STREAM_OPEN -> onStreamOpen(session, frame)+            FrameType.STREAM_CHUNK -> onStreamChunk(frame)+            FrameType.STREAM_CLOSE -> onStreamClose(frame)+            FrameType.STREAM_ACK -> decodeOffsetBody(frame.body)?.let {+                streamAcks.complete(frame.id)?.complete(it)+            }+            else -> Unit+        }+    }++    private fun onStreamOpen(session: Session, frame: WearLinkFrame) {+        val header = StreamHeader.decodeBody(frame.body) ?: return+        if (header.totalSize > WearLinkProtocol.MAX_STREAM_BYTES) return+        val sink = listener.onStreamOpen(frame.path, header) ?: run {+            runCatching {+                session.send(+                    WearLinkFrame(+                        FrameType.STREAM_ACK, frame.id, frame.path, encodeOffsetBody(0),+                    ),+                )+            }+            return+        }+        val receiver = StreamReceiver(header, sink.resumeOffset, sink.prefixStream())+        synchronized(receiving) { receiving[frame.id] = ReceivingStream(sink, receiver) }+        runCatching {+            session.send(+                WearLinkFrame(+                    FrameType.STREAM_ACK, frame.id, frame.path,+                    encodeOffsetBody(receiver.ackOffset),+                ),+            )+        }+    }++    private fun onStreamChunk(frame: WearLinkFrame) {+        val context = synchronized(receiving) { receiving[frame.id] } ?: return+        val offset = context.receiver.received+        if (context.receiver.onChunk(offset, frame.body)) {+            runCatching { context.sink.write(frame.body, offset) }+        }+    }++    private fun onStreamClose(frame: WearLinkFrame) {+        val context = synchronized(receiving) { receiving.remove(frame.id) } ?: return+        val verified = context.receiver.verifyComplete()+        runCatching { context.sink.close(verified) }+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.ktnew file mode 100644index 0000000000..41e78c8a9e--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt@@ -0,0 +1,109 @@+package com.vayunmathur.library.wearlink++import java.util.UUID++/**+ * WearLink wire protocol v1 — first-party replacement for the Play-services+ * Wearable Data Layer. See README.md in this module for the full design.+ *+ * Transport: one Bluetooth Classic RFCOMM stream per peer pair. RFCOMM (not+ * BLE GATT) is the session transport because it is a plain ordered byte+ * stream: APK-sized transfers need no MTU chunk negotiation, no+ * characteristic/descriptor plumbing, and flow control is the socket's.+ * BLE is not used at all — the peer is already BT-bonded by Wear OS, we look+ * it up in the bonded set, so there is no scan and no advertisement (hence+ * no BLUETOOTH_SCAN/ADVERTISE and no location-permission workaround).+ *+ * Both sides run an accept loop on [SERVICE_UUID] and both sides dial bonded+ * devices, so either side can initiate. Simultaneous dials are resolved by+ * the handshake instance-id tie-break (see [WearLinkHandshake]).+ */+object WearLinkProtocol {+    /** RFCOMM service record UUID ("MAWL" + v1). Fixed: changing it is a new protocol. */+    val SERVICE_UUID: UUID = UUID.fromString("4d41574c-0001-1000-8000-00805f9b34fb")++    const val SERVICE_NAME = "ModernApps WearLink"+    const val PROTOCOL_VERSION = 1++    /** Largest framed payload. Data/stream bodies chunk well under this. */+    const val MAX_FRAME_PAYLOAD = 64 * 1024++    /** Largest single message body (messages are commands, not documents). */+    const val MAX_MESSAGE_BYTES = 256 * 1024++    /** Largest data item (path-keyed state document) after reassembly. */+    const val MAX_DATA_ITEM_BYTES = 4 * 1024 * 1024++    /** Body bytes per DATA frame chunk. */+    const val DATA_CHUNK_BYTES = 16 * 1024++    /** Body bytes per STREAM frame chunk. */+    const val STREAM_CHUNK_BYTES = 16 * 1024++    /** Largest stream (APK) accepted; mirrors the appstore watch storage cap. */+    const val MAX_STREAM_BYTES = 200L * 1024 * 1024+}++/** Frame kinds, mirroring the Data Layer surfaces they replace. */+enum class FrameType(val code: Int) {+    HELLO(1),+    HELLO_ACK(2),+    /** Fire-and-forget or ack-requested message (MessageClient). */+    MESSAGE(3),+    /** Correlated reply to a MESSAGE sent with an id expecting a response. */+    RESPONSE(4),+    /** Acknowledgement of a MESSAGE id. */+    MESSAGE_ACK(5),+    /** One chunk of a path-keyed state document (DataClient). */+    DATA(6),+    /** Stream header: total size + SHA-256 + optional resume (ChannelClient). */+    STREAM_OPEN(7),+    /** Raw stream bytes; frame id is the transfer id. */+    STREAM_CHUNK(8),+    /** End of stream; receiver verifies size + SHA-256 before completing. */+    STREAM_CLOSE(9),+    /** Receiver's durable received offset for [transferId]; enables resume. */+    STREAM_ACK(10),+    PING(11),+    PONG(12),+    ERROR(13),+    ;++    companion object {+        fun fromCode(code: Int): FrameType? = entries.firstOrNull { it.code == code }+    }+}++/** One framed unit. [body] is type-specific; see the codec helpers. */+data class WearLinkFrame(+    val type: FrameType,+    val id: Long,+    val path: String = "",+    val body: ByteArray = ByteArray(0),+) {+    override fun equals(other: Any?): Boolean {+        if (this === other) return true+        if (other !is WearLinkFrame) return false+        return type == other.type && id == other.id && path == other.path &&+            body.contentEquals(other.body)+    }++    override fun hashCode(): Int {+        var r = type.hashCode()+        r = 31 * r + id.hashCode()+        r = 31 * r + path.hashCode()+        r = 31 * r + body.contentHashCode()+        return r+    }+}++/** Connection lifecycle, surfaced to each app's existing sync state. */+sealed interface WearLinkState {+    data object Stopped : WearLinkState+    data object PermissionMissing : WearLinkState+    data object BluetoothOff : WearLinkState+    data object NoBondedPeer : WearLinkState+    data class Connecting(val peerLabel: String) : WearLinkState+    data class Connected(val peerLabel: String) : WearLinkState+    data class Failed(val reason: String) : WearLinkState+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.ktnew file mode 100644index 0000000000..90468cb022--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt@@ -0,0 +1,43 @@+package com.vayunmathur.library.wearlink++import java.io.Closeable+import java.io.InputStream+import java.io.OutputStream+import java.util.UUID++/** A bonded peer candidate, as the platform Bluetooth stack reports it. */+data class BondedPeer(val address: String, val label: String)++/**+ * One connected byte stream. Behind this seam the Android implementation is+ * a BluetoothSocket; unit tests use in-memory pipes. All IO on these streams+ * is blocking and must run off the main thread (the node enforces that).+ */+interface WearLinkSocket : Closeable {+    val input: InputStream+    val output: OutputStream+    val peerLabel: String+}++interface WearLinkServerSocket : Closeable {+    /** Blocking accept; throws/returns via close from another thread. */+    fun accept(): WearLinkSocket+}++/**+ * Platform Bluetooth seam. Implementations must only ever talk to bonded+ * devices (no discovery): the Wear OS companion is bonded by the system.+ */+interface WearLinkTransport {+    /** True when a Bluetooth adapter exists and is powered on. */+    fun isAvailable(): Boolean++    /** Currently bonded devices; empty when permission is missing. */+    fun bondedPeers(): List<BondedPeer>++    /** Blocking RFCOMM connect to [peer] for [serviceUuid]. */+    fun connect(peer: BondedPeer, serviceUuid: UUID): WearLinkSocket++    /** Blocking-accept RFCOMM server for [serviceUuid]. */+    fun listen(serviceUuid: UUID, serviceName: String): WearLinkServerSocket+}
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.ktnew file mode 100644index 0000000000..d7a4816479--- /dev/null+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.library.wearlink++import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.PipedInputStream+import java.io.PipedOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.assertFailsWith++class WearLinkProtocolTest {++    @Test+    fun `frame round trips and stream decoder reads consecutive frames`() {+        val frames = listOf(+            WearLinkFrame(FrameType.MESSAGE, 42, "/x/y", "hello".encodeToByteArray()),+            WearLinkFrame(FrameType.DATA, 43, "/d", ByteArray(100) { it.toByte() }),+            WearLinkFrame(FrameType.PING, 44),+        )+        val out = ByteArrayOutputStream()+        frames.forEach { FrameCodec.encode(it, out) }+        val input = ByteArrayInputStream(out.toByteArray())+        frames.forEach { expected ->+            assertEquals(expected, FrameCodec.decode(input))+        }+        assertNull(FrameCodec.decode(input))+    }++    @Test+    fun `frame codec rejects oversize and unknown types`() {+        val big = WearLinkFrame(+            FrameType.MESSAGE, 1, "/x", ByteArray(WearLinkProtocol.MAX_FRAME_PAYLOAD),+        )+        assertFailsWith<IllegalArgumentException> { FrameCodec.encodeToBytes(big) }+        // Corrupt length header.+        val bad = byteArrayOf(0, 0, 0, 2, 99, 0)+        assertFailsWith<java.io.IOException> { FrameCodec.decode(ByteArrayInputStream(bad)) }+    }++    @Test+    fun `handshake accepts same signer and app, rejects other signer or app`() {+        val cert = WearLinkHandshake.certHashHex("cert-der".encodeToByteArray())+        val nonce = ByteArray(WearLinkHandshake.NONCE_BYTES) { it.toByte() }+        val hello = HelloMessage(+            WearLinkProtocol.PROTOCOL_VERSION, "calendar_wear_companion",+            "com.vayunmathur.calendar", "watch-1", nonce,+            WearLinkHandshake.token(cert, nonce, "calendar_wear_companion"),+        )+        assertTrue(+            HandshakeVerifier.verify(hello, "calendar_wear_companion", cert, nonce)+                is HandshakeVerifier.Result.Accepted,+        )+        val otherCert = WearLinkHandshake.certHashHex("other".encodeToByteArray())+        assertTrue(+            HandshakeVerifier.verify(hello, "calendar_wear_companion", otherCert, nonce)+                is HandshakeVerifier.Result.Rejected,+        )+        assertTrue(+            HandshakeVerifier.verify(hello, "contacts_wear_companion", cert, nonce)+                is HandshakeVerifier.Result.Rejected,+        )+        // Replay into a new session (different nonce) fails.+        val newNonce = ByteArray(WearLinkHandshake.NONCE_BYTES) { (it + 9).toByte() }+        assertTrue(+            HandshakeVerifier.verify(hello, "calendar_wear_companion", cert, newNonce)+                is HandshakeVerifier.Result.Rejected,+        )+        // Hello binary round-trip.+        assertEquals(hello, HelloMessage.decode(hello.encode()))+    }++    @Test+    fun `simultaneous dial tie break is symmetric`() {+        assertTrue(HandshakeVerifier.keepInitiatedBySmallerInstance("b", "a"))+        assertFalse(HandshakeVerifier.keepInitiatedBySmallerInstance("a", "b"))+    }++    @Test+    fun `data items chunk, reassemble out of order, reject stale and corrupt`() {+        val payload = ByteArray(40_000) { (it % 251).toByte() }+        val frames = DataItemCodec.chunk("/calendar/snapshot", 7L, payload)+        assertTrue(frames.size > 1)+        val reassembler = DataReassembler()+        var completed: ByteArray? = null+        // Reverse order: still completes only at the last missing chunk.+        for (frame in frames.reversed()) {+            val done = reassembler.onFrame(frame)+            if (done != null) completed = done+        }+        assertNotNull(completed)+        assertTrue(payload.contentEquals(completed))+        // Stale generation is ignored.+        val stale = DataItemCodec.chunk("/calendar/snapshot", 6L, "old".encodeToByteArray())+        assertNull(reassembler.onFrame(stale.first()))+        // Corrupted chunk (flip a byte) never completes.+        val badFrames = DataItemCodec.chunk("/other", 1L, payload)+        val corrupted = badFrames.first().let {+            val chunk = DataChunk.decodeBody(it.body)!!+            val bytes = chunk.bytes.copyOf().also { b -> b[0] = (b[0] + 1).toByte() }+            it.copy(body = chunk.copy(bytes = bytes).encodeBody())+        }+        val r2 = DataReassembler()+        var badCompleted: ByteArray? = null+        for (frame in listOf(corrupted) + badFrames.drop(1)) {+            r2.onFrame(frame)?.let { badCompleted = it }+        }+        assertNull(badCompleted)+    }++    @Test+    fun `stream receiver verifies hash and sender resumes from ack offset`() {+        val data = ByteArray(50_000) { (it % 241).toByte() }+        val header = StreamHeader(data.size.toLong(), Sha256.hex(data))+        val sender = StreamSender(header, data.size.toLong())+        val receiver = StreamReceiver(header)+        val collected = ByteArrayOutputStream()+        while (true) {+            val offset = sender.nextOffset+            val chunk = sender.nextChunk { off, len ->+                data.copyOfRange(off.toInt(), off.toInt() + len)+            } ?: break+            assertTrue(receiver.onChunk(offset, chunk))+            collected.write(chunk)+        }+        assertTrue(sender.complete)+        assertTrue(receiver.verifyComplete())+        assertTrue(data.contentEquals(collected.toByteArray()))++        // Resume: receiver kept first 20_000 bytes, sender seeks.+        val prefix = data.copyOfRange(0, 20_000)+        val resumedReceiver = StreamReceiver(header, 20_000, java.io.ByteArrayInputStream(prefix))+        assertEquals(20_000L, resumedReceiver.ackOffset)+        val resumedSender = StreamSender(header, data.size.toLong())+        resumedSender.seekTo(resumedReceiver.ackOffset)+        while (true) {+            val offset = resumedSender.nextOffset+            val chunk = resumedSender.nextChunk { off, len ->+                data.copyOfRange(off.toInt(), off.toInt() + len)+            } ?: break+            assertTrue(resumedReceiver.onChunk(offset, chunk))+        }+        assertTrue(resumedReceiver.verifyComplete())++        // Tamper fails verification.+        val badReceiver = StreamReceiver(header)+        val badChunk = data.copyOfRange(0, 100).also { it[0] = (it[0] + 1).toByte() }+        assertTrue(badReceiver.onChunk(0, badChunk))+        assertFalse(badReceiver.verifyComplete())+        // Out-of-order chunk aborts.+        val ooo = StreamReceiver(header)+        assertFalse(ooo.onChunk(100, data.copyOfRange(100, 200)))+        assertTrue(ooo.failed)+    }++    @Test+    fun `backoff doubles caps resets and trackers are bounded`() {+        val backoff = WearLinkBackoff(1_000, 30_000)+        assertEquals(1_000L, backoff.nextDelayMillis())+        assertEquals(2_000L, backoff.nextDelayMillis())+        assertEquals(4_000L, backoff.nextDelayMillis())+        repeat(10) { backoff.nextDelayMillis() }+        assertEquals(30_000L, backoff.nextDelayMillis())+        backoff.reset()+        assertEquals(1_000L, backoff.nextDelayMillis())++        val tracker = RequestTracker<String>()+        tracker.register(1, "a")+        assertEquals("a", tracker.complete(1))+        assertNull(tracker.complete(1))++        val seen = SeenMessageIds(capacity = 2)+        assertTrue(seen.markIfNew(1))+        assertFalse(seen.markIfNew(1))+        assertTrue(seen.markIfNew(2))+        assertTrue(seen.markIfNew(3)) // evicts 1+        assertTrue(seen.markIfNew(1))+    }++    @Test+    fun `in-memory pipe transports a framed message end to end`() {+        val serverToClient = PipedOutputStream()+        val clientInput = PipedInputStream(serverToClient)+        val frame = WearLinkFrame(FrameType.MESSAGE, 9, "/contacts/handoff", "x".encodeToByteArray())+        FrameCodec.encode(frame, serverToClient)+        assertEquals(frame, FrameCodec.decode(clientInput))+    }+}
notes-wear/AGENTS.md
diff --git a/notes-wear/AGENTS.md b/notes-wear/AGENTS.mdnew file mode 100644index 0000000000..9a44c4e289--- /dev/null+++ b/notes-wear/AGENTS.md@@ -0,0 +1,45 @@+# AGENTS.md — notes-wear/ (':notes-wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `notes-wear/` + `notes/` (the phone side of the same feature).++- Gradle: :notes-wear / dir: notes-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Notes (`:notes`). This module deliberately+uses `applicationId = "com.vayunmathur.notes"` (the phone app's) with the+shared dev/release signing from the convention plugins: WearLink's+handshake token requires the same signing certificate on both sides, so+changing either breaks phone<->watch sync. Bootstrap is a one-time ADB+sideload of this APK onto the watch.++## Protocol+`domain/WearNotesProtocol.kt` is a copy of the phone's file (Gradle cannot+depend on another app module). Change both copies together; each side's+`WearNotesProtocolTest` pins the same golden JSON.++- Snapshot + watch-state sync: WearLink data items (`/notes/snapshot`, `/notes/watch-state`)+- Watch-originated ops: WearLink message (`/notes/op`, create/edit/delete)+- Sync request: WearLink message (`/notes/request-sync`), watch -> phone only+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Sync semantics (stated, not implied)+- Phone -> watch: bounded snapshot — 50 most recent notes, title ≤120+  chars, body ≤4000 chars, ≤90_000 JSON bytes (`truncated` flags loss).+  The watch persists it and reads fully offline.+- Watch -> phone: create/edit/delete ops flow over the link and apply on+  the phone only. Conflict policy is last-writer-wins per note by+  `updatedAt` (ties: tombstone, then larger title/body) — no text merge.+- Honest writes: notes with image/ink blocks on the phone (`textOnly =+  false`) are read-only on the watch except delete; watch creates/edits+  become single-text-block notes on the phone. An op stays *pending* on+  the watch (persisted, resent on reconnect) until a phone snapshot+  reflects it — the UI never claims "synced" before that.++## Verify (this module only)+```+./gradlew :notes-wear:assembleDev+./gradlew :notes-wear:testDebugUnitTest+```
notes-wear/build.gradle.kts
diff --git a/notes-wear/build.gradle.kts b/notes-wear/build.gradle.ktsnew file mode 100644index 0000000000..249f3aa544--- /dev/null+++ b/notes-wear/build.gradle.kts@@ -0,0 +1,39 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "subject"+}++// Version shared with the phone app (root version.txt), read directly because+// common-conventions-wear inlines 1/"1.0" until a wear consumer wires the shared reader.+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+    // The WearLink handshake only connects apps that share a package name and+    // signing certificate, so this module MUST ship as the phone app's package:+    // same applicationId (below) and the same signing config the convention+    // plugins already apply to both (debug key for dev, release key for+    // release). The namespace only names this module's own R/resources.+    namespace = "com.vayunmathur.notes.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.notes"+        // Convention defaults to 30, but :library:log (pulled in by the wear+        // convention) requires 31, so the watch floor is 31.+        minSdk = 31+        versionCode = wearVersionCode+        versionName = wearVersionName+    }+}++dependencies {+    // Watch side of the Wear OS sync (see domain/WearNotesProtocol.kt, the+    // copy of the phone protocol it must stay in step with).+    implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
notes-wear/src/main/AndroidManifest.xml
diff --git a/notes-wear/src/main/AndroidManifest.xml b/notes-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7ccb8c3001--- /dev/null+++ b/notes-wear/src/main/AndroidManifest.xml@@ -0,0 +1,40 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Wear OS form factor. Declaring the watch hardware makes this build+         installable on Wear OS; the touchscreen is not required there. -->+    <uses-feature+        android:name="android.hardware.type.watch"+        android:required="true" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />++    <uses-permission android:name="android.permission.WAKE_LOCK" />++    <application+        android:allowBackup="false"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@android:style/Theme.Material.NoActionBar">++        <!-- Paired with the phone app, not a standalone watch app. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />++        <activity+            android:name=".ui.WearMainActivity"+            android:exported="true"+            android:taskAffinity="">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->+    </application>+</manifest>
notes-wear/src/main/java/com/vayunmathur/notes/wear/data/WearNotesStore.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/data/WearNotesStore.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/data/WearNotesStore.ktnew file mode 100644index 0000000000..691706bbc9--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/data/WearNotesStore.kt@@ -0,0 +1,143 @@+package com.vayunmathur.notes.wear.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.notes.wear.domain.WearNote+import com.vayunmathur.notes.wear.domain.WearNoteOp+import com.vayunmathur.notes.wear.domain.WearNotesProtocol+import com.vayunmathur.notes.wear.domain.WearNotesSnapshot+import com.vayunmathur.notes.wear.domain.WearOpKind+import com.vayunmathur.notes.wear.domain.mergeWearSnapshot+import com.vayunmathur.notes.wear.domain.reflectedOps+import java.io.File+import java.util.UUID+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * The watch's local truth: the last phone snapshot merged with this watch's+ * pending ops, persisted as JSON in app-private storage so notes read,+ * create and edit fully offline (phone absent, process cold-started).+ * Pending ops are persisted separately and survive until a phone snapshot+ * reflects them (see [WearNotesProtocol] for the LWW policy).+ */+class WearNotesStore private constructor(private val context: Context) {++    companion object {+        private const val TAG = "WearNotesStore"++        @Volatile+        private var instance: WearNotesStore? = null++        /** The process-wide store (bridge and UI must agree on one). */+        fun get(context: Context): WearNotesStore = instance ?: synchronized(this) {+            instance ?: WearNotesStore(context.applicationContext).also { instance = it }+        }++        /** New watch-originated notes use the phone's syncId shape (32 hex chars). */+        fun newSyncId(): String = UUID.randomUUID().toString().replace("-", "")+    }++    private val snapshotFile = File(context.filesDir, "wear-notes-snapshot.json")+    private val pendingFile = File(context.filesDir, "wear-notes-pending.json")++    private val _notes = MutableStateFlow(loadNotes())+    private val _pendingOps = MutableStateFlow(loadPending())++    /** Local view: phone snapshot merged with pending watch ops, recent first. */+    val notes: StateFlow<List<WearNote>> = _notes.asStateFlow()++    /** Watch-originated ops not yet reflected by a phone snapshot. */+    val pendingOps: StateFlow<List<WearNoteOp>> = _pendingOps.asStateFlow()++    private var lastSnapshot: WearNotesSnapshot = loadSnapshot()++    /** Snapshot generation the local view is based on (for watch-state reporting). */+    val appliedGeneratedAtMillis: Long get() = lastSnapshot.generatedAtMillis++    /** Applies a phone snapshot: drops reflected ops, keeps winning pending ones. */+    fun setSnapshot(snapshot: WearNotesSnapshot) {+        lastSnapshot = snapshot+        val reflected = reflectedOps(snapshot, _pendingOps.value)+        if (reflected.isNotEmpty()) {+            _pendingOps.value = _pendingOps.value - reflected.toSet()+            persistPending()+        }+        _notes.value = mergeWearSnapshot(snapshot, _pendingOps.value)+        persistSnapshot()+        com.vayunmathur.notes.wear.sync.WearLinkBridge.publishWatchState(context)+    }++    /** Creates a note locally and queues its op; visible immediately, pending until reflected. */+    fun createNote(title: String, body: String, nowMillis: Long = System.currentTimeMillis()): WearNote {+        val note = WearNote(+            syncId = newSyncId(),+            title = title.take(WearNotesProtocol.MAX_TITLE_CHARS),+            body = body.take(WearNotesProtocol.MAX_BODY_CHARS),+            updatedAt = nowMillis,+        )+        queue(WearNoteOp(WearOpKind.UPSERT, note))+        return note+    }++    /**+     * Edits a text-only note locally and queues its op. The stamp is+     * `max(now, edited.updatedAt + 1)` so it beats the version it derives+     * from under LWW even with a skewed watch clock. Null when the note is+     * missing or not text-only (the UI offers no edit there either).+     */+    fun editNote(syncId: String, title: String, body: String, nowMillis: Long = System.currentTimeMillis()): WearNote? {+        val current = _notes.value.firstOrNull { it.syncId == syncId } ?: return null+        if (!current.textOnly) return null+        val edited = current.copy(+            title = title.take(WearNotesProtocol.MAX_TITLE_CHARS),+            body = body.take(WearNotesProtocol.MAX_BODY_CHARS),+            bodyTruncated = false,+            updatedAt = maxOf(nowMillis, current.updatedAt + 1),+        )+        queue(WearNoteOp(WearOpKind.UPSERT, edited))+        return edited+    }++    /** Deletes any note locally (tombstone op) and queues it; the note hides immediately. */+    fun deleteNote(syncId: String, nowMillis: Long = System.currentTimeMillis()): Boolean {+        val current = _notes.value.firstOrNull { it.syncId == syncId } ?: return false+        queue(+            WearNoteOp(+                WearOpKind.DELETE,+                current.copy(deleted = true, updatedAt = maxOf(nowMillis, current.updatedAt + 1)),+            ),+        )+        return true+    }++    private fun queue(op: WearNoteOp) {+        // One pending op per note: a newer local change supersedes the older one.+        _pendingOps.value = _pendingOps.value.filter { it.note.syncId != op.note.syncId } + op+        persistPending()+        _notes.value = mergeWearSnapshot(lastSnapshot, _pendingOps.value)+        com.vayunmathur.notes.wear.sync.WearLinkBridge.flushPending(context)+    }++    private fun loadSnapshot(): WearNotesSnapshot = runCatching {+        WearNotesProtocol.json.decodeFromString<WearNotesSnapshot>(snapshotFile.readText())+    }.getOrDefault(WearNotesSnapshot())++    private fun loadNotes(): List<WearNote> = mergeWearSnapshot(loadSnapshot(), loadPending())++    private fun loadPending(): List<WearNoteOp> = runCatching {+        WearNotesProtocol.json.decodeFromString<List<WearNoteOp>>(pendingFile.readText())+    }.getOrDefault(emptyList())++    private fun persistSnapshot() {+        runCatching { snapshotFile.writeText(WearNotesProtocol.json.encodeToString(lastSnapshot)) }+            .onFailure { Log.status(TAG, "persist snapshot failed: ${it.message}") }+    }++    private fun persistPending() {+        runCatching { pendingFile.writeText(WearNotesProtocol.json.encodeToString(_pendingOps.value)) }+            .onFailure { Log.status(TAG, "persist pending ops failed: ${it.message}") }+    }+}
notes-wear/src/main/java/com/vayunmathur/notes/wear/domain/WearNotesProtocol.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/domain/WearNotesProtocol.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/domain/WearNotesProtocol.ktnew file mode 100644index 0000000000..b28c33dc72--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/domain/WearNotesProtocol.kt@@ -0,0 +1,196 @@+package com.vayunmathur.notes.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Notes companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:notes-wear`,+ * applicationId `com.vayunmathur.notes`) carries a copy of this file under+ * `com.vayunmathur.notes.wear.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON so a one-sided edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [SNAPSHOT_PATH] phone -> watch (bounded recent notes) and+ *   [WATCH_STATE_PATH] watch -> phone (what the watch applied + pending ops).+ * - Messages: [OP_PATH] watch -> phone (one create/edit/delete) and+ *   [REQUEST_SYNC_PATH] watch -> phone (ask for a fresh snapshot).+ *   Delivery needs a live session; nothing wakes a dead phone process.+ *+ * Conflict policy — last-writer-wins per note, stated plainly: for one+ * `syncId`, the version with the larger `updatedAt` wins on both sides.+ * Ties break deterministically: a tombstone beats a live note, then the+ * lexicographically larger (title, body) wins. Watch edits stamp+ * `max(now, editedVersion.updatedAt + 1)` so an edit always beats the+ * version it was made from, even with a skewed watch clock; an edit made+ * from a stale copy can still lose to a newer phone edit — that is LWW,+ * not merging, and no text merge is attempted or claimed.+ *+ * Honest write scope: the watch body is plain text (`Note.content`). A+ * note whose phone body contains image/ink blocks is flagged+ * `textOnly = false`: the watch renders its text but offers no edit (a+ * text-only replacement would destroy the blocks). Delete is offered for+ * every note — a tombstone destroys nothing the phone cannot still show+ * as deleted — and create/edit only ever produce a single text block on+ * the phone. No watch action claims a write until the phone applies it+ * and the next snapshot reflects it; unreflected ops stay pending.+ */+object WearNotesProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "notes_wear_companion"++    /** Data-item path (phone -> watch): the [WearNotesSnapshot] JSON. */+    const val SNAPSHOT_PATH = "/notes/snapshot"++    /** Data-item path (watch -> phone): the [WearWatchState] JSON. */+    const val WATCH_STATE_PATH = "/notes/watch-state"++    /** Message path (watch -> phone): one [WearNoteOp] JSON. */+    const val OP_PATH = "/notes/op"++    /** Message path (watch -> phone): ask the phone to publish a fresh snapshot. */+    const val REQUEST_SYNC_PATH = "/notes/request-sync"++    /** Most-recent notes in one snapshot; a watch renders a short list. */+    const val MAX_NOTES = 50++    /** Largest snapshot JSON in UTF-8 bytes (near the old 100 KB DataItem ceiling). */+    const val MAX_JSON_BYTES = 90_000++    /** Field caps applied when a snapshot is built. */+    const val MAX_TITLE_CHARS = 120+    const val MAX_BODY_CHARS = 4_000++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One note trimmed to watch size. [syncId] is the phone note's stable sync identity. */+@Serializable+data class WearNote(+    val syncId: String,+    val title: String,+    /** Plain-text body, capped at [WearNotesProtocol.MAX_BODY_CHARS]. */+    val body: String = "",+    /** Last-writer-wins stamp (epoch millis / hybrid stamp on the phone). */+    val updatedAt: Long = 0L,+    val deleted: Boolean = false,+    /** False when the phone body has image/ink blocks: watch is read-only for it. */+    val textOnly: Boolean = true,+    /** True when [body] was cut at the cap; the full text stays on the phone. */+    val bodyTruncated: Boolean = false,+)++/** The phone's bounded recent-notes snapshot for the watch ([WearNotesProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearNotesSnapshot(+    val generatedAtMillis: Long = 0L,+    /** Live notes only, most recently updated first. */+    val notes: List<WearNote> = emptyList(),+    /** True when the count/byte caps dropped notes. */+    val truncated: Boolean = false,+)++/** What the watch last applied, published at [WearNotesProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+    val appliedGeneratedAtMillis: Long = 0L,+    val noteCount: Int = 0,+    /** Watch-originated ops not yet reflected in a phone snapshot. */+    val pendingOps: Int = 0,+)++/** Kind of a watch-originated change. */+@Serializable+enum class WearOpKind { UPSERT, DELETE }++/** One watch-originated create/edit (UPSERT) or delete (DELETE), as [WearNotesProtocol.OP_PATH]. */+@Serializable+data class WearNoteOp(+    val kind: WearOpKind,+    val note: WearNote,+)++/**+ * True when [candidate] wins over [incumbent] under the stated LWW policy+ * (see [WearNotesProtocol]): larger `updatedAt`, then tombstone, then the+ * lexicographically larger (title, body). Identical versions never win.+ */+fun wearNoteWins(candidate: WearNote, incumbent: WearNote): Boolean {+    if (candidate.updatedAt != incumbent.updatedAt) return candidate.updatedAt > incumbent.updatedAt+    if (candidate.deleted != incumbent.deleted) return candidate.deleted+    if (candidate.title != incumbent.title) return candidate.title > incumbent.title+    return candidate.body > incumbent.body+}++/**+ * Builds a bounded snapshot: most-recently-updated live notes first, field+ * caps applied, then [WearNotesProtocol.MAX_NOTES] and+ * [WearNotesProtocol.MAX_JSON_BYTES] enforced by dropping the oldest kept+ * notes (recent notes — the watch's main screen — survive longest).+ */+fun buildWearSnapshot(candidates: List<WearNote>, generatedAtMillis: Long): WearNotesSnapshot {+    val sorted = candidates+        .filter { !it.deleted }+        .sortedWith(compareByDescending<WearNote> { it.updatedAt }.thenBy { it.syncId })+        .map { note ->+            note.copy(+                title = note.title.take(WearNotesProtocol.MAX_TITLE_CHARS),+                body = note.body.take(WearNotesProtocol.MAX_BODY_CHARS),+                bodyTruncated = note.bodyTruncated || note.body.length > WearNotesProtocol.MAX_BODY_CHARS,+            )+        }+    var kept = sorted.take(WearNotesProtocol.MAX_NOTES)+    var truncated = kept.size < sorted.size+    var snapshot = WearNotesSnapshot(generatedAtMillis, kept, truncated)+    while (kept.isNotEmpty() &&+        WearNotesProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+        WearNotesProtocol.MAX_JSON_BYTES+    ) {+        kept = kept.dropLast(1)+        truncated = true+        snapshot = snapshot.copy(notes = kept, truncated = true)+    }+    return snapshot+}++/**+ * Merges a phone [snapshot] into the watch's local view: a pending+ * watch-originated op wins over the snapshot copy of the same note when+ * [wearNoteWins] says so (the phone has not applied/reflected it yet);+ * otherwise the snapshot is truth. Pending deletes hide their note.+ * Result is most-recent first and contains no tombstones.+ */+fun mergeWearSnapshot(+    snapshot: WearNotesSnapshot,+    pendingOps: List<WearNoteOp>,+): List<WearNote> {+    val byId = snapshot.notes.associateBy { it.syncId }.toMutableMap()+    for (op in pendingOps) {+        val local = op.note+        val remote = byId[local.syncId]+        if (remote == null || wearNoteWins(local, remote)) {+            if (local.deleted) byId.remove(local.syncId) else byId[local.syncId] = local+        }+    }+    return byId.values+        .filter { !it.deleted }+        .sortedWith(compareByDescending<WearNote> { it.updatedAt }.thenBy { it.syncId })+}++/** Ops already reflected by [snapshot] (snapshot version is at least as new) and safe to drop. */+fun reflectedOps(snapshot: WearNotesSnapshot, pendingOps: List<WearNoteOp>): List<WearNoteOp> =+    pendingOps.filter { op ->+        val remote = snapshot.notes.firstOrNull { it.syncId == op.note.syncId }+        when {+            // A delete is reflected when the note is gone from the live snapshot+            // at a stamp that cannot beat it, or simply absent entirely.+            op.kind == WearOpKind.DELETE -> remote == null+            remote == null -> false+            else -> !wearNoteWins(op.note, remote)+        }+    }
notes-wear/src/main/java/com/vayunmathur/notes/wear/sync/WearLinkBridge.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/sync/WearLinkBridge.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..e3f7452001--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/sync/WearLinkBridge.kt@@ -0,0 +1,106 @@+package com.vayunmathur.notes.wear.sync++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.notes.wear.data.WearNotesStore+import com.vayunmathur.notes.wear.domain.WearNoteOp+import com.vayunmathur.notes.wear.domain.WearNotesProtocol+import com.vayunmathur.notes.wear.domain.WearNotesSnapshot+import com.vayunmathur.notes.wear.domain.WearWatchState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for Notes: snapshot data items land in+ * [WearNotesStore], watch state goes back as a data item, pending ops and+ * request-sync are messages. Replaces any Play-services listener; delivery+ * is bound to this process being alive. Pending ops are (re)sent whenever+ * a session connects and whenever a new op is queued — they leave the+ * queue only when a phone snapshot reflects them, never on send alone.+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != WearNotesProtocol.SNAPSHOT_PATH) return+                val snapshot = runCatching {+                    WearNotesProtocol.json.decodeFromString<WearNotesSnapshot>(body.decodeToString())+                }.getOrNull()+                if (snapshot == null) {+                    Log.status(TAG, "ignoring malformed snapshot")+                    return+                }+                WearNotesStore.get(context).setSnapshot(snapshot)+            }+        }+        val created = WearLinkNode(context, WearNotesProtocol.CAPABILITY, listener)+        scope.launch {+            var wasConnected = false+            created.state.collect { linkState ->+                val connected = linkState is WearLinkState.Connected+                if (connected && !wasConnected) {+                    flushPending(context)+                    publishWatchState(context)+                }+                wasConnected = connected+            }+        }+        created.start()+        return created+    }++    /** Sends every pending op; ops stay queued until a snapshot reflects them. */+    fun flushPending(context: Context) {+        val store = WearNotesStore.get(context)+        val ops = store.pendingOps.value+        if (ops.isEmpty()) return+        scope.launch {+            val link = get(context)+            for (op in ops) {+                link.sendMessage(+                    WearNotesProtocol.OP_PATH,+                    WearNotesProtocol.json.encodeToString(op).encodeToByteArray(),+                    requireAck = true,+                )+            }+        }+    }++    fun publishWatchState(context: Context) {+        val store = WearNotesStore.get(context)+        val state = WearWatchState(+            appliedGeneratedAtMillis = store.appliedGeneratedAtMillis,+            noteCount = store.notes.value.size,+            pendingOps = store.pendingOps.value.size,+        )+        scope.launch {+            get(context).putData(+                WearNotesProtocol.WATCH_STATE_PATH,+                WearNotesProtocol.json.encodeToString(state).encodeToByteArray(),+            )+        }+    }++    /** Ask the phone for a fresh snapshot; false when no session is live. */+    suspend fun requestSync(context: Context): Boolean =+        get(context).sendMessage(WearNotesProtocol.REQUEST_SYNC_PATH, ByteArray(0))+}
notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearMainActivity.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearMainActivity.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..1266f646c7--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearMainActivity.kt@@ -0,0 +1,57 @@+package com.vayunmathur.notes.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.notes.wear.data.WearNotesStore+import com.vayunmathur.notes.wear.sync.WearLinkBridge++/**+ * Watch notes entry: recent list, note view and quick-note creation,+ * rendered only from the locally stored snapshot so it works standalone+ * (phone absent, cold start). Watch-originated changes queue in the+ * store and flow back over WearLink; nothing here claims a phone write.+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        val store = WearNotesStore.get(this)+        WearLinkBridge.get(this)+        WearLinkBridge.publishWatchState(this)+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.NoteList) }+                when (val current = route) {+                    WearRoute.NoteList -> WearNotesListScreen(+                        store = store,+                        onOpenNote = { route = WearRoute.NoteView(it) },+                        onCreateNote = { route = WearRoute.CreateNote },+                    )+                    is WearRoute.NoteView -> WearNoteScreen(+                        store = store,+                        syncId = current.syncId,+                        onEdit = { route = WearRoute.EditNote(it) },+                        onBack = { route = WearRoute.NoteList },+                    )+                    WearRoute.CreateNote -> WearNoteEditorScreen(+                        store = store,+                        syncId = null,+                        onDone = { route = WearRoute.NoteList },+                    )+                    is WearRoute.EditNote -> WearNoteEditorScreen(+                        store = store,+                        syncId = current.syncId,+                        onDone = { route = WearRoute.NoteView(current.syncId) },+                    )+                }+            }+        }+    }+}
notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteEditorScreen.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteEditorScreen.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteEditorScreen.ktnew file mode 100644index 0000000000..114b88994c--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteEditorScreen.kt@@ -0,0 +1,102 @@+package com.vayunmathur.notes.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.notes.wear.R+import com.vayunmathur.notes.wear.data.WearNotesStore++/**+ * Quick-note create (syncId = null) and text-only edit. The text fields use+ * the watch system IME, whose microphone is the dictation path — speaking+ * the title/body is the intended way to fill them on a round screen. Save+ * queues the op locally; it is pending until the phone reflects it.+ */+@Composable+fun WearNoteEditorScreen(+    store: WearNotesStore,+    syncId: String?,+    onDone: () -> Unit,+) {+    val notes by store.notes.collectAsState()+    val existing = syncId?.let { id -> notes.firstOrNull { it.syncId == id } }+    var title by remember(syncId) { mutableStateOf(existing?.title.orEmpty()) }+    var body by remember(syncId) { mutableStateOf(existing?.body.orEmpty()) }+    val listState = rememberScalingLazyListState()+    val textStyle = TextStyle(color = MaterialTheme.colors.onSurface)++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.wear_title_hint),+                style = MaterialTheme.typography.caption1,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            BasicTextField(+                value = title,+                onValueChange = { title = it },+                textStyle = textStyle,+                cursorBrush = SolidColor(MaterialTheme.colors.onSurface),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Text(+                stringResource(R.string.wear_body_hint),+                style = MaterialTheme.typography.caption1,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            BasicTextField(+                value = body,+                onValueChange = { body = it },+                textStyle = textStyle,+                cursorBrush = SolidColor(MaterialTheme.colors.onSurface),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Chip(+                onClick = {+                    if (syncId == null) {+                        store.createNote(title.trim(), body.trim())+                    } else {+                        store.editNote(syncId, title.trim(), body.trim())+                    }+                    onDone()+                },+                label = { Text(stringResource(R.string.wear_save), maxLines = 1) },+                colors = ChipDefaults.primaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onDone,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteScreen.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteScreen.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteScreen.ktnew file mode 100644index 0000000000..8a09346519--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNoteScreen.kt@@ -0,0 +1,115 @@+package com.vayunmathur.notes.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.notes.wear.R+import com.vayunmathur.notes.wear.data.WearNotesStore++/**+ * One note: title plus its (bounded) full text. Edit is offered only for+ * text-only notes; delete for every note. Both queue an op for the phone —+ * this screen never claims the phone has applied anything.+ */+@Composable+fun WearNoteScreen(+    store: WearNotesStore,+    syncId: String,+    onEdit: (String) -> Unit,+    onBack: () -> Unit,+) {+    val notes by store.notes.collectAsState()+    val note = notes.firstOrNull { it.syncId == syncId }+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        if (note == null) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            item {+                Text(+                    note.title.ifBlank { "Untitled" },+                    style = MaterialTheme.typography.title3,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+            if (note.body.isNotBlank()) {+                item {+                    Text(+                        note.body,+                        style = MaterialTheme.typography.body2,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            if (note.bodyTruncated) {+                item {+                    Text(+                        stringResource(R.string.wear_body_truncated),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            if (!note.textOnly) {+                item {+                    Text(+                        stringResource(R.string.wear_read_only_rich),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            } else {+                item {+                    Chip(+                        onClick = { onEdit(note.syncId) },+                        label = { Text(stringResource(R.string.wear_edit), maxLines = 1) },+                        colors = ChipDefaults.secondaryChipColors(),+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                    )+                }+            }+            item {+                Chip(+                    onClick = {+                        store.deleteNote(note.syncId)+                        onBack()+                    },+                    label = { Text(stringResource(R.string.wear_delete), maxLines = 1) },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNotesListScreen.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNotesListScreen.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNotesListScreen.ktnew file mode 100644index 0000000000..ad50a02499--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearNotesListScreen.kt@@ -0,0 +1,117 @@+package com.vayunmathur.notes.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.notes.wear.R+import com.vayunmathur.notes.wear.data.WearNotesStore+import com.vayunmathur.notes.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/** Round-screen recent-notes list: most recently updated first, from the local store (offline-safe). */+@Composable+fun WearNotesListScreen(+    store: WearNotesStore,+    onOpenNote: (String) -> Unit,+    onCreateNote: () -> Unit,+) {+    val notes by store.notes.collectAsState()+    val pending by store.pendingOps.collectAsState()+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    var syncNote by remember { mutableStateOf<String?>(null) }+    val requestedText = stringResource(R.string.wear_sync_requested)+    val noPhoneText = stringResource(R.string.wear_no_phone)+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.app_name),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (pending.isNotEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_pending, pending.size),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        syncNote?.let { note ->+            item {+                Text(+                    note,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        item {+            Chip(+                onClick = onCreateNote,+                label = { Text(stringResource(R.string.wear_new_note), maxLines = 1) },+                colors = ChipDefaults.primaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        if (notes.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(notes, key = { it.syncId }) { note ->+                Chip(+                    onClick = { onOpenNote(note.syncId) },+                    label = { Text(note.title.ifBlank { "Untitled" }, maxLines = 1) },+                    secondaryLabel = {+                        Text(note.body.replace('\n', ' ').take(60), maxLines = 1)+                    },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        item {+            Chip(+                onClick = {+                    scope.launch {+                        syncNote = if (WearLinkBridge.requestSync(context)) requestedText else noPhoneText+                    }+                },+                label = { Text(stringResource(R.string.wear_request_sync), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearRoute.kt
diff --git a/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearRoute.kt b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..e28dd73168--- /dev/null+++ b/notes-wear/src/main/java/com/vayunmathur/notes/wear/ui/WearRoute.kt@@ -0,0 +1,16 @@+package com.vayunmathur.notes.wear.ui++/** Watch navigation destinations: detail/editor routes carry the note syncId, never selection state. */+sealed interface WearRoute {+    /** Recent-notes list. */+    data object NoteList : WearRoute++    /** One note's view, identified by its stable syncId. */+    data class NoteView(val syncId: String) : WearRoute++    /** Quick-note creation (dictation-friendly title/body entry). */+    data object CreateNote : WearRoute++    /** Edit of one text-only note, identified by its stable syncId. */+    data class EditNote(val syncId: String) : WearRoute+}
notes-wear/src/main/res/values/colors.xml
diff --git a/notes-wear/src/main/res/values/colors.xml b/notes-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..bfc7025d71--- /dev/null+++ b/notes-wear/src/main/res/values/colors.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Background for the generated adaptive launcher icon (see LauncherIconGen). -->+<resources>+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
notes-wear/src/main/res/values/strings.xml
diff --git a/notes-wear/src/main/res/values/strings.xml b/notes-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..6806db4da4--- /dev/null+++ b/notes-wear/src/main/res/values/strings.xml@@ -0,0 +1,20 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Notes</string>+    <string name="wear_empty">No notes synced yet. Open Notes on your phone to sync this watch.</string>+    <string name="wear_new_note">New note</string>+    <string name="wear_request_sync">Sync now</string>+    <string name="wear_sync_requested">Asked your phone for a fresh copy</string>+    <string name="wear_no_phone">Phone not reachable — showing the last synced copy</string>+    <string name="wear_truncated">Showing your most recent notes; the rest stays on your phone</string>+    <string name="wear_body_truncated">… (full text on your phone)</string>+    <string name="wear_read_only_rich">Contains drawings or images from your phone — view only here. You can still delete it.</string>+    <string name="wear_edit">Edit</string>+    <string name="wear_delete">Delete</string>+    <string name="wear_save">Save</string>+    <string name="wear_back">Back</string>+    <string name="wear_title_hint">Title (tap the mic to dictate)</string>+    <string name="wear_body_hint">Note text (tap the mic to dictate)</string>+    <string name="wear_pending">Waiting for your phone to confirm %1$d change(s)</string>+    <string name="wear_deleted_note">Deleted on this watch — waiting for your phone</string>+</resources>
notes-wear/src/test/java/com/vayunmathur/notes/wear/domain/WearNotesProtocolTest.kt
diff --git a/notes-wear/src/test/java/com/vayunmathur/notes/wear/domain/WearNotesProtocolTest.kt b/notes-wear/src/test/java/com/vayunmathur/notes/wear/domain/WearNotesProtocolTest.ktnew file mode 100644index 0000000000..53bb25870e--- /dev/null+++ b/notes-wear/src/test/java/com/vayunmathur/notes/wear/domain/WearNotesProtocolTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.notes.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearNotesProtocolTest {++    private fun note(+        syncId: String,+        updatedAt: Long,+        title: String = "Note $syncId",+        body: String = "Body $syncId",+        deleted: Boolean = false,+    ) = WearNote(syncId = syncId, title = title, body = body, updatedAt = updatedAt, deleted = deleted)++    @Test+    fun goldenSnapshotJson() {+        val snapshot = WearNotesSnapshot(+            generatedAtMillis = 1_000L,+            notes = listOf(note("abc", 900L, title = "Shopping", body = "Milk")),+        )+        assertEquals(+            """{"generatedAtMillis":1000,"notes":[{"syncId":"abc","title":"Shopping",""" ++                """"body":"Milk","updatedAt":900}]}""",+            WearNotesProtocol.json.encodeToString(snapshot),+        )+    }++    @Test+    fun goldenOpJson() {+        val op = WearNoteOp(WearOpKind.UPSERT, note("abc", 900L, title = "Shopping", body = "Milk"))+        assertEquals(+            """{"kind":"UPSERT","note":{"syncId":"abc","title":"Shopping","body":"Milk","updatedAt":900}}""",+            WearNotesProtocol.json.encodeToString(op),+        )+    }++    @Test+    fun snapshotAndOpRoundTrip() {+        val snapshot = WearNotesSnapshot(9L, listOf(note("a", 1L), note("b", 2L)), truncated = true)+        assertEquals(+            snapshot,+            WearNotesProtocol.json.decodeFromString<WearNotesSnapshot>(+                WearNotesProtocol.json.encodeToString(snapshot),+            ),+        )+        val op = WearNoteOp(WearOpKind.DELETE, note("a", 3L, deleted = true))+        assertEquals(+            op,+            WearNotesProtocol.json.decodeFromString<WearNoteOp>(+                WearNotesProtocol.json.encodeToString(op),+            ),+        )+    }++    @Test+    fun buildKeepsMostRecentAndDropsDeleted() {+        val snapshot = buildWearSnapshot(+            candidates = listOf(note("old", 100L), note("new", 300L), note("gone", 400L, deleted = true)),+            generatedAtMillis = 500L,+        )+        assertEquals(listOf("new", "old"), snapshot.notes.map { it.syncId })+        assertFalse(snapshot.truncated)+    }++    @Test+    fun buildCapsCountFieldsAndBytes() {+        val candidates = (1..(WearNotesProtocol.MAX_NOTES + 20)).map {+            note("n$it", it.toLong(), title = "t".repeat(300), body = "b".repeat(5_000))+        }+        val snapshot = buildWearSnapshot(candidates, 0L)+        assertTrue(snapshot.notes.size <= WearNotesProtocol.MAX_NOTES)+        assertTrue(snapshot.truncated)+        assertTrue(snapshot.notes.all {+            it.title.length == WearNotesProtocol.MAX_TITLE_CHARS &&+                it.body.length == WearNotesProtocol.MAX_BODY_CHARS && it.bodyTruncated+        })+        val bytes = WearNotesProtocol.json.encodeToString(snapshot).encodeToByteArray().size+        assertTrue(bytes <= WearNotesProtocol.MAX_JSON_BYTES, "snapshot $bytes bytes over cap")+        // Most recent survives the caps.+        assertEquals("n${WearNotesProtocol.MAX_NOTES + 20}", snapshot.notes.first().syncId)+    }++    @Test+    fun lwwNewerWinsOlderLoses() {+        val incumbent = note("a", 200L, title = "Phone")+        assertTrue(wearNoteWins(note("a", 300L, title = "Watch"), incumbent))+        assertFalse(wearNoteWins(note("a", 100L, title = "Watch"), incumbent))+        assertFalse(wearNoteWins(incumbent, incumbent))+    }++    @Test+    fun lwwTieBreaksTombstoneThenLargerText() {+        val live = note("a", 200L, title = "Same", body = "same")+        assertTrue(wearNoteWins(live.copy(deleted = true), live))+        assertFalse(wearNoteWins(live, live.copy(deleted = true)))+        assertTrue(wearNoteWins(live.copy(title = "Zebra"), live))+        assertTrue(wearNoteWins(live.copy(body = "zebra"), live))+    }++    @Test+    fun mergeKeepsWinningPendingOpAndHidesPendingDelete() {+        val snapshot = WearNotesSnapshot(+            1_000L,+            listOf(note("a", 100L, title = "Phone"), note("b", 100L)),+        )+        val edited = note("a", 200L, title = "Watch edit")+        val merged = mergeWearSnapshot(+            snapshot,+            listOf(+                WearNoteOp(WearOpKind.UPSERT, edited),+                WearNoteOp(WearOpKind.DELETE, note("b", 200L, deleted = true)),+            ),+        )+        assertEquals(listOf(edited), merged)+    }++    @Test+    fun mergeDropsPendingOpThatLosesToSnapshot() {+        val phone = note("a", 300L, title = "Phone newer")+        val snapshot = WearNotesSnapshot(1_000L, listOf(phone))+        val stale = note("a", 200L, title = "Watch stale")+        assertEquals(+            listOf(phone),+            mergeWearSnapshot(snapshot, listOf(WearNoteOp(WearOpKind.UPSERT, stale))),+        )+        // Reflected: the stale op is safe to drop; a winning op is not.+        assertEquals(+            listOf(WearNoteOp(WearOpKind.UPSERT, stale)),+            reflectedOps(snapshot, listOf(WearNoteOp(WearOpKind.UPSERT, stale))),+        )+        assertEquals(+            emptyList(),+            reflectedOps(snapshot, listOf(WearNoteOp(WearOpKind.UPSERT, note("a", 400L)))),+        )+        // A delete is reflected once the note is absent from the live snapshot.+        assertEquals(+            1,+            reflectedOps(+                WearNotesSnapshot(1_000L, emptyList()),+                listOf(WearNoteOp(WearOpKind.DELETE, note("a", 200L, deleted = true))),+            ).size,+        )+    }+}
notes/build.gradle.kts
diff --git a/notes/build.gradle.kts b/notes/build.gradle.ktsindex 43f621f57e..eae81a2d52 100644--- a/notes/build.gradle.kts+++ b/notes/build.gradle.kts@@ -22,4 +22,9 @@ dependencies {     implementation(project(":library:room"))     implementation(project(":library:ink"))     implementation(project(":li

Diff truncated.