Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -970,3 +970,45 @@ coordinator on the event bus, so every frame was persisted and handled twice.
auto-reconnect) runs for the process's first composition only (`claimStartup()`). Re-running the
stale-state reset would write DISCONNECTED over a live link.
- A recreated Activity's first `ON_START` is not the startup's, so it does run `reconnectIfNeeded()`.

## Accuracy check: what it may and may not change

**Read this before touching `health/accuracy/`, the export's held-back records, or anything that
reads `AccuracyCorrections`.** Full design and the "As built" notes: `docs/accuracy-check-plan.md`.

The feature compares the ring with another device's Health Connect records for a few days, holds
back the duplicate exports meanwhile, and can correct a consistent bias. Each rule below is there
because breaking it fails silently:

- **Every reference read filters on `DataOrigin`.** Without it PulseLoop's own earlier exports, or
a third app re-syncing them, get compared with the ring and the report reads "perfect
agreement". A bridge app (Health Sync) can still echo PulseLoop's export back under its own
package, which no origin filter catches. That is what the HR echo check is for (an exact
second-and-beat match on most samples); keep it running on every scoring pass.
- **The reference's readings are never stored.** `accuracy_check_days` holds aggregates only. It
would be the first foreign health data in the archive, and the diagnostics export rule
(no readings in text people paste) applies to the "Copy summary" and "Share" texts too.
- **Held-back exports are filtered by data time, and the watermark still advances past them.**
Don't "fix" this into holding the watermark. That is what makes Skip-these-days the default
with nothing to undo, and what keeps a window record that is updated later (a re-synced night)
out of Health Connect. Export-them-too rewinds watermarks under
`HealthConnectExportWorker.passMutex`; a rewind outside the mutex can be overtaken by a pass in
flight. The pause set follows the **reference device**, never the ring's capability list, so
a ring swap can't open a duplication gap.
- **Corrections are read-time only, and never reach Health Connect.** Stored rows stay as the
ring sent them; it re-sends its history, so a rewritten row wouldn't stay rewritten anyway.
A derived figure that is also *exported* keeps a raw copy for the export:
`estimatedActiveCalories` (raw, exported) vs `estimatedActiveCaloriesAdjusted` (shown), and
`hrRestingBaseline` (raw, exported) vs `Corrections.baseline()` at read time. The display
helpers (`DailyCalorieEstimator.displayActiveCalories` / `displayCalories`) must not be used
by an exporter. A screen showing corrected figures carries the `AdjustedCaption` (a widget tile,
its `adjusted` flag). The coach reads through the corrections too and is told so; a workout's
stored samples and summary stay raw because Health Connect and Strava get them.
- **Corrections belong to one ring (BLE address) and only exist after a consistent-bias
verdict.** Don't widen them to "Inconsistent": a slider that moves the average of an erratic
ring is exactly the false fix the verdict exists to refuse. Sleep stages, onset/wake, HRV and
calories are report-only on purpose: vendors compute them differently, so a difference there
doesn't show which device is wrong.
- **A running check ends the moment a different ring is paired** (`AccuracyRingWatcher`, started
from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split
the two rings' data.
18 changes: 16 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
<!-- Phase 8: Health Connect export (write-only). Exactly the Phase 1–4 data types from
docs/health-connect-integration.md — Phase 5 types (blood pressure, glucose, respiratory
rate, VO2max, resting HR, nutrition) - the Phase 5 "beyond iOS" types, added in Phase 5 so the
first permission sheet stayed narrow. No READ_* permissions anywhere. -->
first permission sheet stayed narrow. The export itself holds no READ_* permissions; the
two read paths below each ask for their own. -->
<uses-permission android:name="android.permission.health.WRITE_HEART_RATE" />
<uses-permission android:name="android.permission.health.WRITE_OXYGEN_SATURATION" />
<uses-permission android:name="android.permission.health.WRITE_HEART_RATE_VARIABILITY" />
Expand All @@ -66,14 +67,27 @@
<uses-permission android:name="android.permission.health.WRITE_VO2_MAX" />
<uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />
<uses-permission android:name="android.permission.health.WRITE_NUTRITION" />
<!-- The one Health Connect READ path: a smart scale's body measurements (HealthConnectBodyImport). -->
<!-- Health Connect READ path 1: a smart scale's body measurements (HealthConnectBodyImport). -->
<uses-permission android:name="android.permission.health.READ_WEIGHT" />
<uses-permission android:name="android.permission.health.READ_HEIGHT" />
<uses-permission android:name="android.permission.health.READ_BODY_FAT" />
<uses-permission android:name="android.permission.health.READ_LEAN_BODY_MASS" />
<uses-permission android:name="android.permission.health.READ_BONE_MASS" />
<uses-permission android:name="android.permission.health.READ_BODY_WATER_MASS" />
<uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE" />
<!-- Accuracy check (docs/accuracy-check-plan.md): reads another device's data to compare the
ring against it. Its own permission set (AccuracyCheckPermissions), requested from
Settings → Accuracy check, never through the export's sheet. -->
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.READ_DISTANCE" />
<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_SLEEP" />
<uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY" />
<!-- Optional: lets the accuracy check's 6-hourly worker read without the app open. -->
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />

<application
android:name=".PulseLoopApplication"
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/com/pulseloop/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ class MainActivity : ComponentActivity() {
if (intent?.action == ACTION_LOG_MEAL) {
com.pulseloop.ui.LaunchRequests.route.value = "nutrition/photo"
intent.action = null // a recreated Activity must not reopen it
} else if (intent?.action == ACTION_OPEN_ACCURACY_CHECK) {
com.pulseloop.ui.LaunchRequests.route.value = "settings/accuracy-check"
intent.action = null
}
}

Expand All @@ -154,6 +157,8 @@ class MainActivity : ComponentActivity() {

companion object {
const val ACTION_LOG_MEAL = "com.pulseloop.action.LOG_MEAL"
/** The accuracy-report-ready notification. */
const val ACTION_OPEN_ACCURACY_CHECK = "com.pulseloop.action.OPEN_ACCURACY_CHECK"
}

private fun handleStravaRedirect(intent: Intent) {
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ class PulseLoopApplication : Application() {
com.pulseloop.service.DrinkPrefs.init(this)
// Application-scoped so capture runs whether or not the Debug screen is open.
DiagnosticsSubscriber(PulseLoopDatabase.getInstance(this)).start(appScope)
// Accuracy check: a different ring ends a running check at once (it can't be told apart later).
com.pulseloop.health.accuracy.AccuracyRingWatcher.start(this, appScope)
com.pulseloop.health.accuracy.AccuracyNotifications.createChannel(this)
// One-time cleanup of activity totals corrupted by the old bucket handling; runs off the
// main thread and is prefs-gated so it executes once. Safe to race the first sync — the
// ring can't connect before this completes a couple of DELETE statements.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,38 @@ object CoachContextBuilder {
val goal = db.userGoalDao().get()

val todayStart = localStartOfDay(now)
val todayActivity = db.activityDailyDao().byDay(todayStart)
// The coach is given what the app shows: accuracy corrections applied, and said so below.
val corrections = com.pulseloop.health.accuracy.AccuracyCorrections.load(db)
val todayActivity = db.activityDailyDao().byDay(todayStart)?.let(corrections::day)

// Latest HR / SpO2
val latestHr = db.measurementDao().latest(MeasurementKind.HEART_RATE.name, now)
val latestSpo2 = db.measurementDao().latest(MeasurementKind.SPO2.name, now)
val latestHr = db.measurementDao().latest(MeasurementKind.HEART_RATE.name, now)?.let(corrections::heartRate)
val latestSpo2 = db.measurementDao().latest(MeasurementKind.SPO2.name, now)?.let(corrections::spo2)

// 7-day trends. Real wins over seeded rows once the ring has synced (`DemoDataPolicy`):
// a connect no longer purges demo data, so without this the coach LLM is handed a
// demo/real blend — and, via `isDemo` below, told it is live.
val activityHasReal = db.activityDailyDao().hasReal()
val sevenDaysAgo = todayStart - 7 * 24 * 3600_000L
val activityWeek = (if (activityHasReal) db.activityDailyDao().recentReal(7)
else db.activityDailyDao().recent(7)).filter { it.date >= sevenDaysAgo }
else db.activityDailyDao().recent(7)).filter { it.date >= sevenDaysAgo }.map(corrections::day)
val stepsWeek = activityWeek.map { it.steps.toDouble() }
val daysAvailable = activityWeek.count { it.steps > 0 }

// Resting HR: average of HR values in the last 24h while at rest (approximated as lowest 25th percentile)
val hr24h = if (db.measurementDao().hasReal(MeasurementKind.HEART_RATE.name))
db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, now - 24 * 3600_000L, now)
else db.measurementDao().range(MeasurementKind.HEART_RATE.name, now - 24 * 3600_000L, now)
val hr24hShown = hr24h.map(corrections::measurement)
val restingHr = if (hr24h.isNotEmpty()) {
val sorted = hr24h.map { it.value }.sorted()
val sorted = hr24hShown.map { it.value }.sorted()
sorted[(sorted.size * 0.25).toInt().coerceAtMost(sorted.size - 1)]
} else null

// Sleep
val sleepHasReal = db.sleepSessionDao().hasReal()
val latestSleep = (if (sleepHasReal) db.sleepSessionDao().recentReal(1)
else db.sleepSessionDao().recent(1)).firstOrNull()
else db.sleepSessionDao().recent(1)).firstOrNull()?.let(corrections::sleep)

val completeness = profileCompleteness(profile)
val warnings = DataQualityAnalyzer.warnings(
Expand All @@ -71,7 +74,7 @@ object CoachContextBuilder {
(activityWeek.isNotEmpty() || latestSleep != null || hr24h.isNotEmpty()),
),
now = now,
)
) + listOfNotNull(corrections.coachNote())

return CoachContextPacket(
today = LocalDate.now().toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,14 @@ object CoachSummaryContextBuilder {
/** Readiness and activity scores (docs/oura-ux-analysis.md phase 5). */
val scores: com.pulseloop.service.ScoresContext? = null,
)
// What the app shows: accuracy corrections applied (packet.dataQualityWarnings says so).
val corrections = com.pulseloop.health.accuracy.AccuracyCorrections.load(db)
val activity = db.activityDailyDao().byDay(
java.time.LocalDate.now().atStartOfDay(java.time.ZoneId.systemDefault())
.toInstant().toEpochMilli()
)
val latestHr = db.measurementDao().latest(com.pulseloop.ring.MeasurementKind.HEART_RATE.name)
val latestSpo2 = db.measurementDao().latest(com.pulseloop.ring.MeasurementKind.SPO2.name)
)?.let(corrections::day)
val latestHr = db.measurementDao().latest(com.pulseloop.ring.MeasurementKind.HEART_RATE.name)?.let(corrections::heartRate)
val latestSpo2 = db.measurementDao().latest(com.pulseloop.ring.MeasurementKind.SPO2.name)?.let(corrections::spo2)

val tp = TodayPacket(
today = todayDate,
Expand Down Expand Up @@ -92,12 +94,13 @@ object CoachSummaryContextBuilder {
suspend fun sleepDay(db: PulseLoopDatabase): Built? {
val todayStart = java.time.LocalDate.now().atStartOfDay(java.time.ZoneId.systemDefault())
.toInstant().toEpochMilli()
val session = db.sleepSessionDao().byDay(todayStart) ?: return null
val corrections = com.pulseloop.health.accuracy.AccuracyCorrections.load(db)
val session = db.sleepSessionDao().byDay(todayStart)?.let(corrections::sleep) ?: return null
if (session.totalMinutes <= 0) return null

val blocks = db.sleepStageBlockDao().forSession(session.id)
val score = SleepScore.calculate(session, blocks)
val activitySteps = db.activityDailyDao().byDay(todayStart)?.steps
val activitySteps = db.activityDailyDao().byDay(todayStart)?.let(corrections::day)?.steps

@Serializable
data class SleepDayPacket(
Expand Down
13 changes: 9 additions & 4 deletions app/src/main/java/com/pulseloop/coach/tools/CoachDataAccess.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.pulseloop.coach.tools

import com.pulseloop.health.accuracy.AccuracyCorrections
import com.pulseloop.data.PulseLoopDatabase
import com.pulseloop.data.entity.*
import com.pulseloop.ring.MeasurementKind
Expand Down Expand Up @@ -79,7 +80,9 @@ object CoachDataAccess {
db: PulseLoopDatabase, kind: MeasurementKind, start: String, end: String
): List<MeasurementEntity> {
val bounds = dayBounds(start, end) ?: return emptyList()
return db.measurementDao().range(kind.name, bounds.first, bounds.second)
// The coach sees what the app shows: accuracy corrections applied (read-time only).
val c = AccuracyCorrections.load(db)
return db.measurementDao().range(kind.name, bounds.first, bounds.second).map(c::measurement)
}

suspend fun activityRows(
Expand All @@ -88,12 +91,13 @@ object CoachDataAccess {
val s = parseLocalDate(start) ?: return emptyList()
val e = parseLocalDate(end) ?: return emptyList()
val recent = db.activityDailyDao().recent(90) // broad window; filter in Kotlin
return recent.filter { it.date >= s && it.date <= e }.sortedBy { it.date }
val c = AccuracyCorrections.load(db)
return recent.filter { it.date >= s && it.date <= e }.sortedBy { it.date }.map(c::day)
}

suspend fun activityRow(db: PulseLoopDatabase, date: String): ActivityDailyEntity? {
val day = parseLocalDate(date) ?: return null
return db.activityDailyDao().byDay(day)
return db.activityDailyDao().byDay(day)?.let(AccuracyCorrections.load(db)::day)
}

suspend fun sleepSessions(
Expand All @@ -102,7 +106,8 @@ object CoachDataAccess {
val s = parseLocalDate(start) ?: return emptyList()
val e = parseLocalDate(end) ?: return emptyList()
val recent = db.sleepSessionDao().recent(90)
return recent.filter { it.date in s..e }.sortedBy { it.date }
val c = AccuracyCorrections.load(db)
return recent.filter { it.date in s..e }.sortedBy { it.date }.map(c::sleep)
}

suspend fun activitySessions(
Expand Down
Loading
Loading