From 8772c92b9edc0676b99d0ce95a77e4baf04b7e08 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 16:20:15 +0000 Subject: [PATCH 1/3] Add My Health: symptom radar, sleep need and debt, stress, body clock, cardio, trends, breathing Ported in approach from anikbharadwaj129/Colmi (Apache-2.0): - Sleep need learned from recovered nights, and a decayed 14-night sleep debt; readiness now scores sleep against the learned need. - Symptom Radar (temperature, resting HR, HRV, respiratory rate, inactivity against the user's last four weeks; "major" needs two nights) with Rest Mode. - Readiness gains body temperature and recovery index, optional-sensor contributors that are never reported missing on rings without the sensor. - Daytime stress zones, resilience, body clock/chronotype, cardio capacity and cardiovascular age (labelled estimates), health areas, habits, and trends by day/week/month/year. - 24h heart-rate chart coloured by sleep and workouts. - Unguided breathing sessions with before/after heart rate. - Charge-before-bed, move reminder and step-progress notifications; the move nudges are silenced in Rest Mode. - Coach scores context carries sleep need, sleep debt and the radar level. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../pulseloop/notifications/GuidanceWorker.kt | 76 ++- .../com/pulseloop/service/HealthInsights.kt | 364 ++++++++++++++ .../service/HealthInsightsRepository.kt | 260 ++++++++++ .../java/com/pulseloop/service/Readiness.kt | 76 ++- .../pulseloop/service/ReadinessRepository.kt | 6 +- .../com/pulseloop/service/ScoresContext.kt | 24 +- .../java/com/pulseloop/ui/PulseLoopApp.kt | 9 + .../com/pulseloop/ui/screens/MyHealthUi.kt | 476 ++++++++++++++++++ .../java/com/pulseloop/ui/screens/Screens.kt | 4 + .../ui/screens/SettingsSubScreens.kt | 18 + .../com/pulseloop/notifications/NudgesTest.kt | 36 ++ .../pulseloop/service/HealthInsightsTest.kt | 218 ++++++++ .../pulseloop/service/ReadinessSensorsTest.kt | 54 ++ 13 files changed, 1608 insertions(+), 13 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/HealthInsights.kt create mode 100644 app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt create mode 100644 app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt create mode 100644 app/src/test/java/com/pulseloop/notifications/NudgesTest.kt create mode 100644 app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt create mode 100644 app/src/test/java/com/pulseloop/service/ReadinessSensorsTest.kt diff --git a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt index 47c6a920..bd12de94 100644 --- a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt +++ b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt @@ -56,6 +56,25 @@ class GuidancePrefs(context: Context) { internal var lastBedtimeReminderDay: String? get() = p.getString("lastBedtimeReminderDay", null) set(v) = p.edit().putString("lastBedtimeReminderDay", v).apply() + var bedtimeBattery: Boolean + get() = p.getBoolean("bedtimeBattery", true) + set(v) = p.edit().putBoolean("bedtimeBattery", v).apply() + var inactivityAlerts: Boolean + get() = p.getBoolean("inactivityAlerts", false) + set(v) = p.edit().putBoolean("inactivityAlerts", v).apply() + var activityProgress: Boolean + get() = p.getBoolean("activityProgress", false) + set(v) = p.edit().putBoolean("activityProgress", v).apply() + + internal var lastBatteryReminderDay: String? + get() = p.getString("lastBatteryReminderDay", null) + set(v) = p.edit().putString("lastBatteryReminderDay", v).apply() + internal var lastInactivityAt: Long + get() = p.getLong("lastInactivityAt", 0L) + set(v) = p.edit().putLong("lastInactivityAt", v).apply() + internal var lastProgressDay: String? + get() = p.getString("lastProgressDay", null) + set(v) = p.edit().putString("lastProgressDay", v).apply() /** ":lunch" / ":dinner" of the last meal reminder sent. */ internal var lastMealReminder: String? get() = p.getString("lastMealReminder", null) @@ -128,9 +147,41 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork } } } + // 5. Charge before bed — the ring can't track a night it runs out on. + val bedtime = BedtimeGuidance.compute(inputs.history + listOfNotNull(night), inputs.sleepGoalMinutes, zone)?.bedtime + if (prefs.bedtimeBattery && prefs.lastBatteryReminderDay != today.toString()) { + val battery = db.deviceDao().currentReal()?.batteryPercent + val minsToBed = bedtime?.let { minutesUntil(local.toLocalTime(), it) } + if (Nudges.chargeBeforeBed(battery, minsToBed)) { + notify(ctx, ID_BATTERY, "Charge your ring before bed", "It's at $battery%. A short charge now keeps tonight's sleep tracked.") + prefs.lastBatteryReminderDay = today.toString() + } + } + + // 6 and 7 are nudges to move, so Rest Mode silences them. + val resting = com.pulseloop.service.RestMode.isOn(ctx) + val todayStart = today.atStartOfDay(zone).toInstant().toEpochMilli() + if (prefs.inactivityAlerts && !resting && now - prefs.lastInactivityAt >= 2 * 3_600_000L) { + val device = db.deviceDao().currentReal() + val buckets = db.activityBucketDao().byDay(todayStart) + val fresh = device?.lastSyncAt?.let { now - it <= 40 * 60_000L } == true && buckets.isNotEmpty() + val lastHour = buckets.filter { it.startEpoch >= now - 3_600_000L }.sumOf { it.steps } + if (Nudges.inactive(local.hour, lastHour, fresh)) { + notify(ctx, ID_INACTIVE, "Time to move", "Under 100 steps in the last hour. A few minutes on your feet helps your energy and your sleep.") + prefs.lastInactivityAt = now + } + } + if (prefs.activityProgress && !resting && prefs.lastProgressDay != today.toString()) { + val goal = db.userGoalDao().get()?.steps ?: 0 + val steps = db.activityDailyDao().byDay(todayStart)?.steps ?: 0 + Nudges.progress(local.hour, steps, goal)?.let { (title, body) -> + notify(ctx, ID_PROGRESS, title, body) + prefs.lastProgressDay = today.toString() + } + } + // 4. Meal reminder — optional, and only while nothing has been logged for that meal. if (prefs.mealReminder && db.userGoalDao().get()?.nutritionEnabled == true) { - val todayStart = today.atStartOfDay(zone).toInstant().toEpochMilli() val meals = db.mealEntryDao().byDay(todayStart).map { it.timestamp } MealReminder.due(local.toLocalTime(), meals.map { Instant.ofEpochMilli(it).atZone(zone).toLocalTime() })?.let { slot -> val key = "$today:$slot" @@ -151,6 +202,9 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork private const val ID_WEEKLY = 3002 private const val ID_BEDTIME = 3003 private const val ID_MEAL = 3004 + private const val ID_BATTERY = 3005 + private const val ID_INACTIVE = 3006 + private const val ID_PROGRESS = 3007 /** Minutes from [now] until [target] later today or, if already past, tomorrow. */ internal fun minutesUntil(now: LocalTime, target: LocalTime): Int { @@ -199,6 +253,26 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork } } +/** The decisions behind the battery, inactivity and step-progress nudges. */ +object Nudges { + /** Battery at or under 30 % between one and two and a half hours before the usual bedtime. */ + fun chargeBeforeBed(battery: Int?, minsToBed: Int?): Boolean = + battery != null && battery in 0..30 && minsToBed != null && minsToBed in 60..150 + + /** Between 09:00 and 19:59, under 100 steps in the last hour, on data synced recently enough to trust. */ + fun inactive(hour: Int, stepsLastHour: Int, dataFresh: Boolean): Boolean = + dataFresh && hour in 9..19 && stepsLastHour < 100 + + /** At 18:00–19:59, when the day is under 70 % of the step goal: how far there is still to go. */ + fun progress(hour: Int, steps: Int, goal: Int): Pair? { + if (hour !in 18..19 || goal <= 0 || steps >= goal * 0.7) return null + val left = goal - steps + val minutes = (left / 100.0).let { kotlin.math.ceil(it).toInt() } + return "${"%,d".format(left)} steps to your goal" to + "You're at ${"%,d".format(steps)} of ${"%,d".format(goal)}. About $minutes minutes of walking closes it." + } +} + /** * When a meal reminder is due: lunch from 13:30 if nothing has been logged since 11:00, dinner * from 20:30 if nothing since 17:00. Each window closes 90 minutes later so a phone that was diff --git a/app/src/main/java/com/pulseloop/service/HealthInsights.kt b/app/src/main/java/com/pulseloop/service/HealthInsights.kt new file mode 100644 index 00000000..154d47e3 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/HealthInsights.kt @@ -0,0 +1,364 @@ +package com.pulseloop.service + +import java.time.LocalDate +import java.time.ZoneId +import kotlin.math.abs +import kotlin.math.exp +import kotlin.math.roundToInt +import kotlin.math.sqrt + +/* + * Longer-range health insights, ported in approach from anikbharadwaj129/Colmi (Apache-2.0), which + * models Oura's published definitions where Oura gives them and documented research where it + * doesn't. Every number here is a PulseLoop estimate from ring data against the user's own normal, + * never a population threshold, and every surface that shows one says so. + */ + +private fun mean(v: List) = if (v.isEmpty()) null else v.average() +private fun sd(v: List): Double? { + if (v.size < 2) return null + val m = v.average() + return sqrt(v.sumOf { (it - m) * (it - m) } / v.size) +} +private fun medianOf(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 +} + +// ── Sleep need and sleep debt ───────────────────────────────────────────────────────────────── + +/** + * How much sleep this user needs: the typical length of recent nights after which their body read + * as recovered (resting HR at or below their normal, HRV at or above it). Judged on physiology, + * not on a score, because the score is what this feeds. Until five such nights in the last 30, + * the user's own sleep goal. + */ +data class SleepNeed(val minutes: Int, val isLearned: Boolean) { + companion object { + const val MIN_RECOVERED_NIGHTS = 5 + + fun estimate(nights: List, fallbackMinutes: Int, today: LocalDate): SleepNeed { + val window = nights.filter { !it.day.isAfter(today) && it.day.isAfter(today.minusDays(30)) } + val rhrBase = mean(nights.mapNotNull { it.restingHr }) + val hrvBase = mean(nights.mapNotNull { it.hrv }) + val recovered = window.mapNotNull { n -> + if (n.asleepMinutes <= 0) return@mapNotNull null + val checks = listOfNotNull( + n.restingHr?.let { v -> rhrBase?.let { v <= it } }, + n.hrv?.let { v -> hrvBase?.let { v >= it } }, + ) + if (checks.isNotEmpty() && checks.all { it }) n.asleepMinutes.toDouble() else null + } + if (recovered.size < MIN_RECOVERED_NIGHTS) return SleepNeed(fallbackMinutes, false) + return SleepNeed(medianOf(recovered)!!.roundToInt().coerceIn(390, 570), true) + } + } +} + +/** + * Accumulated shortfall over the last 14 nights: each night adds what it fell short of the need, + * or pays back its surplus, and older debt fades by 10% a night so recent nights count most. + * Needs five nights in the window, like Oura's. + */ +data class SleepDebt(val minutes: Int, val needMinutes: Int, val nights: Int) { + enum class Level(val label: String) { NONE("None"), LOW("Low"), MODERATE("Moderate"), HIGH("High") } + + val level: Level get() = when { + minutes < 15 -> Level.NONE + minutes < 120 -> Level.LOW + minutes <= 300 -> Level.MODERATE + else -> Level.HIGH + } + + companion object { + /** [asleepByDay]: the last 14 days oldest first, null for a night with no record. */ + fun compute(asleepByDay: List, need: SleepNeed): SleepDebt? { + val nights = asleepByDay.count { it != null } + if (nights < 5) return null + var debt = 0.0 + for (asleep in asleepByDay) { + debt *= 0.9 + if (asleep != null) debt = maxOf(0.0, debt + need.minutes - asleep) + } + return SleepDebt(debt.roundToInt(), need.minutes, nights) + } + + fun from(nights: List, need: SleepNeed, today: LocalDate): SleepDebt? { + val byDay = nights.associateBy { it.day } + return compute((13 downTo 0).map { byDay[today.minusDays(it.toLong())]?.asleepMinutes?.takeIf { m -> m > 0 } }, need) + } + } +} + +// ── Symptom Radar ───────────────────────────────────────────────────────────────────────────── + +/** + * Signs that something is straining the body, read the way UCSF's TemPredict and Stanford's + * wearable work do: several signals moving together against the user's own last four weeks, not + * one number crossing a line. Temperature and HRV weigh most. "Major" needs two nights in a row. + * It is never a diagnosis, and the copy says so. + */ +object SymptomRadar { + enum class Level(val label: String, val summary: String) { + NONE("No signs", "No obvious signs in your biometrics of something straining your body."), + MINOR("Minor signs", "Small signs in your biometrics of something straining your body."), + MAJOR("Major signs", "Stronger signs in your biometrics of something straining your body."), + } + + enum class Metric(val title: String, val weight: Double, val strainUp: Boolean, val minSd: Double, val unit: String) { + TEMPERATURE("Body temperature", 1.0, true, 0.15, "°C"), + TEMPERATURE_TREND("Temperature trend", 1.0, true, 0.12, "°C"), + RESTING_HR("Resting heart rate", 0.8, true, 1.5, "bpm"), + HRV("Heart rate variability", 1.0, false, 3.0, "ms"), + RESPIRATORY_RATE("Respiratory rate", 0.8, true, 0.5, "/min"), + INACTIVE("Inactivity", 0.5, false, 800.0, "steps"), + } + + data class Signal(val metric: Metric, val value: Double, val usual: Double, val z: Double) { + /** Strain-direction deviations of 1.5 SD or more count as a sign. */ + val flagged: Boolean get() = z >= 1.5 + val detail: String get() { + val fmt = { v: Double -> if (metric.unit == "steps") "%,d".format(v.roundToInt()) else "%.1f".format(v) } + val dir = if ((value > usual) == metric.strainUp) (if (metric.strainUp) "higher" else "lower") else "in range" + return "${fmt(value)} ${metric.unit}, $dir than your usual ${fmt(usual)}" + } + } + + data class Result(val level: Level, val signals: List, val strain: Double, val baselineNights: Int) { + val flagged: List get() = signals.filter { it.flagged } + } + + data class Night( + val day: LocalDate, + val temperature: Double? = null, + val restingHr: Double? = null, + val hrv: Double? = null, + val respiratoryRate: Double? = null, + /** Steps the day before the night (low = inactive). */ + val stepsDayBefore: Double? = null, + ) + + const val MIN_BASELINE = 14 + + /** Signals for [night] against the 28 nights before it. */ + fun signals(night: Night, history: List): List { + val base = history.filter { it.day.isBefore(night.day) && it.day.isAfter(night.day.minusDays(29)) } + fun signal(metric: Metric, value: Double?, past: List): Signal? { + if (value == null || past.size < MIN_BASELINE / 2) return null + val m = past.average() + val s = maxOf(sd(past) ?: 0.0, metric.minSd) + val z = (value - m) / s * (if (metric.strainUp) 1 else -1) + return Signal(metric, value, m, z) + } + val recentTemps = (listOf(night) + history.filter { it.day.isBefore(night.day) }.sortedByDescending { it.day }) + .take(3).mapNotNull { it.temperature } + return listOfNotNull( + signal(Metric.TEMPERATURE, night.temperature, base.mapNotNull { it.temperature }), + signal(Metric.TEMPERATURE_TREND, recentTemps.takeIf { it.size == 3 }?.average(), base.mapNotNull { it.temperature }), + signal(Metric.RESTING_HR, night.restingHr, base.mapNotNull { it.restingHr }), + signal(Metric.HRV, night.hrv, base.mapNotNull { it.hrv }), + signal(Metric.RESPIRATORY_RATE, night.respiratoryRate, base.mapNotNull { it.respiratoryRate }), + signal(Metric.INACTIVE, night.stepsDayBefore, base.mapNotNull { it.stepsDayBefore }), + ) + } + + private fun strain(signals: List) = signals.filter { it.flagged }.sumOf { it.metric.weight * minOf(it.z, 4.0) / 1.5 } + + private fun levelFor(signals: List): Level { + val flagged = signals.filter { it.flagged } + val s = strain(signals) + return when { + flagged.size >= 3 || s >= 3.0 -> Level.MAJOR + flagged.size >= 2 || s >= 1.8 -> Level.MINOR + else -> Level.NONE + } + } + + /** Today's radar: "major" only when the night before also showed signs. */ + fun compute(nights: List, today: LocalDate): Result? { + val sorted = nights.sortedBy { it.day } + val last = sorted.lastOrNull { it.day == today } ?: return null + val baseCount = sorted.count { it.day.isBefore(today) && (it.restingHr != null || it.hrv != null) } + if (baseCount < MIN_BASELINE) return Result(Level.NONE, emptyList(), 0.0, baseCount) + val sig = signals(last, sorted) + var level = levelFor(sig) + if (level == Level.MAJOR) { + val prev = sorted.lastOrNull { it.day == today.minusDays(1) } + val prevLevel = prev?.let { levelFor(signals(it, sorted)) } ?: Level.NONE + if (prevLevel == Level.NONE) level = Level.MINOR + } + return Result(level, sig, strain(sig), baseCount) + } +} + +// ── Stress: daytime zones, resilience ───────────────────────────────────────────────────────── + +/** The day's stress readings in Oura's four zones (the ring logs 1–100). */ +data class DaytimeStress(val restoredMin: Int, val relaxedMin: Int, val engagedMin: Int, val stressedMin: Int) { + enum class Summary(val label: String) { RESTORED("Restored"), NORMAL("Normal"), STRESSFUL("Stressful") } + + val totalMin: Int get() = restoredMin + relaxedMin + engagedMin + stressedMin + val summary: Summary get() = when { + totalMin == 0 -> Summary.NORMAL + stressedMin > restoredMin + 30 && stressedMin >= totalMin * 0.25 -> Summary.STRESSFUL + restoredMin >= stressedMin * 2 && restoredMin >= totalMin * 0.3 -> Summary.RESTORED + else -> Summary.NORMAL + } + + companion object { + /** [samples] are stress readings (1–100) during the waking day; each stands for [slotMin] minutes. */ + fun compute(samples: List, slotMin: Int = 30): DaytimeStress? { + val v = samples.filter { it in 1.0..100.0 } + if (v.size < 3) return null + fun count(r: ClosedFloatingPointRange) = v.count { it in r } * slotMin + return DaytimeStress(count(1.0..29.999), count(30.0..59.999), count(60.0..79.999), count(80.0..100.0)) + } + } +} + +/** + * How well the body recovers from stress over the last 14 days: daytime stress against daytime + * recovery and the nights' restoration (HRV relative to normal). Oura's five levels. + */ +data class Resilience(val level: Level, val daysUsed: Int) { + enum class Level(val label: String) { LIMITED("Limited"), ADEQUATE("Adequate"), SOLID("Solid"), STRONG("Strong"), EXCEPTIONAL("Exceptional") } + + data class Day(val stressedMin: Int, val restoredMin: Int, val hrvRatio: Double?) + + companion object { + fun compute(days: List): Resilience? { + if (days.size < 5) return null + val stress = days.sumOf { it.stressedMin }.toDouble() + val restore = days.sumOf { it.restoredMin }.toDouble() + val dayBalance = if (stress + restore == 0.0) 0.5 else restore / (stress + restore) + val night = days.mapNotNull { it.hrvRatio }.takeIf { it.size >= 3 }?.average()?.let { ((it - 0.85) / 0.3).coerceIn(0.0, 1.0) } ?: 0.5 + val score = 0.6 * dayBalance + 0.4 * night + val level = when { + score >= 0.8 -> Level.EXCEPTIONAL + score >= 0.65 -> Level.STRONG + score >= 0.5 -> Level.SOLID + score >= 0.35 -> Level.ADEQUATE + else -> Level.LIMITED + } + return Resilience(level, days.size) + } + } +} + +// ── Body clock ──────────────────────────────────────────────────────────────────────────────── + +/** Chronotype from the usual sleep midpoint, and whether recent nights keep to it. */ +data class BodyClock(val chronotype: Chronotype, val usualMidpointMin: Int, val recentShiftMin: Int, val alignment: Alignment) { + enum class Chronotype(val label: String) { EARLY("Early bird"), MORNING("Morning type"), INTERMEDIATE("In between"), EVENING("Evening type"), LATE("Night owl") } + enum class Alignment(val label: String) { ALIGNED("In sync"), SLIGHTLY_OFF("Slightly off"), MISALIGNED("Out of sync") } + + /** "3:15" for a midpoint in minutes past midnight. */ + fun midpointLabel(): String { + val m = ((usualMidpointMin % 1440) + 1440) % 1440 + return "%d:%02d".format(m / 60, m % 60) + } + + companion object { + fun compute(nights: List, zone: ZoneId = ZoneId.systemDefault()): BodyClock? { + val sorted = nights.sortedByDescending { it.day } + if (sorted.size < 10) return null + val mids = sorted.map { it.midpointMinutes(zone).toDouble() } + val usual = medianOf(mids.drop(7).ifEmpty { mids })!! + val recent = mids.take(7).average() + val shift = (recent - usual).roundToInt() + val chronotype = when { + usual < 150 -> Chronotype.EARLY + usual < 195 -> Chronotype.MORNING + usual < 255 -> Chronotype.INTERMEDIATE + usual < 315 -> Chronotype.EVENING + else -> Chronotype.LATE + } + val alignment = when { + abs(shift) < 30 -> Alignment.ALIGNED + abs(shift) < 60 -> Alignment.SLIGHTLY_OFF + else -> Alignment.MISALIGNED + } + return BodyClock(chronotype, usual.roundToInt(), shift, alignment) + } + } +} + +// ── Cardio capacity and cardiovascular age ──────────────────────────────────────────────────── + +/** + * VO₂max estimated from resting and maximum heart rate (Uth et al., 2004: 15.3 × HRmax/HRrest, + * HRmax = 208 − 0.7 × age), and a cardiovascular age read off where that and HRV sit against + * age norms. Both are coarse estimates — Oura uses pulse-wave velocity, which needs a raw PPG + * waveform this ring doesn't share — and are labelled so. A ring's own VO₂max wins when present. + */ +data class CardioCapacity(val vo2max: Double, val level: Level, val fromRing: Boolean, val cardioAge: Int?) { + enum class Level(val label: String) { LOW("Below average"), AVERAGE("Average"), GOOD("Good"), EXCELLENT("Excellent") } + + companion object { + fun expectedVo2(age: Int, female: Boolean): Double = (if (female) 42.0 else 48.0) - 0.32 * (age - 25).coerceAtLeast(0) + + fun compute(restingHr: Double?, hrv: Double?, age: Int?, sex: String?, ringVo2: Double? = null): CardioCapacity? { + if (age == null || age !in 15..100) return null + val female = sex?.lowercase() == "female" + val vo2 = ringVo2?.takeIf { it in 15.0..90.0 } + ?: restingHr?.takeIf { it in 35.0..110.0 }?.let { 15.3 * (208 - 0.7 * age) / it } + ?: return null + val expected = expectedVo2(age, female) + val ratio = vo2 / expected + val level = when { + ratio >= 1.2 -> Level.EXCELLENT + ratio >= 1.05 -> Level.GOOD + ratio >= 0.9 -> Level.AVERAGE + else -> Level.LOW + } + // Each ~0.32 ml/kg/min of VO₂max is about a year of age; HRV nudges it ±3 years. + var cardioAge = age - (vo2 - expected) / 0.32 + if (hrv != null) { + val expectedHrv = (75 - 0.9 * age).coerceAtLeast(15.0) + cardioAge -= ((hrv - expectedHrv) / expectedHrv * 6).coerceIn(-3.0, 3.0) + } + return CardioCapacity(vo2, level, ringVo2 != null, cardioAge.roundToInt().coerceIn(18, 100)) + } + } +} + +// ── Health areas ────────────────────────────────────────────────────────────────────────────── + +/** A long-term area rated on Oura's scale, from a 0–100 score over the last 90 days. */ +data class HealthArea(val title: String, val rating: Rating, val score: Int, val trend: List, val detail: String) { + enum class Rating(val label: String) { THRIVING("Thriving"), GOOD("Good"), FAIR("Fair"), NEEDS_CARE("Needs care") } + + companion object { + fun rate(score: Int): Rating = when { + score >= 80 -> Rating.THRIVING + score >= 65 -> Rating.GOOD + score >= 50 -> Rating.FAIR + else -> Rating.NEEDS_CARE + } + + /** A smooth 0–100 from a ratio of value to target, with 1.0 at about 85. */ + fun scoreOf(ratio: Double): Int = (100 / (1 + exp(-4 * (ratio - 0.6)))).roundToInt().coerceIn(0, 100) + } +} + +// ── Trends ──────────────────────────────────────────────────────────────────────────────────── + +/** Averages a daily series by week, month or year for the Trends view. */ +object Trends { + enum class Period(val label: String, val days: Long) { DAY("Day", 30), WEEK("Week", 7 * 26), MONTH("Month", 365), YEAR("Year", 365 * 3) } + + data class Point(val start: LocalDate, val value: Double) + + fun aggregate(daily: Map, period: Period): List { + val grouped = daily.entries.groupBy { (d, _) -> + when (period) { + Period.DAY -> d + Period.WEEK -> d.minusDays((d.dayOfWeek.value - 1).toLong()) + Period.MONTH -> d.withDayOfMonth(1) + Period.YEAR -> d.withDayOfYear(1) + } + } + return grouped.map { (k, v) -> Point(k, v.map { it.value }.average()) }.sortedBy { it.start } + } +} diff --git a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt new file mode 100644 index 00000000..46cf1f4a --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt @@ -0,0 +1,260 @@ +package com.pulseloop.service + +import android.content.Context +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.BodyMeasurementEntity +import com.pulseloop.ring.MeasurementKind +import org.json.JSONArray +import org.json.JSONObject +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import kotlin.math.roundToInt + +/** Rest Mode: the user says they're unwell or recovering, so activity nudges stand down. */ +object RestMode { + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences("rest_mode", Context.MODE_PRIVATE) + + /** Rest Mode lasts until the end of [untilDay]; null when off. */ + fun until(c: Context): LocalDate? = prefs(c).getString("until", null)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } + ?.takeIf { !it.isBefore(LocalDate.now()) } + + fun isOn(c: Context): Boolean = until(c) != null + + fun set(c: Context, days: Int?) { + prefs(c).edit().apply { + if (days == null) remove("until") else putString("until", LocalDate.now().plusDays((days - 1).toLong()).toString()) + }.apply() + } +} + +/** Unguided breathing / meditation sessions, kept on the phone. */ +object MindfulSessions { + data class Session(val startAt: Long, val endAt: Long, val avgHr: Int?, val startHr: Int?, val endHr: Int?) { + val minutes: Int get() = ((endAt - startAt) / 60_000L).toInt() + } + + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences("mindful_sessions", Context.MODE_PRIVATE) + + fun all(c: Context): List = runCatching { + val arr = JSONArray(prefs(c).getString("sessions", "[]")) + (0 until arr.length()).map { i -> + val o = arr.getJSONObject(i) + Session(o.getLong("s"), o.getLong("e"), o.optInt("hr", -1).takeIf { it > 0 }, o.optInt("h0", -1).takeIf { it > 0 }, o.optInt("h1", -1).takeIf { it > 0 }) + } + }.getOrDefault(emptyList()) + + fun add(c: Context, s: Session) { + val list = (all(c) + s).takeLast(500) + val arr = JSONArray() + list.forEach { x -> + arr.put(JSONObject().put("s", x.startAt).put("e", x.endAt) + .put("hr", x.avgHr ?: -1).put("h0", x.startHr ?: -1).put("h1", x.endHr ?: -1)) + } + prefs(c).edit().putString("sessions", arr.toString()).apply() + } + + /** + * Saves a finished session with the heart rate the ring recorded during it, and ticks the + * day's "Meditation or relaxing" journal tag so its effect on the night shows up. + */ + suspend fun finish(c: Context, db: PulseLoopDatabase, startAt: Long, endAt: Long): Session { + val hr = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, startAt, endAt + 60_000L) + .map { it.value }.filter { it in 30.0..220.0 } + val s = Session(startAt, endAt, hr.takeIf { it.isNotEmpty() }?.average()?.roundToInt(), hr.firstOrNull()?.roundToInt(), hr.lastOrNull()?.roundToInt()) + add(c, s) + runCatching { + val zone = ZoneId.systemDefault() + val day = Instant.ofEpochMilli(startAt).atZone(zone).toLocalDate().atStartOfDay(zone).toInstant().toEpochMilli() + val tag = JournalInsights.Tag.RELAXATION.key + db.journalDao().upsert(com.pulseloop.data.entity.JournalEntryEntity(com.pulseloop.data.entity.JournalEntryEntity.idFor(day, tag), day, tag)) + } + return s + } +} + +/** Everything the My Health screen shows, loaded together. */ +object HealthInsightsRepository { + + data class Habits( + val bedtime: String?, + val wake: String?, + val sleepMin: Int?, + val steps: Int?, + val activeMin: Int?, + val restingHr: Double?, + ) + + data class Snapshot( + val nights: List, + val need: SleepNeed, + val debt: SleepDebt?, + val radar: SymptomRadar.Result?, + val todayStress: DaytimeStress?, + val resilience: Resilience?, + val bodyClock: BodyClock?, + val cardio: CardioCapacity?, + val areas: List, + val habits: Habits, + val hrToday: List, + val sleepWindows: List, + val workoutWindows: List, + ) + + private const val DAY = 86_400_000L + + suspend fun load(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): Snapshot { + val inputs = ReadinessRepository.loadInputs(db, now, zone) + val nights = (inputs.history + listOfNotNull(inputs.lastNight)).sortedBy { it.day } + val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + fun start(d: LocalDate) = d.atStartOfDay(zone).toInstant().toEpochMilli() + val goal = db.userGoalDao().get() + val profile = db.userProfileDao().get() + + val need = SleepNeed.estimate(nights, goal?.sleepMinutes ?: 480, today) + val debt = SleepDebt.from(nights, need, today) + + // Activity per day (steps), and night respiratory rate where the ring logs it. + val days = db.activityDailyDao().recentReal(120).associateBy { Instant.ofEpochMilli(it.date).atZone(zone).toLocalDate() } + val resp = db.measurementDao().rangeReal(MeasurementKind.RESPIRATORY_RATE.name, start(today.minusDays(60)), now) + val radarNights = nights.map { n -> + SymptomRadar.Night( + day = n.day, + temperature = n.temperature, + restingHr = n.restingHr, + hrv = n.hrv, + respiratoryRate = resp.filter { it.timestamp in n.startAt..n.endAt }.map { it.value }.takeIf { it.size >= 2 }?.average(), + stepsDayBefore = days[n.day.minusDays(1)]?.steps?.takeIf { it > 0 }?.toDouble(), + ) + } + val radar = SymptomRadar.compute(radarNights, today) + + // Stress: today's daytime readings, and 14 days for resilience. + val stressRows = db.measurementDao().rangeReal(MeasurementKind.STRESS.name, start(today.minusDays(14)), now) + val nightByDay = nights.associateBy { it.day } + fun daytime(d: LocalDate) = stressRows.filter { + val t = Instant.ofEpochMilli(it.timestamp).atZone(zone) + t.toLocalDate() == d && t.hour in 8..21 + }.map { it.value } + val todayStress = DaytimeStress.compute(daytime(today)) + val hrvBase = nights.mapNotNull { it.hrv }.takeIf { it.size >= 7 }?.average() + val resilience = Resilience.compute((1..14).mapNotNull { back -> + val d = today.minusDays(back.toLong()) + val z = DaytimeStress.compute(daytime(d)) ?: return@mapNotNull null + Resilience.Day(z.stressedMin, z.restoredMin, nightByDay[d.plusDays(1)]?.hrv?.let { h -> hrvBase?.let { h / it } }) + }) + + val bodyClock = BodyClock.compute(nights, zone) + val recent = nights.takeLast(30) + val ringVo2 = db.measurementDao().rangeReal(MeasurementKind.VO2MAX.name, start(today.minusDays(90)), now).lastOrNull()?.value + val cardio = CardioCapacity.compute( + restingHr = recent.mapNotNull { it.restingHr }.takeIf { it.size >= 5 }?.average(), + hrv = recent.mapNotNull { it.hrv }.takeIf { it.size >= 5 }?.average(), + age = profile?.age, sex = profile?.sex, ringVo2 = ringVo2, + ) + + // Long-term areas, with weekly trend lines. + fun weekly(f: (NightSummary) -> Double?): List = nights.groupBy { it.day.toEpochDay() / 7 }.toSortedMap() + .values.mapNotNull { w -> w.mapNotNull(f).takeIf { it.isNotEmpty() }?.average() } + val areas = buildList { + val asleep = nights.filter { it.asleepMinutes > 0 }.takeLast(60) + if (asleep.size >= 7) { + val ratio = asleep.map { it.asleepMinutes }.average() / need.minutes + val mids = asleep.map { it.midpointMinutes(zone).toDouble() } + val m = mids.average() + val spread = kotlin.math.sqrt(mids.sumOf { (it - m) * (it - m) } / mids.size) + val regularity = Readiness.curve(spread, listOf(30.0 to 100.0, 60.0 to 75.0, 120.0 to 25.0)) + val score = (0.7 * HealthArea.scoreOf(ratio) + 0.3 * regularity).roundToInt() + add(HealthArea("Sleep health", HealthArea.rate(score), score, + weekly { n -> n.asleepMinutes.takeIf { it > 0 }?.div(60.0) }, + "Averaging ${SleepFormat.duration(asleep.map { it.asleepMinutes }.average().roundToInt())} against a need of ${SleepFormat.duration(need.minutes)}")) + } + resilience?.let { r -> + val score = when (r.level) { + Resilience.Level.LIMITED -> 35; Resilience.Level.ADEQUATE -> 52; Resilience.Level.SOLID -> 66 + Resilience.Level.STRONG -> 80; Resilience.Level.EXCEPTIONAL -> 92 + } + val trend = stressRows.groupBy { Instant.ofEpochMilli(it.timestamp).atZone(zone).toLocalDate() } + .toSortedMap().values.map { d -> d.map { it.value }.average() } + add(HealthArea("Stress management", HealthArea.rate(score), score, trend, "Resilience ${r.level.label.lowercase()} over ${r.daysUsed} days")) + } + cardio?.let { c -> + 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" } ?: ""))) + } + } + + // Habits: rolling 30-day averages. + val last30 = nights.filter { it.day.isAfter(today.minusDays(31)) } + fun clock(ms: List): String? { + if (ms.size < 3) return null + // Average around 18:00 so times either side of midnight average correctly. + val mins = ms.map { val t = Instant.ofEpochMilli(it).atZone(zone).toLocalTime(); ((t.hour * 60 + t.minute) - 1080 + 1440) % 1440 } + val avg = (mins.average().roundToInt() + 1080) % 1440 + return "%d:%02d".format(avg / 60, avg % 60) + } + val act30 = db.activityDailyDao().recentReal(31).filter { it.date < start(today) } + val habits = Habits( + bedtime = clock(last30.map { it.startAt }), + wake = clock(last30.map { it.endAt }), + sleepMin = last30.map { it.asleepMinutes }.filter { it > 0 }.takeIf { it.isNotEmpty() }?.average()?.roundToInt(), + steps = act30.map { it.steps }.filter { it > 0 }.takeIf { it.isNotEmpty() }?.average()?.roundToInt(), + activeMin = act30.map { it.activeMinutes }.filter { it > 0 }.takeIf { it.isNotEmpty() }?.average()?.roundToInt(), + restingHr = last30.mapNotNull { it.restingHr }.takeIf { it.isNotEmpty() }?.average(), + ) + + // Today's heart rate with its context. + val dayStart = start(today) + val hrToday = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, dayStart - 6 * 3_600_000L, now) + .map { VitalSample(it.timestamp, it.value) }.filter { it.value in 30.0..220.0 } + val sleepWindows = nights.filter { it.endAt >= dayStart - 6 * 3_600_000L }.map { it.startAt..it.endAt } + val workoutWindows = db.activitySessionDao().recent(20) + .filter { it.statusRaw == "finished" && (it.endedAt ?: 0) >= dayStart - 6 * 3_600_000L } + .map { it.startedAt..(it.endedAt ?: it.startedAt) } + + return Snapshot(nights, need, debt, radar, todayStress, resilience, bodyClock, cardio, areas, habits, hrToday, sleepWindows, workoutWindows) + } + + // ── Trends ─────────────────────────────────────────────────────────────── + + enum class TrendMetric(val label: String, val unit: String) { + SLEEP("Sleep", "h"), STEPS("Steps", ""), ACTIVE("Active minutes", "min"), RESTING_HR("Resting HR", "bpm"), + HRV("HRV", "ms"), STRESS("Stress", ""), SPO2("Blood oxygen", "%"), TEMPERATURE("Temperature", "°C"), WEIGHT("Weight", "kg"), + } + + /** One value per day for [metric] over the last [days]. */ + suspend fun daily(db: PulseLoopDatabase, metric: TrendMetric, days: Long, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): Map { + val from = now - days * DAY + fun dayOf(ms: Long) = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate() + suspend fun dailyMean(kind: MeasurementKind, range: ClosedFloatingPointRange) = + db.measurementDao().rangeReal(kind.name, from, now).filter { it.value in range } + .groupBy { dayOf(it.timestamp) }.mapValues { (_, v) -> v.map { it.value }.average() } + return when (metric) { + TrendMetric.SLEEP -> db.sleepSessionDao().inRangeReal(from, now).filter { it.totalMinutes > 0 } + .groupBy { dayOf(it.date) }.mapValues { (_, s) -> s.maxOf { it.totalMinutes } / 60.0 } + TrendMetric.STEPS -> db.activityDailyDao().recentReal(days.toInt()).filter { it.steps > 0 } + .associate { dayOf(it.date) to it.steps.toDouble() } + TrendMetric.ACTIVE -> db.activityDailyDao().recentReal(days.toInt()).filter { it.activeMinutes > 0 } + .associate { dayOf(it.date) to it.activeMinutes.toDouble() } + TrendMetric.RESTING_HR, TrendMetric.HRV -> { + val kind = if (metric == TrendMetric.HRV) MeasurementKind.HRV else MeasurementKind.HEART_RATE + val sessions = db.sleepSessionDao().inRangeReal(from, now).filter { it.totalMinutes > 0 } + .groupBy { it.date }.mapValues { (_, s) -> s.maxBy { it.totalMinutes } }.values + sessions.mapNotNull { s -> + val samples = db.measurementDao().rangeReal(kind.name, s.startAt, s.endAt).map { VitalSample(it.timestamp, it.value) } + val n = NightlyVitals.summarize(dayOf(s.date), s.startAt, s.endAt, s.totalMinutes, + if (kind == MeasurementKind.HEART_RATE) samples else emptyList(), + if (kind == MeasurementKind.HRV) samples else emptyList()) + (if (metric == TrendMetric.HRV) n.hrv else n.restingHr)?.let { n.day to it } + }.toMap() + } + TrendMetric.STRESS -> dailyMean(MeasurementKind.STRESS, 1.0..100.0) + TrendMetric.SPO2 -> dailyMean(MeasurementKind.SPO2, 70.0..100.0) + TrendMetric.TEMPERATURE -> dailyMean(MeasurementKind.TEMPERATURE, 30.0..42.0) + TrendMetric.WEIGHT -> db.bodyMeasurementDao().since(BodyMeasurementEntity.TYPE_WEIGHT, from) + .groupBy { dayOf(it.measuredAt) }.mapValues { (_, v) -> v.last().value } + } + } +} diff --git a/app/src/main/java/com/pulseloop/service/Readiness.kt b/app/src/main/java/com/pulseloop/service/Readiness.kt index b924e060..1986ae11 100644 --- a/app/src/main/java/com/pulseloop/service/Readiness.kt +++ b/app/src/main/java/com/pulseloop/service/Readiness.kt @@ -79,6 +79,10 @@ data class NightSummary( val coverage: Double, /** Median SpO₂ inside the sleep window (70–100 only), or null when too few readings. */ val spo2: Double? = null, + /** Median skin temperature inside the sleep window (°C), null on rings without the sensor. */ + val temperature: Double? = null, + /** When the night's sustained lowest heart rate happened (recovery index). */ + val minHrAt: Long? = null, ) { /** Clock midpoint of the night, in minutes past local midnight of the waking day (may be negative). */ fun midpointMinutes(zone: ZoneId): Int { @@ -102,6 +106,7 @@ object NightlyVitals { heartRate: List, hrv: List, spo2: List = emptyList(), + temperature: List = emptyList(), ): NightSummary { fun inNight(s: VitalSample) = s.timestampMs in startAt..endAt && s.value > 0 val hr = ReadingQuality.dropSpikes(heartRate.filter(::inNight)) @@ -109,9 +114,9 @@ object NightlyVitals { // Lowest 3-sample rolling mean, not the single lowest sample: Oura's "lowest heart rate" // is a sustained low, and one dropped beat must not set the night's number. - val restingHr = if (hr.size >= MIN_HR_SAMPLES) { - hr.map { it.value }.windowed(3).minOf { it.average() } - } else null + val windows = hr.windowed(3) + 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 @@ -128,6 +133,10 @@ object NightlyVitals { spo2 = spo2.filter { it.timestampMs in startAt..endAt && it.value in 70.0..100.0 } .takeIf { it.size >= MIN_HRV_SAMPLES } ?.let { s -> median(s.map { it.value }) }?.let { (it * 10).roundToInt() / 10.0 }, + temperature = temperature.filter { it.timestampMs in startAt..endAt && it.value in 30.0..42.0 } + .takeIf { it.size >= MIN_HRV_SAMPLES } + ?.let { s -> median(s.map { it.value }) }?.let { (it * 100).roundToInt() / 100.0 }, + minHrAt = lowest?.get(1)?.timestampMs, ) } } @@ -153,11 +162,18 @@ object Readiness { } } - enum class ContributorKind(val title: String, val weight: Double) { - RESTING_HR("Resting heart rate", 0.20), - HRV_BALANCE("HRV balance", 0.20), - SLEEP("Sleep", 0.20), - SLEEP_BALANCE("Sleep balance", 0.15), + /** + * Oura's nine contributors. Body temperature and recovery index need a temperature sensor and + * dense night heart rate; when a ring never provides them they are left out (not "missing") + * and the rest are renormalised. + */ + enum class ContributorKind(val title: String, val weight: Double, val optionalSensor: Boolean = false) { + RESTING_HR("Resting heart rate", 0.15), + HRV_BALANCE("HRV balance", 0.15), + BODY_TEMPERATURE("Body temperature", 0.10, optionalSensor = true), + RECOVERY_INDEX("Recovery index", 0.10, optionalSensor = true), + SLEEP("Sleep", 0.15), + SLEEP_BALANCE("Sleep balance", 0.10), SLEEP_REGULARITY("Sleep regularity", 0.05), PREVIOUS_DAY_ACTIVITY("Previous day activity", 0.10), ACTIVITY_BALANCE("Activity balance", 0.10), @@ -214,6 +230,8 @@ object Readiness { val contributors = listOfNotNull( restingHr(night, inputs.history), hrvBalance(night, inputs.history), + bodyTemperature(night, inputs.history), + recoveryIndex(night), sleep(night, inputs.sleepGoalMinutes), sleepBalance(night, inputs.history, inputs.sleepGoalMinutes), sleepRegularity(night, inputs.history, inputs.zone), @@ -231,11 +249,23 @@ object Readiness { return Result.Score( value = value, contributors = contributors, - missing = ContributorKind.entries.filter { it !in present }, + missing = ContributorKind.entries.filter { k -> + k !in present && !(k.optionalSensor && !sensorSeen(k, night, inputs.history)) + }, nightCoverage = night.coverage, ) } + /** Whether the ring has ever supplied what an optional-sensor contributor needs. */ + private fun sensorSeen(k: ContributorKind, night: NightSummary, history: List): Boolean = + (listOf(night) + history).any { + when (k) { + ContributorKind.BODY_TEMPERATURE -> it.temperature != null + ContributorKind.RECOVERY_INDEX -> it.minHrAt != null + else -> true + } + } + // ── Contributors ───────────────────────────────────────────────────────────────────────── // Each maps a deviation from the user's own baseline onto 0–100 with a piecewise-linear curve: // a band around "usual" scores full marks, and the score falls off as the night moves away. @@ -276,6 +306,34 @@ object Readiness { return Contributor(ContributorKind.HRV_BALANCE, score, detail) } + /** Skin temperature against the user's usual: within ±0.3 °C is full marks, either way off costs. */ + internal fun bodyTemperature(night: NightSummary, history: List): Contributor? { + val t = night.temperature ?: return null + val base = median(history.mapNotNull { it.temperature }.takeIf { it.size >= MIN_BASELINE_NIGHTS }) ?: return null + val delta = t - base + val score = curve(abs(delta), listOf(0.3 to 100.0, 0.5 to 80.0, 1.0 to 45.0, 1.5 to 15.0)) + val detail = when { + abs(delta) < 0.1 -> "At your usual" + delta > 0 -> "+%.1f °C from your usual".format(delta) + else -> "−%.1f °C from your usual".format(-delta) + } + return Contributor(ContributorKind.BODY_TEMPERATURE, score, detail) + } + + /** + * How early in the night the heart rate bottomed out. Oura: the lowest heart rate in the first + * half of the night means the body had time to recover; reaching it just before waking means it + * was still working (a late meal, alcohol, a hard evening session). + */ + internal fun recoveryIndex(night: NightSummary): Contributor? { + val at = night.minHrAt ?: return null + val span = (night.endAt - night.startAt).takeIf { it > 0 } ?: return null + val fraction = ((at - night.startAt).toDouble() / span).coerceIn(0.0, 1.0) + val score = curve(fraction, listOf(0.5 to 100.0, 0.7 to 75.0, 0.85 to 55.0, 1.0 to 35.0)) + val beforeWake = ((night.endAt - at) / 60_000L).toInt() + return Contributor(ContributorKind.RECOVERY_INDEX, score, "Lowest heart rate ${SleepFormat.duration(beforeWake)} before waking") + } + internal fun sleep(night: NightSummary, goalMinutes: Int): Contributor? { if (goalMinutes <= 0 || night.asleepMinutes <= 0) return null val score = sleepCurve(night.asleepMinutes.toDouble() / goalMinutes) diff --git a/app/src/main/java/com/pulseloop/service/ReadinessRepository.kt b/app/src/main/java/com/pulseloop/service/ReadinessRepository.kt index 00084e13..ef8f463f 100644 --- a/app/src/main/java/com/pulseloop/service/ReadinessRepository.kt +++ b/app/src/main/java/com/pulseloop/service/ReadinessRepository.kt @@ -49,6 +49,7 @@ object ReadinessRepository { val hr = samples(MeasurementKind.HEART_RATE) val hrv = samples(MeasurementKind.HRV) val spo2 = samples(MeasurementKind.SPO2) + val temperature = samples(MeasurementKind.TEMPERATURE) val nights = sessions.map { s -> val day = Instant.ofEpochMilli(s.date).atZone(zone).toLocalDate() @@ -60,6 +61,7 @@ object ReadinessRepository { heartRate = hr.filter { it.timestampMs in s.startAt..s.endAt }, hrv = hrv.filter { it.timestampMs in s.startAt..s.endAt }, spo2 = spo2.filter { it.timestampMs in s.startAt..s.endAt }, + temperature = temperature.filter { it.timestampMs in s.startAt..s.endAt }, ) } val lastNight = nights.firstOrNull { it.day == today } @@ -72,7 +74,9 @@ object ReadinessRepository { return Readiness.Inputs( lastNight = lastNight, history = nights.filter { it.day != today && it.day.isBefore(today) }, - sleepGoalMinutes = db.userGoalDao().get()?.sleepMinutes ?: 480, + // Sleep is scored against what this user needs once that is learned (SleepNeed), the + // goal until then. + sleepGoalMinutes = SleepNeed.estimate(nights, db.userGoalDao().get()?.sleepMinutes ?: 480, today).minutes, dailySteps = dailySteps, zone = zone, ) diff --git a/app/src/main/java/com/pulseloop/service/ScoresContext.kt b/app/src/main/java/com/pulseloop/service/ScoresContext.kt index d24f5ad8..91c7d51c 100644 --- a/app/src/main/java/com/pulseloop/service/ScoresContext.kt +++ b/app/src/main/java/com/pulseloop/service/ScoresContext.kt @@ -20,13 +20,33 @@ data class ScoresContext( val lastNightCoveragePct: Int? = null, val activityScore: Int? = null, val activityBand: String? = null, + /** Learned nightly sleep need, and the decayed 14-night shortfall against it. */ + val sleepNeedMinutes: Int? = null, + val sleepDebtMinutes: Int? = null, + val sleepDebtLevel: String? = null, + /** Symptom Radar: "No signs", "Minor signs" or "Major signs" of strain, with the flagged signals. */ + val symptomRadar: String? = null, + val symptomRadarSignals: List = emptyList(), val note: String = "Scores are PulseLoop estimates from ring data compared with the user's own baseline, not medical measurements.", ) { /** Short stable string for coach-summary regeneration signatures. */ - fun signature(): String = listOf(readinessStatus, readiness, activityScore, baselineNightsCollected).joinToString("|") + fun signature(): String = listOf(readinessStatus, readiness, activityScore, baselineNightsCollected).joinToString("|") + + "|$sleepDebtLevel|$symptomRadar" companion object { - suspend fun build(db: PulseLoopDatabase): ScoresContext? = runCatching { + suspend fun build(db: PulseLoopDatabase): ScoresContext? = + buildScores(db)?.let { base -> + val h = runCatching { HealthInsightsRepository.load(db) }.getOrNull() ?: return@let base + base.copy( + sleepNeedMinutes = h.need.minutes, + sleepDebtMinutes = h.debt?.minutes, + sleepDebtLevel = h.debt?.level?.label, + symptomRadar = h.radar?.level?.label, + symptomRadarSignals = h.radar?.signals.orEmpty().filter { it.flagged }.map { it.detail }, + ) + } + + private suspend fun buildScores(db: PulseLoopDatabase): ScoresContext? = runCatching { val activity = runCatching { ActivityScore.load(db) }.getOrNull() when (val r = ReadinessRepository.compute(db)) { is Readiness.Result.Score -> ScoresContext( diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index c90d707c..9c77a448 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -674,6 +674,15 @@ fun PulseLoopApp() { onOpenActivity = { navController.navigate("activity") { launchSingleTop = true } }, ) } + paddedComposable("my_health") { + com.pulseloop.ui.screens.MyHealthScreen( + onBack = { navController.popBackStack() }, + onBreathe = { navController.navigate("breathe") }, + ) + } + paddedComposable("breathe") { + com.pulseloop.ui.screens.BreatheScreen(onBack = { navController.popBackStack() }) + } paddedComposable("readiness") { com.pulseloop.ui.screens.ReadinessScreen(db = db, 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 new file mode 100644 index 00000000..bc6f12a5 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -0,0 +1,476 @@ +package com.pulseloop.ui.screens + +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.keyframes +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +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.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Switch +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.draw.scale +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke +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.service.BodyClock +import com.pulseloop.service.HealthArea +import com.pulseloop.service.HealthInsightsRepository +import com.pulseloop.service.HealthInsightsRepository.TrendMetric +import com.pulseloop.service.MindfulSessions +import com.pulseloop.service.RestMode +import com.pulseloop.service.SleepDebt +import com.pulseloop.service.SleepFormat +import com.pulseloop.service.SymptomRadar +import com.pulseloop.service.Trends +import com.pulseloop.service.VitalSample +import com.pulseloop.ui.theme.PulseColors +import com.pulseloop.ui.theme.dither +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +/* + * My Health: the longer view (ported in approach from anikbharadwaj129/Colmi, Apache-2.0). + * Symptom Radar and Rest Mode, long-term health areas, sleep need and debt, body clock, daytime + * stress and resilience, heart rate today in context, cardio capacity, habits, and trends by + * day / week / month / year. Every number is an estimate against the user's own normal. + */ + +@Composable +private fun Section(title: String, content: @Composable ColumnScope.() -> Unit) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + content = { + Text(title.uppercase(), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + content() + }, + ) +} + +@Composable +private fun Fact(label: String, value: String, note: String? = null, color: Color = PulseColors.textPrimary) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.Top) { + Column(Modifier.weight(1f)) { + Text(label, fontSize = 14.sp, color = PulseColors.textSecondary) + note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } + } + Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = color) + } +} + +private fun ratingColor(r: HealthArea.Rating) = when (r) { + HealthArea.Rating.THRIVING -> PulseColors.success + HealthArea.Rating.GOOD -> PulseColors.info + HealthArea.Rating.FAIR -> PulseColors.warning + HealthArea.Rating.NEEDS_CARE -> PulseColors.danger +} + +@Composable +private fun Sparkline(values: List, color: Color, modifier: Modifier = Modifier.fillMaxWidth().height(40.dp)) { + if (values.size < 2) return + Canvas(modifier) { + val min = values.min(); val max = values.max() + val range = (max - min).takeIf { it > 0 } ?: 1.0 + val path = Path() + values.forEachIndexed { i, v -> + val x = i * size.width / (values.size - 1) + val y = size.height - ((v - min) / range * size.height * 0.85 + size.height * 0.075).toFloat() + if (i == 0) path.moveTo(x, y) else path.lineTo(x, y) + } + drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round)) + } +} + +@Composable +fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + var refresh by remember { mutableIntStateOf(0) } + val snap by produceState(null, refresh) { + value = runCatching { HealthInsightsRepository.load(db) }.getOrNull() + } + var restUntil by remember { mutableStateOf(RestMode.until(context)) } + + 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("My Health", 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 s = snap + if (s == null) { + Text("Reading your history…", color = PulseColors.textMuted, fontSize = 13.sp) + } else { + RadarSection(s.radar, restUntil) { days -> + RestMode.set(context, days); restUntil = RestMode.until(context) + } + if (s.areas.isNotEmpty()) { + Section("Health areas · last 60–90 days") { + s.areas.forEach { a -> + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(a.title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(a.detail, fontSize = 12.sp, color = PulseColors.textMuted) + } + Text(a.rating.label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = ratingColor(a.rating)) + } + Sparkline(a.trend, ratingColor(a.rating)) + } + } + } + SleepSection(s) + StressSection(s, onBreathe) + HeartSection(s) + HabitsSection(s.habits) + TrendsSection(db) + Text( + "Estimates from your ring compared with your own recent normal, not medical measurements.", + fontSize = 11.sp, color = PulseColors.textMuted, + ) + Spacer(Modifier.height(24.dp)) + } + } + } +} + +@Composable +private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate?, onRest: (Int?) -> Unit) { + Section("Symptom Radar") { + if (r == null || r.baselineNights < SymptomRadar.MIN_BASELINE) { + Text("Learning your normal: ${r?.baselineNights ?: 0} of ${SymptomRadar.MIN_BASELINE} nights.", fontSize = 13.sp, color = PulseColors.textSecondary) + } else { + val color = when (r.level) { + SymptomRadar.Level.NONE -> PulseColors.success + SymptomRadar.Level.MINOR -> PulseColors.warning + SymptomRadar.Level.MAJOR -> PulseColors.danger + } + Text(r.level.label, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = color) + Text(r.level.summary, fontSize = 13.sp, color = PulseColors.textSecondary) + r.signals.forEach { sig -> + Fact(sig.metric.title, if (sig.flagged) "Elevated" else "Normal", sig.detail, + if (sig.flagged) PulseColors.warning else PulseColors.textSecondary) + } + if (r.level != SymptomRadar.Level.NONE) { + Text("Not a diagnosis. Rest, fluids and an easier day help; see a doctor if you feel unwell.", fontSize = 12.sp, color = PulseColors.textMuted) + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text("Rest Mode", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text( + restUntil?.let { "On until ${it.dayOfMonth}/${it.monthValue}: activity nudges paused, the coach eases off." } + ?: "Feeling unwell? Pause activity nudges for 3 days.", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + } + Switch(checked = restUntil != null, onCheckedChange = { on -> onRest(if (on) 3 else null) }) + } + } +} + +@Composable +private fun SleepSection(s: HealthInsightsRepository.Snapshot) { + Section("Sleep") { + Fact("Sleep need", SleepFormat.duration(s.need.minutes), + if (s.need.isLearned) "Learned from nights you woke recovered" else "Your goal, until 5 recovered nights teach the app yours") + s.debt?.let { d -> + val color = when (d.level) { + SleepDebt.Level.NONE -> PulseColors.success; SleepDebt.Level.LOW -> PulseColors.info + SleepDebt.Level.MODERATE -> PulseColors.warning; SleepDebt.Level.HIGH -> PulseColors.danger + } + Fact("Sleep debt", "${d.level.label} · ${SleepFormat.duration(d.minutes)}", "Last 14 nights, recent nights weigh more", color) + } ?: Fact("Sleep debt", "—", "Needs 5 nights in the last 2 weeks") + s.bodyClock?.let { c -> + Fact("Body clock", c.chronotype.label, "Usual sleep midpoint ${c.midpointLabel()} · this week ${c.alignment.label.lowercase()}" + + if (c.alignment != BodyClock.Alignment.ALIGNED) " (${if (c.recentShiftMin > 0) "+" else ""}${c.recentShiftMin} min)" else "") + } + } +} + +@Composable +private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> Unit) { + val context = LocalContext.current + Section("Stress") { + val z = s.todayStress + if (z == null) { + Text("No daytime stress readings today yet.", fontSize = 13.sp, color = PulseColors.textMuted) + } else { + Text("Today: ${z.summary.label}", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + val total = z.totalMin.coerceAtLeast(1).toFloat() + Row(Modifier.fillMaxWidth().height(10.dp).clip(RoundedCornerShape(2.dp))) { + listOf(z.restoredMin to PulseColors.success, z.relaxedMin to PulseColors.info, + z.engagedMin to PulseColors.warning, z.stressedMin to PulseColors.danger).forEach { (m, c) -> + if (m > 0) Box(Modifier.weight(m / total).fillMaxHeight().background(c)) + } + } + Text("Restored ${SleepFormat.duration(z.restoredMin)} · relaxed ${SleepFormat.duration(z.relaxedMin)} · engaged ${SleepFormat.duration(z.engagedMin)} · stressed ${SleepFormat.duration(z.stressedMin)}", + fontSize = 12.sp, color = PulseColors.textMuted) + } + s.resilience?.let { Fact("Resilience", it.level.label, "Daytime recovery against stress, and how well nights restore you (${it.daysUsed} days)") } + val sessions = remember { MindfulSessions.all(context) } + val week = sessions.filter { it.startAt >= System.currentTimeMillis() - 7 * 86_400_000L } + Fact("Breathing sessions this week", "${week.size} · ${week.sumOf { it.minutes }} min") + OutlinedButton(onClick = onBreathe, modifier = Modifier.fillMaxWidth()) { Text("Start a breathing session") } + } +} + +@Composable +private fun HeartSection(s: HealthInsightsRepository.Snapshot) { + Section("Heart") { + if (s.hrToday.size >= 2) { + Text("Heart rate since last night", fontSize = 13.sp, color = PulseColors.textSecondary) + HeartRateContextChart(s.hrToday, s.sleepWindows, s.workoutWindows) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Legend(PulseColors.sleep, "Sleep"); Legend(PulseColors.steps, "Workout"); Legend(PulseColors.heartRate, "Day") + } + } + 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") } + } ?: Text("Add your age in Settings → User Profile for cardio capacity.", fontSize = 12.sp, color = PulseColors.textMuted) + } +} + +@Composable +private fun Legend(color: Color, label: String) { + Row(verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.size(8.dp).clip(CircleShape).background(color)) + Spacer(Modifier.width(4.dp)) + Text(label, fontSize = 11.sp, color = PulseColors.textMuted) + } +} + +/** Heart rate over the last ~30 hours, each segment coloured by what was happening: sleep, workout, or day. */ +@Composable +fun HeartRateContextChart(samples: List, sleep: List, workouts: List) { + val sorted = remember(samples) { samples.sortedBy { it.timestampMs } } + Canvas(Modifier.fillMaxWidth().height(90.dp)) { + val t0 = sorted.first().timestampMs; val t1 = sorted.last().timestampMs.coerceAtLeast(t0 + 1) + val lo = sorted.minOf { it.value } - 5; val hi = sorted.maxOf { it.value } + 5 + fun x(t: Long) = (t - t0).toFloat() / (t1 - t0) * size.width + fun y(v: Double) = size.height - ((v - lo) / (hi - lo) * size.height).toFloat() + for (i in 1 until sorted.size) { + val a = sorted[i - 1]; val b = sorted[i] + if (b.timestampMs - a.timestampMs > 45 * 60_000L) continue // a gap, not a line + val color = when { + workouts.any { b.timestampMs in it } -> PulseColors.steps + sleep.any { b.timestampMs in it } -> PulseColors.sleep + else -> PulseColors.heartRate + } + drawLine(color, Offset(x(a.timestampMs), y(a.value)), Offset(x(b.timestampMs), y(b.value)), strokeWidth = 2.dp.toPx(), cap = StrokeCap.Round) + } + } +} + +@Composable +private fun HabitsSection(h: HealthInsightsRepository.Habits) { + Section("Habits & routines · 30-day averages") { + h.bedtime?.let { Fact("Bedtime", it) } + h.wake?.let { Fact("Wake-up", it) } + h.sleepMin?.let { Fact("Sleep", SleepFormat.duration(it)) } + h.steps?.let { Fact("Steps", "%,d".format(it)) } + h.activeMin?.let { Fact("Active minutes", "$it min") } + h.restingHr?.let { Fact("Resting heart rate", "${it.roundToInt()} bpm") } + if (listOf(h.bedtime, h.steps, h.restingHr).all { it == null }) { + Text("A few more days of data and your routines show up here.", fontSize = 12.sp, color = PulseColors.textMuted) + } + } +} + +@Composable +private fun TrendsSection(db: PulseLoopDatabase) { + var metric by remember { mutableStateOf(TrendMetric.SLEEP) } + var period by remember { mutableStateOf(Trends.Period.WEEK) } + val points by produceState?>(null, metric, period) { + value = null + value = runCatching { Trends.aggregate(HealthInsightsRepository.daily(db, metric, period.days), period) }.getOrNull() + } + Section("Trends") { + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + TrendMetric.entries.forEach { m -> + val on = m == metric + Text(m.label, fontSize = 12.sp, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + modifier = Modifier.clip(RoundedCornerShape(16.dp)) + .background(if (on) PulseColors.accent else PulseColors.cardSoft) + .clickable { metric = m }.padding(horizontal = 10.dp, vertical = 6.dp)) + } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Trends.Period.entries.forEach { p -> + val on = p == period + Text(p.label, fontSize = 12.sp, color = if (on) PulseColors.textPrimary else PulseColors.textMuted, + fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, + modifier = Modifier.weight(1f).clip(RoundedCornerShape(4.dp)) + .then(if (on) Modifier.dither(PulseColors.accent, 0.18f) else Modifier) + .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(4.dp)) + .clickable { period = p }.padding(vertical = 6.dp), + textAlign = androidx.compose.ui.text.style.TextAlign.Center) + } + } + val pts = points + when { + pts == null -> Text("Loading…", fontSize = 12.sp, color = PulseColors.textMuted) + pts.size < 2 -> Text("Not enough ${metric.label.lowercase()} data for this view yet.", fontSize = 12.sp, color = PulseColors.textMuted) + else -> { + val shown = pts.takeLast(if (period == Trends.Period.DAY) 30 else 26) + Canvas(Modifier.fillMaxWidth().height(120.dp)) { + val max = shown.maxOf { it.value }; val min = minOf(0.0, shown.minOf { it.value }) + val lo = if (metric in setOf(TrendMetric.RESTING_HR, TrendMetric.HRV, TrendMetric.SPO2, TrendMetric.TEMPERATURE, TrendMetric.WEIGHT)) + shown.minOf { it.value } * 0.95 else min + val range = (max - lo).takeIf { it > 0 } ?: 1.0 + val bw = size.width / shown.size + shown.forEachIndexed { i, p -> + val h = ((p.value - lo) / range * size.height).toFloat().coerceAtLeast(2f) + drawRect(PulseColors.accent, Offset(i * bw + bw * 0.15f, size.height - h), Size(bw * 0.7f, h)) + } + } + val last = shown.last() + val fmt = if (metric == TrendMetric.TEMPERATURE || metric == TrendMetric.SLEEP || metric == TrendMetric.WEIGHT) "%.1f" else "%.0f" + Text("Latest ${period.label.lowercase()}: ${fmt.format(last.value)} ${metric.unit} · average ${fmt.format(shown.map { it.value }.average())} ${metric.unit}", + fontSize = 12.sp, color = PulseColors.textSecondary) + } + } + } +} + +// ── Breathing session ───────────────────────────────────────────────────────────────────────── + +/** + * An unguided breathing session: pick a length, follow the circle (in for 4 s, out for 6 s), and + * the heart rate the ring logged during it is saved with the session. + */ +@Composable +fun BreatheScreen(onBack: () -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val scope = rememberCoroutineScope() + var minutes by remember { mutableIntStateOf(5) } + var startedAt by remember { mutableStateOf(null) } + var remaining by remember { mutableIntStateOf(0) } + var result by remember { mutableStateOf(null) } + + fun finish() { + val s = startedAt ?: return + startedAt = null + scope.launch { result = MindfulSessions.finish(context, db, s, System.currentTimeMillis()) } + } + + LaunchedEffect(startedAt) { + val s = startedAt ?: return@LaunchedEffect + while (true) { + remaining = (minutes * 60 - ((System.currentTimeMillis() - s) / 1000)).toInt() + if (remaining <= 0) { finish(); break } + delay(500) + } + } + + Column(Modifier.fillMaxSize().background(PulseColors.background).padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { + Box(Modifier.fillMaxWidth()) { + IconButton(onClick = { if (startedAt != null) finish(); onBack() }, modifier = Modifier.align(Alignment.CenterStart)) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") + } + Text("Breathe", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + } + Spacer(Modifier.weight(1f)) + val r = result + when { + startedAt != null -> { + val t = rememberInfiniteTransition(label = "breath") + val s by t.animateFloat( + 0.55f, 1f, + infiniteRepeatable(keyframes { durationMillis = 10_000; 1f at 4_000 using FastOutSlowInEasing; 0.55f at 10_000 }, RepeatMode.Restart), + label = "scale", + ) + Box(Modifier.size(220.dp).scale(s).clip(CircleShape).dither(PulseColors.accent, 0.35f, CircleShape).border(2.dp, PulseColors.accent, CircleShape)) + Spacer(Modifier.height(24.dp)) + Text(if (s > 0.98f || remaining % 10 < 4) "Breathe in" else "Breathe out", fontSize = 18.sp, color = PulseColors.textPrimary) + Text("%d:%02d".format(remaining / 60, remaining % 60), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Spacer(Modifier.height(16.dp)) + OutlinedButton(onClick = { finish() }) { Text("End session") } + } + r != null -> { + Text("Session saved", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("${r.minutes} min" + (r.avgHr?.let { " · average $it bpm" } ?: ""), fontSize = 15.sp, color = PulseColors.textSecondary) + if (r.startHr != null && r.endHr != null) { + Text("Heart rate ${r.startHr} → ${r.endHr} bpm", fontSize = 15.sp, color = PulseColors.textSecondary) + } else { + Text("Your ring logs heart rate every few minutes, so short sessions may show none.", fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("Tagged as \"Meditation or relaxing\" in today's journal.", fontSize = 12.sp, color = PulseColors.textMuted) + Spacer(Modifier.height(16.dp)) + Button(onClick = onBack) { Text("Done") } + } + else -> { + Text("Slow breathing: in for 4 seconds, out for 6.", fontSize = 15.sp, color = PulseColors.textSecondary) + Spacer(Modifier.height(16.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(1, 3, 5, 10).forEach { m -> + val on = m == minutes + Text("$m min", fontSize = 14.sp, color = if (on) PulseColors.onAccent else PulseColors.textPrimary, + modifier = Modifier.clip(RoundedCornerShape(16.dp)) + .background(if (on) PulseColors.accent else PulseColors.card) + .clickable { minutes = m }.padding(horizontal = 14.dp, vertical = 8.dp)) + } + } + Spacer(Modifier.height(24.dp)) + Button(onClick = { result = null; startedAt = System.currentTimeMillis() }) { Text("Start") } + } + } + Spacer(Modifier.weight(1f)) + } +} + +/** The way into [MyHealthScreen] from Vitals: one row, with Rest Mode shown while it is on. */ +@Composable +fun MyHealthEntryCard(onClick: () -> Unit) { + val context = LocalContext.current + val restUntil = remember { RestMode.until(context) } + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(onClick = onClick).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("My Health & Trends", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text( + if (restUntil != null) "Rest Mode on until ${restUntil.dayOfWeek.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.getDefault())}" + else "Symptom radar, sleep debt, stress, body clock, cardio capacity", + fontSize = 12.sp, color = if (restUntil != null) PulseColors.accent else PulseColors.textMuted, + ) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt index db1300eb..137cd064 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -504,6 +504,10 @@ fun VitalsScreen( Spacer(Modifier.height(8.dp)) } + if (navController != null) { + item { MyHealthEntryCard { navController.navigate("my_health") } } + } + // Card order mirrors VitalsView.swift (HR, SpO₂, BP, HRV, Stress, Fatigue, Glucose, Temp) // by default, but honors the user's per-metric visibility + order (iOS #64). Long-press a // card to reorder/hide; the Hidden tray restores. diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 2bb4832a..7119d8e1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1065,6 +1065,9 @@ private fun DailyGuidanceSettingsCard() { var weekly by remember { mutableStateOf(prefs.weeklyReport) } var bedtime by remember { mutableStateOf(prefs.bedtimeReminder) } var meal by remember { mutableStateOf(prefs.mealReminder) } + var battery by remember { mutableStateOf(prefs.bedtimeBattery) } + var inactive by remember { mutableStateOf(prefs.inactivityAlerts) } + var progress by remember { mutableStateOf(prefs.activityProgress) } Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { @@ -1094,6 +1097,21 @@ private fun DailyGuidanceSettingsCard() { "Around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on.", meal, ) { meal = it; prefs.mealReminder = it } + GuidanceSwitch( + "Charge before bed", + "When the ring is at 30% or less a couple of hours before your usual bedtime.", + battery, + ) { battery = it; prefs.bedtimeBattery = it } + GuidanceSwitch( + "Move reminder", + "Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode.", + inactive, + ) { inactive = it; prefs.inactivityAlerts = it } + GuidanceSwitch( + "Step progress", + "Early evening, when you're under 70% of your step goal. Off in Rest Mode.", + progress, + ) { progress = it; prefs.activityProgress = it } } } } diff --git a/app/src/test/java/com/pulseloop/notifications/NudgesTest.kt b/app/src/test/java/com/pulseloop/notifications/NudgesTest.kt new file mode 100644 index 00000000..1121bfb7 --- /dev/null +++ b/app/src/test/java/com/pulseloop/notifications/NudgesTest.kt @@ -0,0 +1,36 @@ +package com.pulseloop.notifications + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Battery-before-bed, inactivity and step-progress nudges. */ +class NudgesTest { + + @Test + fun `charge reminder fires on low battery a couple of hours before bed`() { + assertTrue(Nudges.chargeBeforeBed(battery = 25, minsToBed = 90)) + assertFalse(Nudges.chargeBeforeBed(battery = 45, minsToBed = 90)) + assertFalse(Nudges.chargeBeforeBed(battery = 25, minsToBed = 20)) + assertFalse(Nudges.chargeBeforeBed(battery = null, minsToBed = 90)) + assertFalse(Nudges.chargeBeforeBed(battery = 25, minsToBed = null)) + } + + @Test + fun `inactivity needs fresh data and waking hours`() { + assertTrue(Nudges.inactive(hour = 14, stepsLastHour = 40, dataFresh = true)) + assertFalse(Nudges.inactive(hour = 14, stepsLastHour = 40, dataFresh = false)) + assertFalse(Nudges.inactive(hour = 22, stepsLastHour = 40, dataFresh = true)) + assertFalse(Nudges.inactive(hour = 14, stepsLastHour = 500, dataFresh = true)) + } + + @Test + fun `step progress speaks only early evening and under 70 percent`() { + assertNotNull(Nudges.progress(hour = 18, steps = 3000, goal = 8000)) + assertNull(Nudges.progress(hour = 18, steps = 7000, goal = 8000)) + assertNull(Nudges.progress(hour = 12, steps = 1000, goal = 8000)) + assertNull(Nudges.progress(hour = 18, steps = 1000, goal = 0)) + } +} diff --git a/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt b/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt new file mode 100644 index 00000000..b9502a45 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt @@ -0,0 +1,218 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZoneOffset + +/** Sleep need and debt, Symptom Radar, stress zones, body clock, cardio capacity and trends. */ +class HealthInsightsTest { + + private val zone: ZoneId = ZoneOffset.UTC + private val today: LocalDate = LocalDate.of(2026, 10, 18) + + /** A night ending at [wakeHour]:30 on [day], eight hours long, asleep [asleep] minutes. */ + private fun night( + day: LocalDate, rhr: Double? = 55.0, hrv: Double? = 40.0, asleep: Int = 450, wakeHour: Int = 7, + ): NightSummary { + val end = day.atTime(wakeHour, 30).atZone(zone).toInstant().toEpochMilli() + return NightSummary(day, end - 8 * 3600_000L, end, asleep, rhr, hrv, 1.0) + } + + // ── Sleep need ─────────────────────────────────────────────────────────────────────────── + + @Test + fun `sleep need is the typical length of nights the body recovered from`() { + val recovered = (1..10).map { night(today.minusDays(it * 2L), rhr = 52.0, hrv = 45.0, asleep = 480) } + val strained = (1..10).map { night(today.minusDays(it * 2L - 1), rhr = 60.0, hrv = 35.0, asleep = 400) } + val need = SleepNeed.estimate(recovered + strained, fallbackMinutes = 450, today = today) + assertTrue(need.isLearned) + assertEquals(480, need.minutes) + } + + @Test + fun `sleep need falls back to the goal until five recovered nights`() { + val nights = (1..4).map { night(today.minusDays(it.toLong()), rhr = 50.0, hrv = 50.0, asleep = 500) } + + (5..14).map { night(today.minusDays(it.toLong()), rhr = 60.0, hrv = 30.0) } + val need = SleepNeed.estimate(nights, fallbackMinutes = 450, today = today) + assertFalse(need.isLearned) + assertEquals(450, need.minutes) + } + + // ── Sleep debt ─────────────────────────────────────────────────────────────────────────── + + @Test + fun `nights at the need carry no debt`() { + val debt = SleepDebt.compute(List(14) { 480 }, SleepNeed(480, true))!! + assertEquals(0, debt.minutes) + assertEquals(SleepDebt.Level.NONE, debt.level) + } + + @Test + fun `an hour short every night builds high debt that fades with age`() { + val debt = SleepDebt.compute(List(14) { 420 }, SleepNeed(480, true))!! + // 60 × (1 − 0.9¹⁴) / 0.1 ≈ 463, well under the undecayed 840. + assertEquals(463, debt.minutes) + assertEquals(SleepDebt.Level.HIGH, debt.level) + } + + @Test + fun `a surplus pays debt back but never below zero`() { + val debt = SleepDebt.compute(List(10) { 600 } + List(4) { 480 }, SleepNeed(480, true))!! + assertEquals(0, debt.minutes) + } + + @Test + fun `sleep debt needs five nights`() { + assertNull(SleepDebt.compute(List(10) { null } + List(4) { 400 }, SleepNeed(480, true))) + } + + // ── Symptom Radar ──────────────────────────────────────────────────────────────────────── + + /** 20 ordinary nights before [today]: RHR 54/56, HRV 38/42, temperature 33.9/34.1. */ + private fun baseline(n: Int = 20) = (1..n).map { i -> + val even = i % 2 == 0 + SymptomRadar.Night( + today.minusDays(i.toLong()), + temperature = if (even) 33.9 else 34.1, + restingHr = if (even) 54.0 else 56.0, + hrv = if (even) 38.0 else 42.0, + ) + } + + private fun strained(day: LocalDate) = SymptomRadar.Night(day, temperature = 34.6, restingHr = 60.0, hrv = 30.0) + + @Test + fun `an ordinary night shows no signs`() { + val tonight = SymptomRadar.Night(today, temperature = 34.0, restingHr = 55.0, hrv = 40.0) + val r = SymptomRadar.compute(baseline() + tonight, today)!! + assertEquals(SymptomRadar.Level.NONE, r.level) + assertTrue(r.flagged.isEmpty()) + } + + @Test + fun `three signals on one night are minor until the night before also shows signs`() { + val one = SymptomRadar.compute(baseline() + strained(today), today)!! + assertEquals(3, one.flagged.size) + assertEquals(SymptomRadar.Level.MINOR, one.level) + + val history = baseline().filter { it.day != today.minusDays(1) } + strained(today.minusDays(1)) + val two = SymptomRadar.compute(history + strained(today), today)!! + assertEquals(SymptomRadar.Level.MAJOR, two.level) + } + + @Test + fun `a perfectly steady baseline does not turn a tiny change into a sign`() { + val steady = (1..20).map { SymptomRadar.Night(today.minusDays(it.toLong()), temperature = 34.0, restingHr = 55.0, hrv = 40.0) } + val tonight = SymptomRadar.Night(today, temperature = 34.1, restingHr = 56.0, hrv = 38.0) + val r = SymptomRadar.compute(steady + tonight, today)!! + assertTrue(r.flagged.isEmpty()) + } + + @Test + fun `the radar waits for two weeks of baseline`() { + val r = SymptomRadar.compute(baseline(10) + strained(today), today)!! + assertEquals(SymptomRadar.Level.NONE, r.level) + assertEquals(10, r.baselineNights) + assertTrue(r.signals.isEmpty()) + } + + // ── Stress ─────────────────────────────────────────────────────────────────────────────── + + @Test + fun `stress readings fall into the four zones`() { + val s = DaytimeStress.compute(listOf(10.0, 20.0, 50.0, 70.0, 90.0, 95.0))!! + assertEquals(60, s.restoredMin) + assertEquals(30, s.relaxedMin) + assertEquals(30, s.engagedMin) + assertEquals(60, s.stressedMin) + assertEquals(DaytimeStress.Summary.NORMAL, s.summary) + } + + @Test + fun `a day mostly in the stressed zone reads stressful`() { + assertEquals(DaytimeStress.Summary.STRESSFUL, DaytimeStress.compute(listOf(85.0, 85.0, 85.0, 85.0, 10.0))!!.summary) + assertEquals(DaytimeStress.Summary.RESTORED, DaytimeStress.compute(listOf(10.0, 15.0, 20.0, 50.0))!!.summary) + assertNull(DaytimeStress.compute(listOf(50.0, 60.0))) + } + + @Test + fun `resilience rises with recovery and needs five days`() { + assertNull(Resilience.compute(List(4) { Resilience.Day(60, 60, 1.0) })) + val strong = Resilience.compute(List(7) { Resilience.Day(10, 120, 1.15) })!! + val limited = Resilience.compute(List(7) { Resilience.Day(180, 10, 0.8) })!! + assertTrue(strong.level.ordinal > limited.level.ordinal) + assertEquals(Resilience.Level.LIMITED, limited.level) + } + + // ── Body clock ─────────────────────────────────────────────────────────────────────────── + + @Test + fun `a 3 30 midpoint is in between and steady nights are in sync`() { + val c = BodyClock.compute((1..14).map { night(today.minusDays(it.toLong())) }, zone)!! + assertEquals(210, c.usualMidpointMin) + assertEquals("3:30", c.midpointLabel()) + assertEquals(BodyClock.Chronotype.INTERMEDIATE, c.chronotype) + assertEquals(BodyClock.Alignment.ALIGNED, c.alignment) + } + + @Test + fun `two hours later this week is out of sync`() { + val recent = (1..7).map { night(today.minusDays(it.toLong()), wakeHour = 9) } + val older = (8..14).map { night(today.minusDays(it.toLong())) } + val c = BodyClock.compute(recent + older, zone)!! + assertEquals(120, c.recentShiftMin) + assertEquals(BodyClock.Alignment.MISALIGNED, c.alignment) + assertNull(BodyClock.compute(older, zone)) + } + + // ── Cardio capacity ────────────────────────────────────────────────────────────────────── + + @Test + fun `cardio capacity uses the Uth estimate and age norms`() { + val c = CardioCapacity.compute(restingHr = 60.0, hrv = null, age = 30, sex = "male")!! + assertEquals(47.7, c.vo2max, 0.1) + assertEquals(CardioCapacity.Level.AVERAGE, c.level) + assertFalse(c.fromRing) + + val fit = CardioCapacity.compute(restingHr = 45.0, hrv = 70.0, age = 30, sex = "male")!! + assertEquals(CardioCapacity.Level.EXCELLENT, fit.level) + assertTrue(fit.cardioAge!! < 30) + } + + @Test + fun `a ring's own VO2max wins and missing inputs give nothing`() { + assertTrue(CardioCapacity.compute(60.0, null, 30, "female", ringVo2 = 50.0)!!.fromRing) + assertNull(CardioCapacity.compute(60.0, null, null, "male")) + assertNull(CardioCapacity.compute(null, null, 30, "male")) + } + + // ── Health areas and trends ────────────────────────────────────────────────────────────── + + @Test + fun `health area ratings follow the score`() { + assertEquals(HealthArea.Rating.THRIVING, HealthArea.rate(HealthArea.scoreOf(1.2))) + assertEquals(HealthArea.Rating.NEEDS_CARE, HealthArea.rate(HealthArea.scoreOf(0.3))) + assertTrue(HealthArea.scoreOf(1.0) in 80..90) + } + + @Test + fun `trends average by week starting Monday and by month`() { + val start = LocalDate.of(2026, 10, 12) + val daily = (0 until 14).associate { start.plusDays(it.toLong()) to (if (it < 7) 1.0 else 3.0) } + val weeks = Trends.aggregate(daily, Trends.Period.WEEK) + assertTrue(weeks.all { it.start.dayOfWeek == DayOfWeek.MONDAY }) + assertEquals(listOf(1.0, 3.0), weeks.map { it.value }) + + val months = Trends.aggregate(mapOf(LocalDate.of(2026, 9, 30) to 2.0, LocalDate.of(2026, 10, 1) to 4.0, LocalDate.of(2026, 10, 2) to 6.0), Trends.Period.MONTH) + assertEquals(listOf(LocalDate.of(2026, 9, 1), LocalDate.of(2026, 10, 1)), months.map { it.start }) + assertEquals(5.0, months[1].value, 0.0) + assertNotNull(Trends.aggregate(emptyMap(), Trends.Period.YEAR)) + } +} diff --git a/app/src/test/java/com/pulseloop/service/ReadinessSensorsTest.kt b/app/src/test/java/com/pulseloop/service/ReadinessSensorsTest.kt new file mode 100644 index 00000000..132c223f --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/ReadinessSensorsTest.kt @@ -0,0 +1,54 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZoneOffset + +/** The optional-sensor contributors: body temperature and recovery index. */ +class ReadinessSensorsTest { + + private val zone: ZoneId = ZoneOffset.UTC + private val today: LocalDate = LocalDate.of(2026, 10, 18) + + private fun night(day: LocalDate, temp: Double? = null, minHrFraction: Double? = null): NightSummary { + val end = day.atTime(7, 30).atZone(zone).toInstant().toEpochMilli() + val start = end - 8 * 3600_000L + val minAt = minHrFraction?.let { start + ((end - start) * it).toLong() } + return NightSummary(day, start, end, 450, 55.0, 40.0, 1.0, temperature = temp, minHrAt = minAt) + } + + private fun history(temp: Double? = null) = (1..14).map { night(today.minusDays(it.toLong()), temp) } + + @Test + fun `a usual skin temperature scores full marks and a degree up costs`() { + assertEquals(100, Readiness.bodyTemperature(night(today, 34.1), history(34.0))!!.score) + val warm = Readiness.bodyTemperature(night(today, 35.2), history(34.0))!! + assertTrue("got ${warm.score}", warm.score < 50) + assertTrue(warm.detail.startsWith("+1.2")) + assertNull(Readiness.bodyTemperature(night(today, 34.0), history(null))) + } + + @Test + fun `an early heart rate low recovers best`() { + assertEquals(100, Readiness.recoveryIndex(night(today, minHrFraction = 0.3))!!.score) + assertTrue(Readiness.recoveryIndex(night(today, minHrFraction = 0.95))!!.score < 50) + assertNull(Readiness.recoveryIndex(night(today))) + } + + @Test + fun `a ring without a temperature sensor is not told a contributor is missing`() { + val r = Readiness.compute(Readiness.Inputs(night(today), history(), 450, List(28) { 8000 }, zone)) as Readiness.Result.Score + assertTrue(r.missing.isEmpty()) + assertTrue(r.contributors.none { it.kind == Readiness.ContributorKind.BODY_TEMPERATURE }) + } + + @Test + fun `a ring that has reported temperature before is told when tonight lacks it`() { + val r = Readiness.compute(Readiness.Inputs(night(today), history(34.0), 450, List(28) { 8000 }, zone)) as Readiness.Result.Score + assertTrue(Readiness.ContributorKind.BODY_TEMPERATURE in r.missing) + } +} From ab8b6334dec2a61bae995483048857d4790621d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 16:22:48 +0000 Subject: [PATCH 2/3] Explain the body temperature and recovery index contributors Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/java/com/pulseloop/service/Readiness.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/pulseloop/service/Readiness.kt b/app/src/main/java/com/pulseloop/service/Readiness.kt index 1986ae11..20eb8c5c 100644 --- a/app/src/main/java/com/pulseloop/service/Readiness.kt +++ b/app/src/main/java/com/pulseloop/service/Readiness.kt @@ -453,8 +453,12 @@ object ReadinessCopy { "Your lowest sustained heart rate last night, compared with your usual over recent nights. A resting heart rate a few beats above normal can mean your body is working on recovery, stress, or an oncoming illness." Readiness.ContributorKind.HRV_BALANCE -> "Your heart rate variability over the last few nights, weighted toward last night, compared with your usual. Higher than usual generally means you're well recovered; a drop suggests strain." + Readiness.ContributorKind.BODY_TEMPERATURE -> + "Your skin temperature last night compared with your usual. A rise of half a degree or more can come with illness, a hard training load, alcohol or the menstrual cycle." + Readiness.ContributorKind.RECOVERY_INDEX -> + "How early in the night your heart rate reached its lowest. An early low means your body had time to recover; a low just before waking means it was still working, often after a late meal, alcohol or an evening workout." Readiness.ContributorKind.SLEEP -> - "How much you slept last night compared with your sleep goal." + "How much you slept last night compared with your sleep need, learned from the nights you woke up recovered (your sleep goal until then)." Readiness.ContributorKind.SLEEP_BALANCE -> "Your average sleep over the last two weeks compared with your goal. It shows whether sleep debt is building up." Readiness.ContributorKind.SLEEP_REGULARITY -> From d23b3b737965cc87c62ce0b7e2b47e83bbe8b48b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 16:26:50 +0000 Subject: [PATCH 3/3] Keep readiness proportions for rings without the new sensors; fix radar test count Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../main/java/com/pulseloop/service/Readiness.kt | 16 +++++++++------- .../com/pulseloop/service/HealthInsightsTest.kt | 5 +++-- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/com/pulseloop/service/Readiness.kt b/app/src/main/java/com/pulseloop/service/Readiness.kt index 20eb8c5c..1bd75f1f 100644 --- a/app/src/main/java/com/pulseloop/service/Readiness.kt +++ b/app/src/main/java/com/pulseloop/service/Readiness.kt @@ -168,15 +168,17 @@ object Readiness { * and the rest are renormalised. */ enum class ContributorKind(val title: String, val weight: Double, val optionalSensor: Boolean = false) { - RESTING_HR("Resting heart rate", 0.15), - HRV_BALANCE("HRV balance", 0.15), + // The original seven keep their proportions (×0.8), so a ring without the optional + // sensors scores exactly as it did before they existed. + RESTING_HR("Resting heart rate", 0.16), + HRV_BALANCE("HRV balance", 0.16), BODY_TEMPERATURE("Body temperature", 0.10, optionalSensor = true), RECOVERY_INDEX("Recovery index", 0.10, optionalSensor = true), - SLEEP("Sleep", 0.15), - SLEEP_BALANCE("Sleep balance", 0.10), - SLEEP_REGULARITY("Sleep regularity", 0.05), - PREVIOUS_DAY_ACTIVITY("Previous day activity", 0.10), - ACTIVITY_BALANCE("Activity balance", 0.10), + SLEEP("Sleep", 0.16), + SLEEP_BALANCE("Sleep balance", 0.12), + SLEEP_REGULARITY("Sleep regularity", 0.04), + PREVIOUS_DAY_ACTIVITY("Previous day activity", 0.08), + ACTIVITY_BALANCE("Activity balance", 0.08), } data class Contributor( diff --git a/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt b/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt index b9502a45..bb885ea3 100644 --- a/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt +++ b/app/src/test/java/com/pulseloop/service/HealthInsightsTest.kt @@ -97,9 +97,10 @@ class HealthInsightsTest { } @Test - fun `three signals on one night are minor until the night before also shows signs`() { + fun `several signals on one night are minor until the night before also shows signs`() { val one = SymptomRadar.compute(baseline() + strained(today), today)!! - assertEquals(3, one.flagged.size) + // Temperature, its three-night trend, resting HR and HRV. + assertEquals(4, one.flagged.size) assertEquals(SymptomRadar.Level.MINOR, one.level) val history = baseline().filter { it.day != today.minusDays(1) } + strained(today.minusDays(1))