Repository navigation
fix(app): pendant ring custody v1 — advance only after durable storage, never evict pending audio - #20462
Conversation
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Gate ring reclamation on validated incarnation-scoped WAL proofs and preserve pending recordings instead of evicting them under pressure. Failure-Class: none Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…gged ring timestamps The pending-WAL count now only warns. On legacy firmware the pendant has already freed live audio, so refusing it for count lost it after about two hours of 10-second chunks. Only the free-disk reserve refuses admission. Ring record timestamps with bit 31 set (the custody firmware's boot-uptime flag) are read as no usable time instead of a 2038+ epoch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ract Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
33 issues found and verified against the latest diff
Confidence score: 2/5
PENDANT_RING_CUSTODY.mdallows an unscoped stale sequence to advance a reinitialized ring, conflicting with the rule that replay requiresCAP_RING_ID. Limit replay to a matching persisted ring ID.local_wal_sync.dartdrops pendant frames at the 2,000-frame cap even when disk admission succeeds. Drop frames only after an actual storage failure.pendant_ring_custody.darttreatswriteSeq == 0as no bound, so it can advance past the device’s reported end and release uncustodied records. Apply the cap when the reported value is zero too.omi_connection.dartlets a custody checkpoint I/O failure throw fromconnect()after the BLE link is up, preventing connection setup from completing. Catch and log probe failures, then continue connecting.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="app/test/services/capture/capture_transcript_coverage_test.dart">
<violation number="1" location="app/test/services/capture/capture_transcript_coverage_test.dart:293">
P2: This split omits the uncovered `[60,70)`, `[140,150)`, and `[150,160)` chunks, and marks `[70,80)` uncovered even though it overlaps transcript text at 78–80. Expect offsets `[60, 140, 150]` and update the corresponding covered-offset assertions; these incorrect expectations make the replay tests fail.</violation>
</file>
<file name="app/test/unit/pendant_custody_main_red_test.dart">
<violation number="1" location="app/test/unit/pendant_custody_main_red_test.dart:162">
P2: This assertion only orders a generic write before the audio subscription; it never orders `CMD_CUSTODY_ENABLE` against that subscription, so a regression that subscribes before opting in still passes. Record the enable command in the shared `ops` timeline and assert that entry precedes `audioSubAt`.</violation>
</file>
<file name="app/test/unit/native_ble_transport_resync_test.dart">
<violation number="1" location="app/test/unit/native_ble_transport_resync_test.dart:483">
P2: The listener is registered after `onDeviceReady`, so the ready handler arms no liveness watch and the gate-held subscription never arms one. Register the stream before signaling ready so the 8-second wait actually covers repeated watches.</violation>
</file>
<file name="app/lib/services/wals/PENDANT_RING_CUSTODY.md">
<violation number="1" location="app/lib/services/wals/PENDANT_RING_CUSTODY.md:23">
P2: CAP_APP_ACK_RECLAIM is described as preventing all firmware-initiated reclamation, but §3 retains overwrite-oldest, which discards ring audio when full. Clarify that capacity-driven overwrite remains possible so this capability is not mistaken for a no-loss guarantee.</violation>
<violation number="2" location="app/lib/services/wals/PENDANT_RING_CUSTODY.md:91">
P1: This reconnect rule conflicts with §1c, which forbids replay without CAP_RING_ID; an unscoped stale sequence can advance a reinitialized ring. Limit replay to a matching persisted ring ID and keep legacy advancement connection-local.</violation>
</file>
<file name="app/test/unit/ring_custody_download_test.dart">
<violation number="1" location="app/test/unit/ring_custody_download_test.dart:253">
P2: The 300 ms delay does not guarantee the queued records have been persisted and incrementally advanced, so this test can fail on slower CI runs even when the implementation is correct. Wait for a deterministic signal that a mid-transfer advance occurred before capturing the count.</violation>
</file>
<file name="app/test/unit/ring_storage_sync_no_advance_test.dart">
<violation number="1" location="app/test/unit/ring_storage_sync_no_advance_test.dart:211">
P2: This fixed delay does not guarantee that the sync listener is ready before the test emits notifications; a missed emission leaves the test waiting for the transfer timeout. Signal readiness from the fake when the read request is issued, then await that signal.</violation>
</file>
<file name="app/lib/services/capture/capture_wedge_monitor.dart">
<violation number="1" location="app/lib/services/capture/capture_wedge_monitor.dart:278">
P2: Disk-reserve and unknown-space blocks are also labeled as a count-cap policy, although the 720-WAL threshold is warning-only. Derive this label from `reason` so telemetry does not misattribute storage failures.</violation>
</file>
<file name="app/lib/services/wals/local_wal_sync.dart">
<violation number="1" location="app/lib/services/wals/local_wal_sync.dart:500">
P2: This admits duplicate `wal.id` values, but `_syncAll` deduplicates later batches by `wal.id`; colliding WALs in different session or location groups can leave one unattempted for the entire sync run. Track uploads with a collision-safe identity, such as WAL ID plus file path.</violation>
<violation number="2" location="app/lib/services/wals/local_wal_sync.dart:1767">
P1: At `count_cap`, this drops pendant frames once the buffer reaches 2,000, even when disk admission succeeds; the 720-WAL threshold is warning-only. Gate frame dropping on an actual storage failure, not any `retentionRisk`.</violation>
</file>
<file name="app/lib/services/wals/sdcard_wal_sync.dart">
<violation number="1" location="app/lib/services/wals/sdcard_wal_sync.dart:796">
P2: The `chunksDownloaded == 0` return bypasses this check, so an incomplete read with no chunks makes `_syncWal` report success and `syncWal` marks the source WAL synced without a durable local copy. Reject incomplete reads before the zero-chunk return.</violation>
</file>
<file name="app/lib/services/wals/storage_sync.dart">
<violation number="1" location="app/lib/services/wals/storage_sync.dart:643">
P2: A file the firmware reports as empty (status byte 0x04 completes the transfer with `endReached = true` and no bytes parsed) now returns false and stays `WalStatus.miss` forever. `_syncAll` breaks its loop on a failed file, so a single empty file on the device stalls every subsequent sync and is never deleted (deletion only happens after a complete sync). The old code returned `transferComplete` (true when offset already reached `storageTotalBytes`), which marked the empty file synced and deleted it. Restore the empty-file completion path while keeping the new strict checks for real transfers.</violation>
<violation number="2" location="app/lib/services/wals/storage_sync.dart:730">
P2: A registration failure after `_flushToDisk` leaves the flushed audio file unindexed; retries can accumulate more `_uN` files that consume disk but cannot be recovered as WALs. Clean up or otherwise track the flushed file when registration fails.</violation>
</file>
<file name="app/lib/services/wals/pendant_ring_custody.dart">
<violation number="1" location="app/lib/services/wals/pendant_ring_custody.dart:574">
P1: An INFO `writeSeq` of 0 disables the bound, so a positive retained frontier can produce an ADVANCE beyond the device's reported end and release uncustodied records. Apply the cap even when it is zero.</violation>
</file>
<file name="app/lib/services/devices/connectors/omi_connection.dart">
<violation number="1" location="app/lib/services/devices/connectors/omi_connection.dart:141">
P2: The future returned by `whenComplete` preserves probe errors, but this code discards it, producing an unhandled asynchronous error whenever custody replay or checkpoint persistence fails. Handle the rejection in the cleanup continuation while returning the original future to its callers.</violation>
<violation number="2" location="app/lib/services/devices/connectors/omi_connection.dart:314">
P1: A custody checkpoint I/O failure now makes `connect()` throw after the BLE link has already connected, preventing the connection setup from completing. Catch and log probe failures here, then continue with the connection and time sync.</violation>
</file>
<file name="app/test/unit/omi_ring_custody_test.dart">
<violation number="1" location="app/test/unit/omi_ring_custody_test.dart:139">
P2: `_settle()` is an arbitrary 50 ms delay, not completion of the probe or checkpoint work, so slow I/O can leave these assertions racing unfinished setup. Await the relevant operation or a condition with a timeout instead.</violation>
<violation number="2" location="app/test/unit/omi_ring_custody_test.dart:272">
P2: This does not test the stated rejection behavior: the INFO probe can replay the seeded frontier via `0x15` before audio attach sends the rejected `0x14`, while the assertion checks only `0x12`. Check `cmdAdvanceId` in this scenario or rename the test if replay is intended.</violation>
</file>
<file name="app/lib/providers/device_provider.dart">
<violation number="1" location="app/lib/providers/device_provider.dart:1030">
P3: `_coherentRingStatus` consults `info` only when `status` is null (or for `freeBytes` when it reads exactly 0), so a stale status snapshot keeps `status.unreadPackets` as the auto-sync decision. In `_checkAndStartAutoSync`, `onOfflineDataDetected` is then skipped even when the live `NOTIFY_INFO` reports unread packets — the info-based detection this change adds only ever engages when the status read outright fails. The merge is also internally inconsistent: `freeBytes` is substituted from `info` when the snapshot says 0, but `usedBytes`/`unreadPackets` are never cross-checked, so the storage card can show used + free exceeding ring capacity when the snapshot and the pushed info disagree. Prefer the live `info.unreadPackets`/derived bytes when they disagree with the snapshot, or document why the cached snapshot is authoritative for unread counts.</violation>
</file>
<file name="app/changelog/unreleased/20261003-pendant-ring-custody.json">
<violation number="1" location="app/changelog/unreleased/20261003-pendant-ring-custody.json:2">
P2: “Before any device-side advance” overstates the guarantee: legacy firmware can autonomously reclaim ring audio before the phone has durably stored it. Describe the protection for supported firmware and qualify the legacy limitation.</violation>
<violation number="2" location="app/changelog/unreleased/20261003-pendant-ring-custody.json:2">
P3: This fragment describes internal implementation (WAL fsync/indexing order, capability gating, eviction policy) instead of a user-visible outcome. Per `app/changelog/README.md` style rules, fragments must say what the user can now do or what got better, impact first, with no jargon. Rewrite it around the user-facing result, e.g. recordings being kept safe on the phone until the pendant has them durably.</violation>
</file>
<file name="app/test/unit/sdcard_custody_sync_test.dart">
<violation number="1" location="app/test/unit/sdcard_custody_sync_test.dart:176">
P2: This test does not verify that admission precedes chunk-file creation: its event fields are never asserted, and `firstWriteEvent` tracks the BLE read request instead. Add a file-write event or seam and assert admission occurs before it; the empty-directory check only verifies the final state after refusal.</violation>
</file>
<file name="app/test/services/capture/capture_wedge_monitor_test.dart">
<violation number="1" location="app/test/services/capture/capture_wedge_monitor_test.dart:626">
P3: The new `block_reason` telemetry is not asserted here; check that it equals `count_cap` so regressions dropping or changing this field are caught.</violation>
</file>
<file name="app/lib/services/devices/transports/native_ble_transport.dart">
<violation number="1" location="app/lib/services/devices/transports/native_ble_transport.dart:208">
P2: The `beforeAudioResubscribe` gate is awaited outside the `subscriptionTimeout` that bounds the actual `subscribeCharacteristic` call, and `_pendingSubscriptions[key] = generation` was already set before the gate. If the gate stalls, the audio CCCD subscribe is blocked without any timeout: later `_subscribeCharacteristic` calls for that key short-circuit on `_pendingSubscriptions[key] == generation`, and `_onAudioLivenessTimeout` suppresses the silence retry whenever a pending audio subscription exists, so nothing recovers the subscription until `_subscriptionGeneration` is bumped (disconnect). The current gate (Omi custody probe + `_enableAfterProbe`, up to ~10–15 s of reads/ACK timeouts) also delays the first live-audio subscribe and every reconnect audio resubscribe by the full probe duration. Bound the gate await with a timeout and fall back to subscribing without waiting (custody ordering is still enforced by the epoch/ring-id checks on frames).</violation>
<violation number="2" location="app/lib/services/devices/transports/native_ble_transport.dart:396">
P2: This delayed pass can subscribe audio after its reconnect has been disconnected: disconnect bumps `_subscriptionGeneration`, but this continuation starts subscriptions without checking the originating generation. Capture the generation before `Future.wait` and skip the pass if it changed.</violation>
</file>
<file name="app/test/unit/legacy_storage_limitless_seam_test.dart">
<violation number="1" location="app/test/unit/legacy_storage_limitless_seam_test.dart:226">
P2: These final-state assertions do not prove deletion or ACK happened after durable registration; a regression that releases the device copy early would still pass. Record persistence and release actions in a shared ordered event log, then assert the persistence check precedes each release.</violation>
<violation number="2" location="app/test/unit/legacy_storage_limitless_seam_test.dart:242">
P2: This sleep does not guarantee `addExternalWal` has reached `addGate` before `setDevice`, so a slow test can switch during transfer and pass without exercising the persistence race. Expose and await a `persistenceStarted` completer from the fake instead of relying on elapsed time.</violation>
</file>
<file name="app/lib/services/wals/ring_storage_sync.dart">
<violation number="1" location="app/lib/services/wals/ring_storage_sync.dart:504">
P2: This branch certifies a record as durable despite writing no WAL. `parseAudioPayload` also returns no frames for malformed length prefixes, so the ring can discard the only copy of that audio; distinguish verified padding-only records from parse failures and leave malformed records unadvanced.</violation>
</file>
<file name="app/test/unit/local_wal_live_custody_test.dart">
<violation number="1" location="app/test/unit/local_wal_live_custody_test.dart:114">
P2: This fixed sleep does not synchronize with the asynchronous custody mark task, so slow filesystem or scheduler runs can assert or tear down before it completes. Wait for an explicit completion signal or a bounded condition instead.</violation>
</file>
<file name="app/lib/services/wals/flash_page_wal_sync.dart">
<violation number="1" location="app/lib/services/wals/flash_page_wal_sync.dart:478">
P2: This marks the page acknowledged even when the transport write failed: `acknowledgeProcessedData` catches the exception and returns normally, so `reachedEnd` can report success without the device receiving the release command. Return ACK success from the connection method and update this index only on success.</violation>
<violation number="2" location="app/lib/services/wals/flash_page_wal_sync.dart:759">
P2: A registration failure after the file write leaves an unindexed audio file behind; retries create more copies and can consume the disk reserve, eventually blocking downloads. Delete the file and roll back any uncommitted WAL when registration fails.</violation>
</file>
<file name="app/lib/services/wals/wal.dart">
<violation number="1" location="app/lib/services/wals/wal.dart:432">
P2: `liveConnectionEpoch` is not written to the WAL index JSON (and not in WalFileManager's validation allow-list, which only gained `live_ring_id`/`live_ordinal_start`/`live_ordinal_end`), so after an app restart every loaded WAL has a null epoch. `LocalWalSyncImpl._reportDurableLiveWal` then returns early (`epoch == null`), so audio that was flushed durably just before a restart is never folded into the custody checkpoint's live/ring ranges: the next sync re-downloads those records as new chunks and the live-advance path for them never runs. Persist `live_connection_epoch` alongside the other three live fields so post-restart evidence reporting is possible, or document that restart intentionally re-downloads pre-restart audio.</violation>
</file>
<file name="app/lib/services/devices/connectors/device_connection.dart">
<violation number="1" location="app/lib/services/devices/connectors/device_connection.dart:239">
P3: `disconnect()` now calls `onPhysicalConnectionLost()` unconditionally, even when the physical link was never established or already dropped. The transport listener already fires this hook on the disconnected transition, so a transport-led disconnect followed by an app `disconnect()` (or a failed `connect()` cleanup) invokes `onPhysicalConnectionLost()` twice or spuriously. Subclasses key side effects off the hook — OmiDeviceConnection ends the custody session and re-allocates `_physicalReady` every time. Guard the call on the previous connection state so the hook fires only for a real established-to-down transition.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| - On reconnect, before a new READ, the app re-sends `ADVANCE(last_durable_seq)` from persisted state, in | ||
| case the previous ADVANCE was lost. |
There was a problem hiding this comment.
P1: This reconnect rule conflicts with §1c, which forbids replay without CAP_RING_ID; an unscoped stale sequence can advance a reinitialized ring. Limit replay to a matching persisted ring ID and keep legacy advancement connection-local.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/services/wals/PENDANT_RING_CUSTODY.md, line 91:
<comment>This reconnect rule conflicts with §1c, which forbids replay without CAP_RING_ID; an unscoped stale sequence can advance a reinitialized ring. Limit replay to a matching persisted ring ID and keep legacy advancement connection-local.</comment>
<file context>
@@ -0,0 +1,128 @@
+ and flushed with fsync (`flush: true` or equivalent), with the WAL index entry for that audio persisted.
+- The app may advance incrementally during a transfer, after each durably flushed chunk. That bounds the
+ sync speed by the phone's flush cadence, not by RAM.
+- On reconnect, before a new READ, the app re-sends `ADVANCE(last_durable_seq)` from persisted state, in
+ case the previous ADVANCE was lost.
+- **Legacy firmware (caps = 0):** the app runs the same code. The firmware already self-freed, so
</file context>
| - On reconnect, before a new READ, the app re-sends `ADVANCE(last_durable_seq)` from persisted state, in | |
| case the previous ADVANCE was lost. | |
| - On reconnect with `CAP_RING_ID`, after confirming INFO's `ring_id` matches persisted state and before a new READ, the app re-sends `ADVANCE(last_durable_seq)`; without `CAP_RING_ID`, it advances only within the connection after the READ that delivered those records. |
| int? liveEpoch; | ||
| int? liveRingId; | ||
| if (_isPendantFrame(frame)) { | ||
| if ((_retentionRisk != null || _pendantBlockedByStorage) && |
There was a problem hiding this comment.
P1: At count_cap, this drops pendant frames once the buffer reaches 2,000, even when disk admission succeeds; the 720-WAL threshold is warning-only. Gate frame dropping on an actual storage failure, not any retentionRisk.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/services/wals/local_wal_sync.dart, line 1767:
<comment>At `count_cap`, this drops pendant frames once the buffer reaches 2,000, even when disk admission succeeds; the 720-WAL threshold is warning-only. Gate frame dropping on an actual storage failure, not any `retentionRisk`.</comment>
<file context>
@@ -1281,18 +1760,85 @@ class LocalWalSyncImpl implements LocalWalSync {
+ int? liveEpoch;
+ int? liveRingId;
+ if (_isPendantFrame(frame)) {
+ if ((_retentionRisk != null || _pendantBlockedByStorage) &&
+ _countPendantBuffered() >= _maxPendantBufferedFrames) {
+ _pendantDroppedWhileBlocked++;
</file context>
| if (state == null || state.incarnationInvalid) return null; | ||
| var target = state.durableFrontier; | ||
| final cap = state.checkpoint.reportedWriteSeq; | ||
| if (cap > 0 && target > cap) target = cap; |
There was a problem hiding this comment.
P1: An INFO writeSeq of 0 disables the bound, so a positive retained frontier can produce an ADVANCE beyond the device's reported end and release uncustodied records. Apply the cap even when it is zero.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/services/wals/pendant_ring_custody.dart, line 574:
<comment>An INFO `writeSeq` of 0 disables the bound, so a positive retained frontier can produce an ADVANCE beyond the device's reported end and release uncustodied records. Apply the cap even when it is zero.</comment>
<file context>
@@ -0,0 +1,900 @@
+ if (state == null || state.incarnationInvalid) return null;
+ var target = state.durableFrontier;
+ final cap = state.checkpoint.reportedWriteSeq;
+ if (cap > 0 && target > cap) target = cap;
+ if (target <= state.checkpoint.lastAdvancedSeq) return null;
+ return target;
</file context>
| @override | ||
| Future<void> connect({Function(String deviceId, DeviceConnectionState state)? onConnectionStateChanged}) async { | ||
| await super.connect(onConnectionStateChanged: onConnectionStateChanged); | ||
| await retryRingCustodyProbe(); |
There was a problem hiding this comment.
P1: A custody checkpoint I/O failure now makes connect() throw after the BLE link has already connected, preventing the connection setup from completing. Catch and log probe failures here, then continue with the connection and time sync.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/services/devices/connectors/omi_connection.dart, line 314:
<comment>A custody checkpoint I/O failure now makes `connect()` throw after the BLE link has already connected, preventing the connection setup from completing. Catch and log probe failures here, then continue with the connection and time sync.</comment>
<file context>
@@ -22,13 +25,293 @@ class OmiDeviceConnection extends DeviceConnection {
@override
Future<void> connect({Function(String deviceId, DeviceConnectionState state)? onConnectionStateChanged}) async {
await super.connect(onConnectionStateChanged: onConnectionStateChanged);
+ await retryRingCustodyProbe();
await performSyncTime();
</file context>
| await retryRingCustodyProbe(); | |
| try { | |
| await retryRingCustodyProbe(); | |
| } catch (e) { | |
| Logger.debug('OmiDeviceConnection: custody readiness failed: $e'); | |
| } |
| ); | ||
| return (origin, covered); | ||
| final (covered, hole) = await judgedWals(); | ||
| expect(offsetsOf(hole, origin), [70, 150], |
There was a problem hiding this comment.
P2: This split omits the uncovered [60,70), [140,150), and [150,160) chunks, and marks [70,80) uncovered even though it overlaps transcript text at 78–80. Expect offsets [60, 140, 150] and update the corresponding covered-offset assertions; these incorrect expectations make the replay tests fail.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/test/services/capture/capture_transcript_coverage_test.dart, line 293:
<comment>This split omits the uncovered `[60,70)`, `[140,150)`, and `[150,160)` chunks, and marks `[70,80)` uncovered even though it overlaps transcript text at 78–80. Expect offsets `[60, 140, 150]` and update the corresponding covered-offset assertions; these incorrect expectations make the replay tests fail.</comment>
<file context>
@@ -289,13 +289,10 @@ void main() {
- );
- return (origin, covered);
+ final (covered, hole) = await judgedWals();
+ expect(offsetsOf(hole, origin), [70, 150],
+ reason: 'silence-only 10s chunks inside tolerated pauses stay miss on every anchor');
+ return (origin, covered, hole);
</file context>
| try { | ||
| if (isBleAudioCharacteristicUuid(characteristicUuid)) { | ||
| final gate = beforeAudioResubscribe; | ||
| if (gate != null) await gate(characteristicUuid); |
There was a problem hiding this comment.
P2: The beforeAudioResubscribe gate is awaited outside the subscriptionTimeout that bounds the actual subscribeCharacteristic call, and _pendingSubscriptions[key] = generation was already set before the gate. If the gate stalls, the audio CCCD subscribe is blocked without any timeout: later _subscribeCharacteristic calls for that key short-circuit on _pendingSubscriptions[key] == generation, and _onAudioLivenessTimeout suppresses the silence retry whenever a pending audio subscription exists, so nothing recovers the subscription until _subscriptionGeneration is bumped (disconnect). The current gate (Omi custody probe + _enableAfterProbe, up to ~10–15 s of reads/ACK timeouts) also delays the first live-audio subscribe and every reconnect audio resubscribe by the full probe duration. Bound the gate await with a timeout and fall back to subscribing without waiting (custody ordering is still enforced by the epoch/ring-id checks on frames).
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/services/devices/transports/native_ble_transport.dart, line 208:
<comment>The `beforeAudioResubscribe` gate is awaited outside the `subscriptionTimeout` that bounds the actual `subscribeCharacteristic` call, and `_pendingSubscriptions[key] = generation` was already set before the gate. If the gate stalls, the audio CCCD subscribe is blocked without any timeout: later `_subscribeCharacteristic` calls for that key short-circuit on `_pendingSubscriptions[key] == generation`, and `_onAudioLivenessTimeout` suppresses the silence retry whenever a pending audio subscription exists, so nothing recovers the subscription until `_subscriptionGeneration` is bumped (disconnect). The current gate (Omi custody probe + `_enableAfterProbe`, up to ~10–15 s of reads/ACK timeouts) also delays the first live-audio subscribe and every reconnect audio resubscribe by the full probe duration. Bound the gate await with a timeout and fall back to subscribing without waiting (custody ordering is still enforced by the epoch/ring-id checks on frames).</comment>
<file context>
@@ -203,6 +203,11 @@ class NativeBleTransport extends DeviceTransport implements CaptureSubscriptionE
try {
+ if (isBleAudioCharacteristicUuid(characteristicUuid)) {
+ final gate = beforeAudioResubscribe;
+ if (gate != null) await gate(characteristicUuid);
+ if (generation != _subscriptionGeneration) return;
+ }
</file context>
| if (gate != null) await gate(characteristicUuid); | |
| if (gate != null) { | |
| try { | |
| await gate(characteristicUuid).timeout(const Duration(seconds: 5)); | |
| } on TimeoutException { | |
| Logger.debug('[NativeBleTransport] audio resubscribe gate timed out, subscribing without it'); | |
| } | |
| } |
| static RingStatus? _coherentRingStatus(RingStatus? status, RingInfo? info) { | ||
| if (info == null) return status; | ||
| final pkt = info.packetSize > 0 ? info.packetSize : 444; | ||
| final infoUnread = info.unreadPackets; | ||
| final infoFree = (info.capacityPackets - infoUnread).clamp(0, info.capacityPackets) * pkt; | ||
| if (status == null) { | ||
| return RingStatus(usedBytes: infoUnread * pkt, unreadPackets: infoUnread, freeBytes: infoFree, rtcValid: 0); | ||
| } | ||
| final free = status.freeBytes > 0 ? status.freeBytes : infoFree; | ||
| return RingStatus( | ||
| usedBytes: status.usedBytes, unreadPackets: status.unreadPackets, freeBytes: free, rtcValid: status.rtcValid); | ||
| } | ||
|
|
There was a problem hiding this comment.
P3: _coherentRingStatus consults info only when status is null (or for freeBytes when it reads exactly 0), so a stale status snapshot keeps status.unreadPackets as the auto-sync decision. In _checkAndStartAutoSync, onOfflineDataDetected is then skipped even when the live NOTIFY_INFO reports unread packets — the info-based detection this change adds only ever engages when the status read outright fails. The merge is also internally inconsistent: freeBytes is substituted from info when the snapshot says 0, but usedBytes/unreadPackets are never cross-checked, so the storage card can show used + free exceeding ring capacity when the snapshot and the pushed info disagree. Prefer the live info.unreadPackets/derived bytes when they disagree with the snapshot, or document why the cached snapshot is authoritative for unread counts.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/providers/device_provider.dart, line 1030:
<comment>`_coherentRingStatus` consults `info` only when `status` is null (or for `freeBytes` when it reads exactly 0), so a stale status snapshot keeps `status.unreadPackets` as the auto-sync decision. In `_checkAndStartAutoSync`, `onOfflineDataDetected` is then skipped even when the live `NOTIFY_INFO` reports unread packets — the info-based detection this change adds only ever engages when the status read outright fails. The merge is also internally inconsistent: `freeBytes` is substituted from `info` when the snapshot says 0, but `usedBytes`/`unreadPackets` are never cross-checked, so the storage card can show used + free exceeding ring capacity when the snapshot and the pushed info disagree. Prefer the live `info.unreadPackets`/derived bytes when they disagree with the snapshot, or document why the cached snapshot is authoritative for unread counts.</comment>
<file context>
@@ -1022,6 +1027,19 @@ class DeviceProvider extends ChangeNotifier implements IDeviceServiceSubsciption
}
}
+ static RingStatus? _coherentRingStatus(RingStatus? status, RingInfo? info) {
+ if (info == null) return status;
+ final pkt = info.packetSize > 0 ? info.packetSize : 444;
</file context>
| static RingStatus? _coherentRingStatus(RingStatus? status, RingInfo? info) { | |
| if (info == null) return status; | |
| final pkt = info.packetSize > 0 ? info.packetSize : 444; | |
| final infoUnread = info.unreadPackets; | |
| final infoFree = (info.capacityPackets - infoUnread).clamp(0, info.capacityPackets) * pkt; | |
| if (status == null) { | |
| return RingStatus(usedBytes: infoUnread * pkt, unreadPackets: infoUnread, freeBytes: infoFree, rtcValid: 0); | |
| } | |
| final free = status.freeBytes > 0 ? status.freeBytes : infoFree; | |
| return RingStatus( | |
| usedBytes: status.usedBytes, unreadPackets: status.unreadPackets, freeBytes: free, rtcValid: status.rtcValid); | |
| } | |
| static RingStatus? _coherentRingStatus(RingStatus? status, RingInfo? info) { | |
| if (info == null) return status; | |
| final pkt = info.packetSize > 0 ? info.packetSize : 444; | |
| final infoUnread = info.unreadPackets; | |
| final infoFree = (info.capacityPackets - infoUnread).clamp(0, info.capacityPackets) * pkt; | |
| if (status == null) { | |
| return RingStatus(usedBytes: infoUnread * pkt, unreadPackets: infoUnread, freeBytes: infoFree, rtcValid: 0); | |
| } | |
| // The status characteristic is a cached snapshot; prefer the live info | |
| // counts when they disagree so a stale snapshot cannot suppress auto-sync | |
| // or pair used/free values from different moments. | |
| final unread = infoUnread > 0 && infoUnread != status.unreadPackets ? infoUnread : status.unreadPackets; | |
| final used = unread == infoUnread ? infoUnread * pkt : status.usedBytes; | |
| final free = status.freeBytes > 0 ? status.freeBytes : infoFree; | |
| return RingStatus(usedBytes: used, unreadPackets: unread, freeBytes: free, rtcValid: status.rtcValid); | |
| } |
| expect(detected['blocked_wal_count'], 3); | ||
| expect(detected['retained_wal_count'], 720); | ||
| expect(detected['retention_policy'], 'oldest_first_count_cap'); | ||
| expect(detected['retention_policy'], 'admission_count_cap'); |
There was a problem hiding this comment.
P3: The new block_reason telemetry is not asserted here; check that it equals count_cap so regressions dropping or changing this field are caught.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/test/services/capture/capture_wedge_monitor_test.dart, line 626:
<comment>The new `block_reason` telemetry is not asserted here; check that it equals `count_cap` so regressions dropping or changing this field are caught.</comment>
<file context>
@@ -609,21 +609,21 @@ void main() {
+ expect(detected['blocked_wal_count'], 3);
expect(detected['retained_wal_count'], 720);
- expect(detected['retention_policy'], 'oldest_first_count_cap');
+ expect(detected['retention_policy'], 'admission_count_cap');
monitor.dispose();
});
</file context>
| expect(detected['retention_policy'], 'admission_count_cap'); | |
| expect(detected['retention_policy'], 'admission_count_cap'); | |
| expect(detected['block_reason'], 'count_cap'); |
| @@ -0,0 +1,3 @@ | |||
| { | |||
| "change": "Pendant ring custody: WAL writes are fsynced and indexed before any device-side advance, and custody release is capability-gated on new firmware; pending copies are never evicted." | |||
There was a problem hiding this comment.
P3: This fragment describes internal implementation (WAL fsync/indexing order, capability gating, eviction policy) instead of a user-visible outcome. Per app/changelog/README.md style rules, fragments must say what the user can now do or what got better, impact first, with no jargon. Rewrite it around the user-facing result, e.g. recordings being kept safe on the phone until the pendant has them durably.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/changelog/unreleased/20261003-pendant-ring-custody.json, line 2:
<comment>This fragment describes internal implementation (WAL fsync/indexing order, capability gating, eviction policy) instead of a user-visible outcome. Per `app/changelog/README.md` style rules, fragments must say what the user can now do or what got better, impact first, with no jargon. Rewrite it around the user-facing result, e.g. recordings being kept safe on the phone until the pendant has them durably.</comment>
<file context>
@@ -0,0 +1,3 @@
+{
+ "change": "Pendant ring custody: WAL writes are fsynced and indexed before any device-side advance, and custody release is capability-gated on new firmware; pending copies are never evicted."
+}
</file context>
| "change": "Pendant ring custody: WAL writes are fsynced and indexed before any device-side advance, and custody release is capability-gated on new firmware; pending copies are never evicted." | |
| { | |
| "change": "Your recordings now stay safely on your phone until they're confirmed saved on your pendant, so audio is never lost when storage is running low." | |
| } |
| _connectionEpoch++; | ||
| onPhysicalConnectionEstablished(); | ||
| } else if (deviceState == DeviceConnectionState.disconnected) { | ||
| onPhysicalConnectionLost(); |
There was a problem hiding this comment.
P3: disconnect() now calls onPhysicalConnectionLost() unconditionally, even when the physical link was never established or already dropped. The transport listener already fires this hook on the disconnected transition, so a transport-led disconnect followed by an app disconnect() (or a failed connect() cleanup) invokes onPhysicalConnectionLost() twice or spuriously. Subclasses key side effects off the hook — OmiDeviceConnection ends the custody session and re-allocates _physicalReady every time. Guard the call on the previous connection state so the hook fires only for a real established-to-down transition.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/lib/services/devices/connectors/device_connection.dart, line 239:
<comment>`disconnect()` now calls `onPhysicalConnectionLost()` unconditionally, even when the physical link was never established or already dropped. The transport listener already fires this hook on the disconnected transition, so a transport-led disconnect followed by an app `disconnect()` (or a failed `connect()` cleanup) invokes `onPhysicalConnectionLost()` twice or spuriously. Subclasses key side effects off the hook — OmiDeviceConnection ends the custody session and re-allocates `_physicalReady` every time. Guard the call on the previous connection state so the hook fires only for a real established-to-down transition.</comment>
<file context>
@@ -178,12 +217,27 @@ abstract class DeviceConnection {
+ _connectionEpoch++;
+ onPhysicalConnectionEstablished();
+ } else if (deviceState == DeviceConnectionState.disconnected) {
+ onPhysicalConnectionLost();
+ }
_connectionStateChangedCallback?.call(device.id, _connectionState);
</file context>
There was a problem hiding this comment.
💡 Codex Review
omi/app/lib/services/devices/connectors/omi_connection.dart
Lines 879 to 882 in 16e9453
On custody firmware, a successful CMD_RING_CLEAR creates a new ring_id, but this path returns immediately after the ACK and leaves _lastRingInfo plus PendantRingCustody bound to the old incarnation. Since CLEAR does not itself provide a replacement INFO payload, subsequent live marks carry the new ID and observeLiveMark() marks the evidence broken; live records then remain unadvanced for the rest of the connection and can eventually fill or overwrite the ring. Re-read INFO and reset the custody state after a successful clear.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if ((_retentionRisk != null || _pendantBlockedByStorage) && | ||
| _countPendantBuffered() >= _maxPendantBufferedFrames) { |
There was a problem hiding this comment.
Do not turn the count warning into a frame-drop gate
Once the pending WAL count reaches 720, _evaluateRetentionPressure() sets _retentionRisk with reason count_cap even when disk space is plentiful. This condition treats that warning as blocked storage, so after 2,000 buffered frames onFrameCaptured() returns before adding the frame and silently discards subsequent pendant audio. On legacy firmware the pendant may already have reclaimed those live packets, making the loss permanent; only an actual disk-reserve/admission failure should enable this bounded-drop path.
Useful? React with 👍 / 👎.
| Logger.debug("LocalWalSync: WAL id collision on ${wal.id}; admitting both on distinct file paths"); | ||
| } | ||
| if (!_isCurrent(admittedGeneration)) return; | ||
| _wals.add(wal); |
There was a problem hiding this comment.
Give colliding WALs distinct identities
When two external recordings share device and timerStart, this now retains both files but both still have the same Wal.id. Existing consumers require that ID to be unique: sync_page.dart uses it as a sibling Dismissible key, waveform lookup returns the first matching WAL, and the upload drain's attemptedWalIds can exclude the second recording when the collisions fall into different batches. A distinct path is therefore insufficient; assign each retained collision a stable unique identity and use it throughout those consumers.
Useful? React with 👍 / 👎.
| // Send periodic ACK for diagnostic-only pages (no audio accumulated) | ||
| if (pageData != null && !shouldSave && accumulatedFrames.isEmpty && lastProcessedIndex != null) { | ||
| if (pageData != null && !shouldSave && accumulatedFrames.isEmpty && lastDurablePageIndex != null) { | ||
| if (DateTime.now().difference(lastSaveTime) >= _persistBatchDuration) { | ||
| try { | ||
| await limitlessConnection.acknowledgeProcessedData(lastProcessedIndex); | ||
| Logger.debug("FlashPageSync: Diagnostic-only ACK sent for page $lastProcessedIndex"); | ||
| await limitlessConnection.acknowledgeProcessedData(lastDurablePageIndex); | ||
| lastAcknowledgedIndex = lastDurablePageIndex; | ||
| Logger.debug("FlashPageSync: Diagnostic-only ACK sent for page $lastDurablePageIndex"); |
There was a problem hiding this comment.
Advance past processed diagnostic-only flash pages
When Limitless yields pages with no Opus frames, lastProcessedIndex advances but this branch only re-ACKs the older lastDurablePageIndex; if the range is entirely diagnostic, that value is null and no ACK is sent at all. The later reachedEnd check can still report success because it only compares the ACK against that old/null durable index, after which device refresh exposes the same unacknowledged pages and the auto-resume loop stops for lack of progress. Track and acknowledge the processed diagnostic-page frontier so these ranges can actually drain without acknowledging an unsaved audio batch.
Useful? React with 👍 / 👎.
| final custodyDeviceId = _device!.id; | ||
| final effectiveCaps = connection.ringEffectiveCaps; | ||
| final ringId = (effectiveCaps & RingProtocol.capRingId) != 0 ? ringInfo.ringId : null; |
There was a problem hiding this comment.
Re-probe custody after a transient INFO failure
If both connection-time INFO attempts time out, the probe remains unresolved and _ringEffectiveCaps stays zero; a later INFO read here may succeed, but the sync still takes this cached zero and treats custody firmware as legacy. It consequently sends an unscoped 0x12 ADVANCE instead of the required ring-ID-scoped 0x15, so a ring reset or metadata reinitialization between READ and ADVANCE can release records from the new incarnation. When the fresh ringInfo advertises v1 capabilities but the cached probe does not, re-run negotiation or fail closed rather than using the legacy advance path.
Useful? React with 👍 / 👎.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…21319) * fix(app): bound sync upload batches by audio seconds, not file count Pendant ring custody (#20462, first shipped in v1.0.554) drains buffered pendant audio into a new WAL every 10 seconds. The upload batcher still capped a sync job at five files — a limit sized for 60s chunks, where five files were 300s of audio. With 10s WALs a job became 50s: six times the sync jobs for the same audio against the same rate limiter, and a separate ~50s conversation per job with too little audio to separate speakers. Reported in Discord and #21177: thousands of <=10s recordings on a CV1 pendant, a backlog of 1,200-2,500 that only clears overnight, and every voice attributed to the wearer. Bound each batch by audio instead: up to 300s (five 60s chunks, the budget the backend's 600s stale guard was sized for), with a 30-file ceiling that keeps per-file VAD fan-out at one job of 10s WALs. A WAL longer than the budget still uploads, alone. Custody and the 10s drain are untouched. Verification: - flutter test test/unit/local_wal_sync_test.dart: 144 passed, with and without --dart-define=CAPTURE_EVIDENCE_V1_DARK_WRITE=true. - The three new tests fail against main's batcher (5 files instead of 30 for 40 x 10s WALs; 5 instead of 6 for 10 x 45s; a 400s WAL batched with another). - Existing expectations (25 x 60s -> 5, 6 x 60s -> 5) are unchanged. - dart format and flutter analyze clean on both files. - Not exercised on a device with a pendant backlog. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(app): changelog fragment for sync upload batches by audio Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(app): keep upload batches within the capture manifest's 20-file limit A batch that claims live capture first sends every file in it to /v2/sync-capture-manifest, and SyncCaptureManifestRequest.files accepts at most 20 (backend/routers/sync.py, published as maxItems in docs/api-reference/app-client-openapi.json). The previous ceiling of 30 let a recent single-conversation batch of 21-30 ten-second WALs pass the whole-conversation claim check and then make a guaranteed-failing manifest request before falling back to the paced backfill lane. Cap batches at the manifest limit. A conversation with more pending WALs than one batch holds now never claims, which is the existing whole-conversation rule rather than a claim over a subset. The 300s audio budget is unchanged; for 10s pendant WALs the file ceiling binds first, at 200s per job against the 50s it was before this PR. Verification: - New uploader-level tests in sync_manifest_claim_drain_test.dart drive LocalWalSyncImpl.syncAll with a recording uploader: 20 WALs upload as one claiming batch; 21 drain as 20 + 1 and 30 as 20 + 10 with no claim; and the client ceiling must not exceed the manifest maxItems in the OpenAPI contract. - With the ceiling set back to 30, the 21-file, 30-file and contract tests fail ([21], [30], 30 > 20). - 264 tests across the 11 sync test files pass, with and without --dart-define=CAPTURE_EVIDENCE_V1_DARK_WRITE=true. - dart format and flutter analyze clean. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
## Problem and result Pendant packets arriving during a reconnect could be appended to the WAL buffer after its old contents were drained, then erased by `onAudioCodecChanged` after disk I/O. This is a product audio-loss bug, not a polling fixture bug. Seal the complete old pendant tail and advance codec and device identity synchronously before the flush; packets arriving during I/O stay in the new buffer under the new source's custody. The pendant capture caller supplies identity at this boundary because native BLE continues delivering during the flush. Phone capture starts only after its flush and identity update both finish, so its existing ordering and protected spine oracle remain unchanged. Reuse the existing pendant custody construction and preserve the phone chunk/tail policy. The existing `capture_live_recovery_test` packet count and three-second recovery bound are unchanged. New barrier tests force the exact I/O interval on same-codec reconnects and codec changes, then read the durable index and files to prove every packet appears exactly once, in order, under the correct codec. ## Causal evidence - The pre-fix product fails the new write-barrier test: 50 initial packets + 10 during the blocked write produces only 50 durable packets, expected 60. With this fix the barrier and original capture recovery suites pass. - `git log -S 'pendant BLE drop'` and blame locate the failing regression case at `78b11b7ac95` in #22873. The same PR introduced the orphan route in `c6f8014808f`, finalized as synchronous delivery in `930bfaaa519`, exposing an existing codec-reset race: the post-await buffer clear traces to `f3aa85e9e16`, with the pendant drain/flush queue added in `c0c766c0dce1` (#20462). - #22987's CI still reports 210 expected / 200 actual despite its longer 15-second wait: https://github.com/BasedHardware/omi/actions/runs/39554266739/job/119071092410 . Coordination and mechanism are posted on that PR. Its timeout-only approach does not fix this race, so this is a separate product fix. - The original test passes on a fast local filesystem; the write barrier reproduces the packet loss independently of host timing. No test is skipped, quarantined, retried, or weakened. ## Verification All local checks run through `/Users/dazheng/workspace/omi/bin/omi-heavy run -- nice -n 19`. - Baseline: `bash test.sh test/services/capture/capture_live_recovery_test.dart` (138 protected spine tests and 17 capture recovery tests passed). - Red: the new same-codec write-barrier regression against unmodified main fails 60 expected / 50 actual. - Green after source-identity correction: `flutter test test/unit/local_wal_durability_seam_test.dart test/unit/local_wal_sync_test.dart test/unit/local_wal_live_custody_test.dart test/unit/local_wal_sync_session_generation_test.dart test/unit/local_wal_sync_owner_uid_test.dart test/services/capture test/services/wals`, 633 passed. Includes same-codec and changed-codec write barriers, two-pendant ring custody during flush, exact file payloads, session generation fencing and unchanged live recovery assertions. - `flutter test --dart-define=OMI_DEV_CONTROLS=1 test/spine`: 138 passed after the correction. - `scripts/pr-preflight --pr-body-file ...`: 25 checks passed. `OMI_PR_BODY_FILE=... make preflight`: 25 checks passed. Push hooks also run without bypasses. This is source-level and hermetic disk evidence. No physical-device run or production account data was used. A read-only App Store Connect check on 2026-10-21 confirms iOS 1.0.568 build 1423 is still `WAITING_FOR_REVIEW`, release `MANUAL`; public iOS is 1.0.566 build 1417. Codemagic identifies iOS1423 and Android1471's source as `fbb197a6bf4fb56b432280140beb6c8c797e5927`, containing #22873 and the vulnerable clear. The existing rollout receipt `6ad848373ac160f4685c9479` at 05:06 UTC confirms Android 1.0.568/1471 advanced from 1% to 10% production. Public Play still lists 1.0.567, so the listing alone missed staged exposure. The later internal 1.0.569 candidates (iOS1427, Android1475; source `bbede22e1e4`) also contain the vulnerable code. Field-loss prevalence was not measured. A rebuilt mobile artifact is needed; no backend deployment is needed. ## Review follow-through - Round 1 full Grok review: SHIP at `6fc768e8375`. - Automated P1: moving codec before I/O must also move device identity. A two-pendant write barrier reproduces missing ring evidence on the first head; the fix moves codec/device together for the pendant caller and checks exact old/new device, codec, ring, epoch and frame counts. - The unchanged stop/ingress race noted as minor in round 1 is tracked in #22996. This PR changes the automatic reconnect/source boundary. ## Product invariants affected - INV-CAP-1: preserve every admitted pendant packet across automatic reconnect and WAL source changes, including arrivals during durable writes. Failure-Class: new UI-Evidence: none -- WAL buffering and hermetic regressions only; no UI change. Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2756 -> 2764 | extract one synchronous pendant-sealing primitive shared by tail drain and source rollover so asynchronous flushes cannot erase later arrivals or bind them to the previous device
Summary
App-only pendant ring custody v1 and phone durability. No firmware, backend, overwrite-oldest policy, server receipt, or phone-mic safety-copy changes.
app/lib/services/wals/PENDANT_RING_CUSTODY.mdfor the parallel firmware PR to link to.Supervisor changes on top of the implementation lane:
Compatibility matrix
Costs and limits
These are engineering estimates, not hardware battery measurements.
Verification
Commands run from the supplied worktree; Flutter commands below use
app/as cwd unless noted.bash app/test.sh(root) on the final head16e94536fd: exit 0, main suite 4,263 passed / 5 skipped / 0 failed, plus the opt-in spine suite 138 passed.flutter test test/services/devices/transports/native_ble_transport_test.dart test/unit/native_ble_transport_resync_test.dart test/unit/omi_ring_custody_test.dart test/unit/pendant_ring_custody_test.dart test/unit/local_wal_live_custody_test.dart test/unit/local_wal_sync_test.dart test/unit/pendant_custody_main_red_test.dart: exit 0, 188 passed after the native opt-in gate, validation-race, and immutable-WAL fixes; raw log.agent-briefs/raw-logs/flutter-test-final-fix.log.flutter test test/unit/pendant_ring_custody_test.dart test/services/capture/capture_transcript_coverage_test.dart test/unit/pendant_custody_main_red_test.dart: exit 0, 55 passed after the final record-gap/wrap proof guard; raw log.agent-briefs/raw-logs/flutter-test-final-mark-guard.log. Both fix(app): release the pendant backup only for audio the saved transcript covers #20376 regression files remain green.flutter analyzecovered 36 Dart files: no errors or warnings; 16 existing info-level diagnostics remained. The three final mark-guard files reported 0 issues, exit 0 (flutter-analyze-mark-guard.log). No analysis baseline was changed.bash app/scripts/analyze_ratchet.sh(root): PASS, exit 0; raw log.agent-briefs/raw-logs/analyze-ratchet-final.log.dart format --line-length 120on all changed Dart files: clean; pre-commit formatted 36 files with 0 changes.git diff --no-index -- .agent-briefs/pendant-ring-custody-contract.md app/lib/services/wals/PENDANT_RING_CUSTODY.md: exit 0, canonical contract is byte-identical.make preflighton the committed tree: 22 checks passed (.agent-briefs/raw-logs/make-preflight-committed.log); re-run by the pre-push hook on the final head.Red/green evidence and limits
The isolated baseline worktree is pinned to
2e00a44ff2. Three tests copied verbatim inpendant_custody_main_red_test.dartfail at runtime on that base (0 passed / 3 failed) and pass here (3 passed): capable-firmware opt-in, 10-second pendant disk drain, and preservation of 723 pending files. Logs:flutter-test-base-red-main-compat.logandflutter-test-main-red-branch.log.Four additional confirmed behavioral reds from the original baseline run cover SD pre-write admission, rejected CLEAR, timestamp-marker placement, and colliding external WAL inventory. The mixed baseline invocation ended 8 passed / 7 failed; some failures were missing new APIs and are not counted as behavioral reds (
flutter-test-base-red-2e00a44.log).The literal request that every behavior test fail on main is not fully met. API-new tests cannot compile unchanged on main, and unchanged legacy compatibility/negative regression guards should pass on both branches. Those cases are reported as compile limitations or regression controls, not fabricated behavioral-red evidence. The branch tests include actual LocalWalSync/WalFileManager files and index persistence, live index barriers, kill-before-flush, lost-ACK replay, incarnation changes, missing-file keep-both, scripted Omi command bytes, and a real NativeBleTransport held-gate/liveness/generation fixture. Some sync tests use strict logical DeviceConnection fakes rather than wire/hardware replay.
Product invariants affected
PRODUCT.md): release a copy only after the next holder is durable. The canonical pendant custody contract is the executable-design authority for the app and firmware lanes.device_timerStartidentity, timerStart/seconds coverage semantics, ownership buckets, and server-confirmedsyncedAtretention. The fix(app): release the pendant backup only for audio the saved transcript covers #20376 capture-transcript and local-WAL tests are required regression gates.Failure-Class: none
The existing advertised-capability and delivery-reachability registry entries describe different mechanisms; this fix is a durable holder handoff / ring-incarnation boundary. A new registry definition would be outside the explicitly app-only scope.
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2023 -> 2572 | Keep the existing WAL inventory, ownership buckets, lifecycle drains, and durable index boundary together; ring incarnation and live-mark proof mapping are isolated in pendant_ring_custody.dart.
Implemented with Devin; supervised, amended and published by Claude Code.
🤖 Generated with Claude Code