diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index 618fc092..6781c9e2 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -48,8 +48,9 @@ import com.pulseloop.data.entity.* CoachGoalEntity::class, FoodPreferenceEntity::class, DrinkEntryEntity::class, + FindingEntity::class, ], - version = 32, + version = 33, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -78,6 +79,8 @@ abstract class PulseLoopDatabase : RoomDatabase() { abstract fun foodPreferenceDao(): FoodPreferenceDao /** Drinks (docs/drinks-plan.md, v32). */ abstract fun drinkDao(): DrinkDao + /** "What changed" findings (v33). */ + abstract fun findingDao(): FindingDao abstract fun coachSummaryDao(): CoachSummaryDao abstract fun wearableLogDao(): WearableLogDao abstract fun rawPacketDao(): RawPacketDao @@ -129,6 +132,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { "coach_goals", "food_preferences", "drink_entries", + "findings", ) @Volatile private var INSTANCE: PulseLoopDatabase? = null @@ -597,6 +601,18 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** v32 → v33: the "what changed" findings log. */ + private val MIGRATION_32_33 = object : Migration(32, 33) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `findings` (`id` TEXT NOT NULL, `day` INTEGER NOT NULL, `kind` TEXT NOT NULL, " + + "`title` TEXT NOT NULL, `detail` TEXT NOT NULL, `positive` INTEGER NOT NULL, " + + "`algorithmVersion` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + db.execSQL("CREATE INDEX IF NOT EXISTS `index_findings_day` ON `findings` (`day`)") + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -695,6 +711,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_29_30, MIGRATION_30_31, MIGRATION_31_32, + MIGRATION_32_33, ) // Downgrades only (sideloading an older APK). A blanket destructive // fallback would silently wipe every measurement, sleep session, and diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index a993fd11..1a2b889b 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -965,3 +965,18 @@ interface DrinkDao { @Query("DELETE FROM drink_entries") suspend fun clear() } + +@Dao +interface FindingDao { + @Query("SELECT * FROM findings WHERE day >= :from ORDER BY day DESC, kind ASC") + fun sinceFlow(from: Long): Flow> + + @Query("SELECT * FROM findings WHERE day >= :from ORDER BY day DESC, kind ASC") + suspend fun since(from: Long): List + + @Query("DELETE FROM findings WHERE day >= :from AND algorithmVersion = :version") + suspend fun deleteWindow(from: Long, version: Int) + + @Upsert + suspend fun upsertAll(rows: List) +} diff --git a/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt b/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt index 3e70bee5..44000752 100644 --- a/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt +++ b/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt @@ -416,3 +416,19 @@ data class FoodPreferenceEntity( fun idFor(slot: String, item: String, action: String) = "$slot:${item.trim().lowercase()}:$action" } } + +/** + * One "what changed" finding (service/Findings.kt): one row per day and kind, stamped with the + * formula version that produced it. Derived and recomputable, so it isn't in the backup archive. + */ +@Entity(tableName = "findings", indices = [Index("day")]) +data class FindingEntity( + @PrimaryKey val id: String, + val day: Long, + val kind: String, + val title: String, + val detail: String, + val positive: Boolean, + val algorithmVersion: Int, + val createdAt: Long = System.currentTimeMillis(), +) diff --git a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt index 8693f68c..d954cdcd 100644 --- a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt +++ b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt @@ -102,6 +102,8 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork val local = Instant.ofEpochMilli(now).atZone(zone) val today = local.toLocalDate() val inputs = runCatching { ReadinessRepository.loadInputs(db, now, zone) }.getOrNull() ?: return Result.success() + // Keep the "what changed" log current even when the screen isn't opened. + runCatching { com.pulseloop.service.FindingsRepository.refresh(db, now, zone) } // 1. Something's off — once a day, during waking hours, once last night has synced. val night = inputs.lastNight diff --git a/app/src/main/java/com/pulseloop/service/Algorithms.kt b/app/src/main/java/com/pulseloop/service/Algorithms.kt new file mode 100644 index 00000000..13796f4c --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/Algorithms.kt @@ -0,0 +1,27 @@ +package com.pulseloop.service + +/** + * The version of PulseLoop's scoring and insight formulas. Bump it whenever a change would make a + * past day's number differ if it were computed again. Findings are stamped with it, the "data + * behind this score" view shows it, and comparisons never reach back across a bump, so an app + * update is never reported as a change in the person (OpenStrap Edge's rule). + */ +object Algorithms { + const val VERSION = 3 + + /** What each version changed, newest first, for the data view. */ + val HISTORY = listOf( + 3 to "HRV withheld when sparse, flat or scattered; readiness withheld below half its weight; corrected journal statistics", + 2 to "Readiness gained body temperature and recovery index; sleep scored against learned sleep need", + 1 to "First readiness, sleep and activity scores", + ) + + /** When the current version first ran on this device; findings before it aren't compared across. */ + fun firstRunOfCurrent(context: android.content.Context): Long { + val p = context.applicationContext.getSharedPreferences("algorithms", android.content.Context.MODE_PRIVATE) + if (p.getInt("version", 0) != VERSION) { + p.edit().putInt("version", VERSION).putLong("since", System.currentTimeMillis()).apply() + } + return p.getLong("since", System.currentTimeMillis()) + } +} diff --git a/app/src/main/java/com/pulseloop/service/Findings.kt b/app/src/main/java/com/pulseloop/service/Findings.kt new file mode 100644 index 00000000..0ca598c4 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/Findings.kt @@ -0,0 +1,133 @@ +package com.pulseloop.service + +import java.time.LocalDate +import kotlin.math.abs +import kotlin.math.roundToInt + +/* + * "What changed": each night compared with the user's own trailing history, written down so it + * can be browsed later instead of living only in a notification (OpenStrap Edge's findings log). + * A day where nothing stood out is a complete answer, not an empty state. + */ + +data class Finding( + val day: LocalDate, + /** Stable per day: one row per kind per day, so a re-run replaces rather than duplicates. */ + val kind: Kind, + val title: String, + val detail: String, +) { + enum class Kind(val positive: Boolean) { + RESTING_HR_UP(false), RESTING_HR_DOWN(true), + HRV_DOWN(false), HRV_UP(true), + TEMPERATURE_UP(false), + SLEEP_SHORT(false), SLEEP_LONGER(true), + RADAR(false), + } +} + +object Findings { + /** Nights of history needed before any comparison is made. */ + const val MIN_BASELINE = 14 + private const val BASELINE_DAYS = 28L + + private fun median(v: List): Double? { + if (v.isEmpty()) return null + val s = v.sorted(); val m = s.size / 2 + return if (s.size % 2 == 1) s[m] else (s[m - 1] + s[m]) / 2 + } + + /** Median absolute deviation, floored so a very steady baseline can't make noise look big. */ + private fun mad(v: List, floor: Double): Double { + val m = median(v) ?: return floor + return maxOf(median(v.map { abs(it - m) }) ?: floor, floor) + } + + /** + * Findings for [day] (a waking day), from nights up to and including it. Recent windows are + * compared with the 28 nights before them; each detector needs a 14-night baseline and a + * change that is both big in absolute terms and large against the user's usual spread. + */ + fun forDay(day: LocalDate, nights: List, radar: SymptomRadar.Level? = null): List { + val upTo = nights.filter { !it.day.isAfter(day) }.sortedBy { it.day } + fun recent(n: Long) = upTo.filter { it.day.isAfter(day.minusDays(n)) } + fun baseline(n: Long) = upTo.filter { !it.day.isAfter(day.minusDays(n)) && it.day.isAfter(day.minusDays(n + BASELINE_DAYS)) } + val out = mutableListOf() + + // Resting heart rate: the last 3 nights against the 28 before. + run { + val now = recent(3).mapNotNull { it.restingHr } + val base = baseline(3).mapNotNull { it.restingHr } + if (now.size < 2 || base.size < MIN_BASELINE) return@run + val m = median(now)!!; val b = median(base)!! + val delta = m - b + if (delta >= 3 && delta >= 2 * mad(base, 1.0)) { + out += Finding(day, Finding.Kind.RESTING_HR_UP, "Resting heart rate up", + "${m.roundToInt()} bpm over the last 3 nights against your usual ${b.roundToInt()}. Illness, alcohol, stress, heat or hard training can all raise it.") + } + } + // Resting heart rate trending down over two weeks: usually fitness or recovery. + run { + val now = recent(14).mapNotNull { it.restingHr } + val base = baseline(14).mapNotNull { it.restingHr } + if (now.size < 10 || base.size < MIN_BASELINE) return@run + val delta = median(now)!! - median(base)!! + if (delta <= -3) { + out += Finding(day, Finding.Kind.RESTING_HR_DOWN, "Resting heart rate trending down", + "${abs(delta).roundToInt()} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery.") + } + } + // HRV: the last 3 nights against the 28 before. + run { + val now = recent(3).mapNotNull { it.hrv } + val base = baseline(3).mapNotNull { it.hrv } + if (now.size < 2 || base.size < MIN_BASELINE) return@run + val m = median(now)!!; val b = median(base)!! + if (b <= 0) return@run + if (m <= b * 0.85 && b - m >= 2 * mad(base, 2.0)) { + out += Finding(day, Finding.Kind.HRV_DOWN, "HRV lower than usual", + "${m.roundToInt()} ms over the last 3 nights against your usual ${b.roundToInt()} (${((m - b) / b * 100).roundToInt()}%). Your body may be under extra load.") + } + } + run { + val now = recent(14).mapNotNull { it.hrv } + val base = baseline(14).mapNotNull { it.hrv } + if (now.size < 10 || base.size < MIN_BASELINE) return@run + val m = median(now)!!; val b = median(base)!! + if (b > 0 && m >= b * 1.10) { + out += Finding(day, Finding.Kind.HRV_UP, "HRV trending up", + "${((m - b) / b * 100).roundToInt()}% higher over two weeks than the four before.") + } + } + // Skin temperature: last night against the 28 before. + run { + val t = upTo.lastOrNull { it.day == day }?.temperature ?: return@run + val base = baseline(1).mapNotNull { it.temperature } + if (base.size < MIN_BASELINE) return@run + val b = median(base)!! + val delta = t - b + if (delta >= 0.5 && delta >= 2 * mad(base, 0.1)) { + out += Finding(day, Finding.Kind.TEMPERATURE_UP, "Skin temperature up", + "+%.1f °C last night against your usual. Can come with illness, a late workout, alcohol or the menstrual cycle.".format(delta)) + } + } + // Sleep: the last 7 nights against the 28 before. + run { + val now = recent(7).map { it.asleepMinutes.toDouble() }.filter { it > 0 } + val base = baseline(7).map { it.asleepMinutes.toDouble() }.filter { it > 0 } + if (now.size < 5 || base.size < MIN_BASELINE) return@run + val delta = now.average() - median(base)!! + if (delta <= -45) { + out += Finding(day, Finding.Kind.SLEEP_SHORT, "Sleeping less this week", + "${abs(delta).roundToInt()} min a night less than your usual over the last 7 nights.") + } else if (delta >= 45) { + out += Finding(day, Finding.Kind.SLEEP_LONGER, "Sleeping more this week", + "${delta.roundToInt()} min a night more than your usual over the last 7 nights.") + } + } + if (radar != null && radar != SymptomRadar.Level.NONE) { + out += Finding(day, Finding.Kind.RADAR, "Symptom Radar: ${radar.label.lowercase()}", radar.summary) + } + return out + } +} diff --git a/app/src/main/java/com/pulseloop/service/FindingsRepository.kt b/app/src/main/java/com/pulseloop/service/FindingsRepository.kt new file mode 100644 index 00000000..b6117c38 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/FindingsRepository.kt @@ -0,0 +1,41 @@ +package com.pulseloop.service + +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.FindingEntity +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId + +/** Recomputes the last [WINDOW_DAYS] of findings and stores them; older rows are history. */ +object FindingsRepository { + const val WINDOW_DAYS = 30L + + fun dayKey(d: LocalDate, zone: ZoneId) = d.atStartOfDay(zone).toInstant().toEpochMilli() + fun dateOf(ms: Long, zone: ZoneId): LocalDate = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate() + + suspend fun refresh(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()) { + val inputs = ReadinessRepository.loadInputs(db, now, zone) + val nights = inputs.history + listOfNotNull(inputs.lastNight) + val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + val radarToday = runCatching { HealthInsightsRepository.load(db, now, zone).radar?.level }.getOrNull() + val rows = (0 until WINDOW_DAYS).flatMap { back -> + val day = today.minusDays(back) + Findings.forDay(day, nights, radar = if (back == 0L) radarToday else null).map { f -> + FindingEntity( + id = "${dayKey(day, zone)}:${f.kind.name}", + day = dayKey(day, zone), + kind = f.kind.name, + title = f.title, + detail = f.detail, + positive = f.kind.positive, + algorithmVersion = Algorithms.VERSION, + ) + } + } + val from = dayKey(today.minusDays(WINDOW_DAYS - 1), zone) + // Today's Symptom Radar row is only computed for today; keep earlier days' radar rows. + val keptRadar = db.findingDao().since(from).filter { it.kind == Finding.Kind.RADAR.name && it.day != dayKey(today, zone) } + db.findingDao().deleteWindow(from, Algorithms.VERSION) + db.findingDao().upsertAll(rows + keptRadar) + } +} diff --git a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt index 46cf1f4a..b1dabe8f 100644 --- a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt +++ b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt @@ -182,7 +182,7 @@ object HealthInsightsRepository { val expected = profile?.age?.let { CardioCapacity.expectedVo2(it, profile?.sex?.lowercase() == "female") } val score = expected?.let { HealthArea.scoreOf(c.vo2max / it * 0.85) } ?: 60 add(HealthArea("Heart health", HealthArea.rate(score), score, weekly { it.restingHr }, - "Cardio capacity ${c.level.label.lowercase()}" + (c.cardioAge?.let { ", cardiovascular age about $it" } ?: ""))) + "Cardio capacity ${c.level.label.lowercase()}, estimated from resting heart rate and age")) } } diff --git a/app/src/main/java/com/pulseloop/service/Readiness.kt b/app/src/main/java/com/pulseloop/service/Readiness.kt index 1bd75f1f..3da6abc0 100644 --- a/app/src/main/java/com/pulseloop/service/Readiness.kt +++ b/app/src/main/java/com/pulseloop/service/Readiness.kt @@ -83,6 +83,14 @@ data class NightSummary( val temperature: Double? = null, /** When the night's sustained lowest heart rate happened (recovery index). */ val minHrAt: Long? = null, + /** Readings behind the night's numbers, for the "data behind this score" view. */ + val hrSamples: Int = 0, + val hrvSamples: Int = 0, + /** + * Numbers withheld tonight and why ("hrv" → "…"), so the UI says "not measured" with a + * reason instead of guessing (OpenStrap Edge refuses an artefact night the same way). + */ + val withheld: Map = emptyMap(), ) { /** Clock midpoint of the night, in minutes past local midnight of the waking day (may be negative). */ fun midpointMinutes(zone: ZoneId): Int { @@ -118,7 +126,12 @@ object NightlyVitals { val lowest = if (hr.size >= MIN_HR_SAMPLES) windows.minByOrNull { w -> w.sumOf { it.value } } else null val restingHr = lowest?.map { it.value }?.average() - val hrvValue = if (hrvNight.size >= MIN_HRV_SAMPLES) median(hrvNight.map { it.value }) else null + val hrvGate = hrvQuality(hrvNight.map { it.value }) + val hrvValue = if (hrvGate == null) median(hrvNight.map { it.value }) else null + val withheld = buildMap { + hrvGate?.let { put("hrv", it) } + if (hr.size < MIN_HR_SAMPLES) put("restingHr", "Only ${hr.size} heart-rate reading${if (hr.size == 1) "" else "s"} during the night ($MIN_HR_SAMPLES needed)") + } val slots = ((endAt - startAt) / SLOT_MS).toInt().coerceAtLeast(1) val covered = hr.map { ((it.timestampMs - startAt) / SLOT_MS).toInt().coerceIn(0, slots - 1) }.toSet().size @@ -137,12 +150,45 @@ object NightlyVitals { .takeIf { it.size >= MIN_HRV_SAMPLES } ?.let { s -> median(s.map { it.value }) }?.let { (it * 100).roundToInt() / 100.0 }, minHrAt = lowest?.get(1)?.timestampMs, + hrSamples = hr.size, + hrvSamples = hrvNight.size, + withheld = withheld, ) } } +/** + * Whether a night's HRV readings can stand for the night, or why not. A ring reports HRV as a + * few vendor values a night, so the checks are about those values, not beat intervals: too few, + * all identical (a stored value repeated, not measurements), or scattered so widely that their + * middle means nothing. Null when the night's HRV can be used. + */ +internal fun hrvQuality(values: List): String? { + if (values.isEmpty()) return null + if (values.size < NightlyVitals.MIN_HRV_SAMPLES) { + return "Only ${values.size} HRV reading${if (values.size == 1) "" else "s"} during the night (${NightlyVitals.MIN_HRV_SAMPLES} needed)" + } + if (values.size >= 4 && values.distinct().size == 1) { + return "Every HRV reading was the same value, which looks like a repeated stored number rather than a measurement" + } + val sorted = values.sorted() + val med = sorted[sorted.size / 2] + val mad = values.map { kotlin.math.abs(it - med) }.sorted()[values.size / 2] + if (med > 0 && mad / med > HRV_MAX_SPREAD) { + return "HRV readings were scattered too widely to trust (half were more than ${(mad / med * 100).roundToInt()}% from the middle)" + } + return null +} + +/** Median absolute deviation over median above which a night's HRV is noise, not a level. */ +internal const val HRV_MAX_SPREAD = 0.5 + object Readiness { + /** Readiness needs at least this many contributors carrying at least this share of the weight. */ + const val MIN_CONTRIBUTORS = 2 + const val MIN_WEIGHT_SHARE = 0.5 + /** Oura asks for "up to two weeks"; a week of nights is the least that is a baseline at all. */ const val MIN_BASELINE_NIGHTS = 7 const val MIN_REGULARITY_NIGHTS = 5 @@ -209,6 +255,12 @@ object Readiness { /** No sleep recorded for last night: there is nothing to be ready *from*. */ data object NoSleep : Result() + + /** + * The baseline exists but last night's readings can't carry a score: shown as "—" with the + * reasons rather than a number built from whatever happened to survive. + */ + data class Withheld(val reasons: List, val nightCoverage: Double?) : Result() } data class Inputs( @@ -240,12 +292,21 @@ object Readiness { previousDayActivity(inputs.dailySteps), activityBalance(inputs.dailySteps), ) - // A score from sleep alone is a sleep score; readiness needs the body's own signal. - if (contributors.none { it.kind == ContributorKind.RESTING_HR || it.kind == ContributorKind.HRV_BALANCE }) { - return Result.Learning(nightsWithVitals, MIN_BASELINE_NIGHTS) + // A score from sleep alone is a sleep score; readiness needs the body's own signal, and + // enough of the whole that what survived isn't a guess. + val weightSum = contributors.sumOf { it.kind.weight } + val applicableWeight = ContributorKind.entries + .filter { !(it.optionalSensor && !sensorSeen(it, night, inputs.history)) } + .sumOf { it.weight } + if (contributors.none { it.kind == ContributorKind.RESTING_HR || it.kind == ContributorKind.HRV_BALANCE } || + contributors.size < MIN_CONTRIBUTORS || weightSum < applicableWeight * MIN_WEIGHT_SHARE + ) { + val reasons = night.withheld.values.toList().ifEmpty { + listOf("Last night's heart rate and HRV readings weren't enough to score recovery") + } + return Result.Withheld(reasons, night.coverage) } - val weightSum = contributors.sumOf { it.kind.weight } val value = (contributors.sumOf { it.score * it.kind.weight } / weightSum).roundToInt().coerceIn(0, 100) val present = contributors.map { it.kind }.toSet() return Result.Score( @@ -435,6 +496,8 @@ object ReadinessCopy { is Readiness.Result.Learning -> "Learning your baseline: ${result.nightsCollected} of ${result.nightsNeeded} nights. Keep wearing your ring to bed." Readiness.Result.NoSleep -> "No sleep recorded for last night yet. Sync your ring after you wake up." + is Readiness.Result.Withheld -> + "No readiness today: ${result.reasons.first().replaceFirstChar { it.lowercase() }}. Wear the ring snugly tonight." } /** A visible caution when the ring missed much of the night, or null when coverage is fine. */ diff --git a/app/src/main/java/com/pulseloop/service/ScoresContext.kt b/app/src/main/java/com/pulseloop/service/ScoresContext.kt index 91c7d51c..d29c95bd 100644 --- a/app/src/main/java/com/pulseloop/service/ScoresContext.kt +++ b/app/src/main/java/com/pulseloop/service/ScoresContext.kt @@ -10,7 +10,7 @@ import kotlinx.serialization.Serializable */ @Serializable data class ScoresContext( - /** "score", "learning" or "no_sleep". */ + /** "score", "learning", "withheld" (readings too poor; contributors hold the reasons) or "no_sleep". */ val readinessStatus: String, val readiness: Int? = null, val readinessBand: String? = null, @@ -64,6 +64,13 @@ data class ScoresContext( activityScore = activity?.value, activityBand = activity?.band?.label, ) + is Readiness.Result.Withheld -> ScoresContext( + readinessStatus = "withheld", + readinessContributors = r.reasons, + lastNightCoveragePct = r.nightCoverage?.let { (it * 100).toInt() }, + activityScore = activity?.value, + activityBand = activity?.band?.label, + ) Readiness.Result.NoSleep -> ScoresContext( readinessStatus = "no_sleep", activityScore = activity?.value, diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 0fc9acdb..c3d2951e 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -689,8 +689,12 @@ fun PulseLoopApp() { com.pulseloop.ui.screens.MyHealthScreen( onBack = { navController.popBackStack() }, onBreathe = { navController.navigate("breathe") }, + onWhatChanged = { navController.navigate("what_changed") }, ) } + paddedComposable("what_changed") { + com.pulseloop.ui.screens.WhatChangedScreen(onBack = { navController.popBackStack() }) + } paddedComposable("breathe") { com.pulseloop.ui.screens.BreatheScreen(onBack = { navController.popBackStack() }) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index d79a4868..4bf892ba 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -126,7 +126,7 @@ private fun Sparkline(values: List, color: Color, modifier: Modifier = M } @Composable -fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit) { +fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () -> Unit = {}) { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } var refresh by remember { mutableIntStateOf(0) } @@ -154,6 +154,17 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit) { color = if (loadFailed) PulseColors.warning else PulseColors.textMuted, fontSize = 13.sp, ) } else { + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(onClick = onWhatChanged).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("What changed", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("Your nights against your own normal, kept as a log", fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } RadarSection(s.radar, restUntil) { days -> RestMode.set(context, days); restUntil = RestMode.until(context) } @@ -280,7 +291,9 @@ private fun HeartSection(s: HealthInsightsRepository.Snapshot) { s.cardio?.let { c -> Fact("Cardio capacity (VO₂max)", "%.0f · %s".format(c.vo2max, c.level.label), if (c.fromRing) "Measured by your ring" else "Estimated from resting heart rate and age") - c.cardioAge?.let { Fact("Cardiovascular age", "about $it", "Estimate from VO₂max and HRV against age norms") } + // No "cardiovascular age": from a ring it would only restate resting heart rate and age + // as a number of years, which reads as far more than it is (OpenStrap Edge dropped its + // own for the same reason). } ?: Text("Add your age in Settings → User Profile for cardio capacity.", fontSize = 12.sp, color = PulseColors.textMuted) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt index c5ae4502..42fa5617 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -42,6 +42,7 @@ import com.pulseloop.service.ReadinessRepository import com.pulseloop.service.ScoreContributor import com.pulseloop.service.asScoreContributor import com.pulseloop.ui.theme.PulseColors +import kotlin.math.roundToInt /* * Oura-style score surfaces (docs/oura-ux-analysis.md, phase 2): the three-ring header on Today @@ -153,6 +154,7 @@ fun ScoreHeader( is Readiness.Result.Score -> readiness.band.label is Readiness.Result.Learning -> "Learning" Readiness.Result.NoSleep -> "No sleep yet" + is Readiness.Result.Withheld -> "Not measured" null -> " " }, color = score?.let { bandColor(it.band) } ?: PulseColors.readiness, @@ -260,6 +262,18 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { } } + if (result is Readiness.Result.Withheld) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text("Why there's no score today", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) + result.reasons.forEach { Text("• $it", fontSize = 13.sp, color = PulseColors.textSecondary) } + } + } + + DataBehindScore(db, result) + Text(ReadinessCopy.DERIVED_FOOTER, fontSize = 12.sp, color = PulseColors.textMuted) Spacer(Modifier.height(24.dp)) } @@ -371,3 +385,48 @@ fun activityHeadline(result: com.pulseloop.service.ActivityScore.Result?): Strin if (weakest != null) "There's room to move more. Start with your $weakest." else "There's room to move more today." } } + + +/** + * "Data behind this score": the readings last night's numbers stand on, anything withheld and + * why, and the formula version — so a surprising number can be checked, not just trusted. + */ +@Composable +private fun DataBehindScore(db: PulseLoopDatabase, result: Readiness.Result?) { + var open by remember { mutableStateOf(false) } + val inputs by produceState(null, result) { + value = runCatching { com.pulseloop.service.ReadinessRepository.loadInputs(db) }.getOrNull() + } + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable { open = !open }.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Data behind this score", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, modifier = Modifier.weight(1f)) + Text(if (open) "Hide" else "Show", fontSize = 13.sp, color = PulseColors.accent) + } + if (open) { + val night = inputs?.lastNight + fun line(label: String, value: String) = label to value + val rows = buildList { + if (night != null) { + add(line("Night covered by the ring", "${(night.coverage * 100).roundToInt()}%")) + add(line("Heart-rate readings", "${night.hrSamples}")) + add(line("HRV readings", "${night.hrvSamples}")) + add(line("Resting heart rate", night.restingHr?.let { "${it.roundToInt()} bpm" } ?: "not measured")) + add(line("HRV", night.hrv?.let { "${it.roundToInt()} ms" } ?: "not measured")) + } else add(line("Last night", "no sleep recorded")) + inputs?.let { add(line("Nights in your baseline", "${it.history.count { n -> n.restingHr != null || n.hrv != null }}")) } + add(line("Formula version", "${com.pulseloop.service.Algorithms.VERSION}")) + } + rows.forEach { (k, v) -> + Row(Modifier.fillMaxWidth()) { + Text(k, fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) + Text(v, fontSize = 13.sp, color = PulseColors.textPrimary) + } + } + night?.withheld?.values?.forEach { Text("Withheld: $it.", fontSize = 12.sp, color = PulseColors.warning) } + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt new file mode 100644 index 00000000..4418b481 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt @@ -0,0 +1,104 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.FindingEntity +import com.pulseloop.service.Algorithms +import com.pulseloop.service.FindingsRepository +import com.pulseloop.ui.theme.PulseColors +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +/** + * "What changed": your nights against your own normal, day by day, kept as a log. Positive changes + * are listed too. A stretch where nothing stood out says so plainly. + */ +@Composable +fun WhatChangedScreen(onBack: () -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val zone = remember { ZoneId.systemDefault() } + val today = remember { LocalDate.now() } + val from = remember { FindingsRepository.dayKey(today.minusDays(90), zone) } + LaunchedEffect(Unit) { runCatching { FindingsRepository.refresh(db) } } + val rows by remember { db.findingDao().sinceFlow(from) }.collectAsState(initial = emptyList()) + val fmt = remember { DateTimeFormatter.ofPattern("EEE d MMM") } + + Column(Modifier.fillMaxSize().background(PulseColors.background)) { + Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } + Text("What changed", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + } + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + val recentKey = FindingsRepository.dayKey(today.minusDays(2), zone) + val recent = rows.filter { it.day >= recentKey } + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text("LAST 3 DAYS", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + if (recent.isEmpty()) { + Text("Nothing stood out", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("Your nights look like your usual. That's an answer too.", fontSize = 13.sp, color = PulseColors.textSecondary) + } else { + recent.distinctBy { it.kind }.forEach { FindingRow(it) } + } + } + val older = rows.filter { it.day < recentKey }.groupBy { it.day } + if (older.isNotEmpty()) { + Text("EARLIER", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + older.forEach { (day, list) -> + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text(FindingsRepository.dateOf(day, zone).format(fmt), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) + list.forEach { FindingRow(it) } + } + } + } + Text( + "Each night is compared with your own previous four weeks once there are two weeks to compare with. " + + "Findings carry the formula version that made them (now v${Algorithms.VERSION}). Patterns, not diagnoses.", + fontSize = 11.sp, color = PulseColors.textMuted, + ) + Spacer(Modifier.height(24.dp)) + } + } +} + +@Composable +private fun FindingRow(f: FindingEntity) { + Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Box( + Modifier.padding(top = 6.dp).size(8.dp).clip(CircleShape) + .background(if (f.positive) PulseColors.accent else PulseColors.warning), + ) + Column(Modifier.weight(1f)) { + Text(f.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(f.detail, fontSize = 13.sp, color = PulseColors.textSecondary) + } + } +} diff --git a/app/src/test/java/com/pulseloop/service/FindingsTest.kt b/app/src/test/java/com/pulseloop/service/FindingsTest.kt new file mode 100644 index 00000000..82614c4e --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/FindingsTest.kt @@ -0,0 +1,40 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate + +class FindingsTest { + private val day = LocalDate.of(2026, 10, 21) + + private fun nights(n: Int, recent: (Int) -> Pair? = { null }): List = + (0 until n).map { back -> + val even = back % 2 == 0 + val (rhr, hrv) = recent(back) ?: ((if (even) 54.0 else 56.0) to (if (even) 38.0 else 42.0)) + NightSummary(day.minusDays(back.toLong()), 0, 8 * 3600_000L, 450, rhr, hrv, 1.0) + } + + @Test + fun `an ordinary month finds nothing`() { + assertTrue(Findings.forDay(day, nights(31)).isEmpty()) + } + + @Test + fun `three nights of higher resting heart rate and lower HRV are found`() { + val f = Findings.forDay(day, nights(31) { back -> if (back < 3) 62.0 to 30.0 else null }) + assertEquals(setOf(Finding.Kind.RESTING_HR_UP, Finding.Kind.HRV_DOWN), f.map { it.kind }.toSet()) + assertTrue(f.first { it.kind == Finding.Kind.RESTING_HR_UP }.detail.startsWith("62 bpm")) + } + + @Test + fun `nothing is judged without two weeks of baseline`() { + assertTrue(Findings.forDay(day, nights(10) { back -> if (back < 3) 62.0 to 30.0 else null }).isEmpty()) + } + + @Test + fun `a symptom radar sign is logged as a finding`() { + val f = Findings.forDay(day, nights(31), radar = SymptomRadar.Level.MINOR) + assertEquals(listOf(Finding.Kind.RADAR), f.map { it.kind }) + } +} diff --git a/app/src/test/java/com/pulseloop/service/ReadinessTest.kt b/app/src/test/java/com/pulseloop/service/ReadinessTest.kt index fc311c93..f574ec36 100644 --- a/app/src/test/java/com/pulseloop/service/ReadinessTest.kt +++ b/app/src/test/java/com/pulseloop/service/ReadinessTest.kt @@ -117,9 +117,20 @@ class ReadinessTest { } @Test - fun `a night without HR or HRV gives Learning rather than a sleep-only readiness`() { + fun `a night without HR or HRV is withheld rather than a sleep-only readiness`() { + // The baseline exists, so this isn't "learning": last night's readings were too poor. val r = Readiness.compute(inputs(last = night(today, rhr = null, hrv = null))) - assertTrue(r is Readiness.Result.Learning) + assertTrue(r is Readiness.Result.Withheld) + assertTrue((r as Readiness.Result.Withheld).reasons.isNotEmpty()) + } + + @Test + fun `hrv that is too sparse, flat or scattered is withheld with a reason`() { + assertTrue(hrvQuality(listOf(40.0, 42.0))!!.startsWith("Only 2 HRV readings")) + assertTrue(hrvQuality(listOf(40.0, 40.0, 40.0, 40.0))!!.contains("same value")) + assertTrue(hrvQuality(listOf(10.0, 90.0, 15.0, 80.0, 40.0))!!.contains("scattered")) + assertNull(hrvQuality(listOf(38.0, 42.0, 40.0, 45.0, 36.0))) + assertNull(hrvQuality(emptyList())) } @Test