From 536389843fc37c2a11b5c838f0096554a82d6d9d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:44:37 +0000 Subject: [PATCH] Accuracy check grades past days too A check can reach back 7, 14 or 30 days (14 by default) over what the app, the second ring and Health Connect already hold, from the start dialog or on a running check. Grading moves (historyFrom, DB v39); the check's start, day count and export pause do not. Never before the ring was paired. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 3 + app/src/main/assets/i18n/pt-BR.json | 5 ++ .../java/com/pulseloop/data/DataArchive.kt | 1 + .../com/pulseloop/data/DataArchiveService.kt | 2 + .../com/pulseloop/data/PulseLoopDatabase.kt | 10 ++- .../pulseloop/data/entity/AccuracyEntities.kt | 8 ++ .../accuracy/AccuracyCheckController.kt | 38 ++++++++ .../health/accuracy/AccuracyScorer.kt | 4 +- .../pulseloop/ui/screens/AccuracyCheckUi.kt | 55 ++++++++++-- .../pulseloop/ui/screens/AccuracyReportUi.kt | 3 +- .../accuracy/AccuracyHistoryStartTest.kt | 31 +++++++ audits/2026-11-18-accuracy-past-days.md | 90 +++++++++++++++++++ docs/ring-comparison.md | 9 ++ 13 files changed, 250 insertions(+), 9 deletions(-) create mode 100644 app/src/test/java/com/pulseloop/health/accuracy/AccuracyHistoryStartTest.kt create mode 100644 audits/2026-11-18-accuracy-past-days.md diff --git a/AGENTS.md b/AGENTS.md index bfbe36ba..71bb5f48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1142,6 +1142,9 @@ because breaking it fails silently: `AccuracyScorer.SCORING_VERSION`: finished checks otherwise keep their stored result forever, and an outdated one is re-scored once by itself (app launch, or opening the accuracy screen). Corrections already accepted are not touched by a re-score. +- **Reaching back over past days moves grading, never the pause** (`historyFrom`, v39). Grading + starts at `gradeFrom`; `startedAt`, the day count and every `pausedFrom` stay at the real start. + Never before the ring was paired, for the same no-device-id reason as the next rule. - **A running check ends the moment a different ring is paired** (`AccuracyRingWatcher`, started from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split the two rings' data. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 892d0dd9..66d1808b 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -201,6 +201,7 @@ "Allow camera access in Settings to scan barcodes, or enter the food manually instead.": "Permita o acesso à câmera em Configurações para ler códigos de barras, ou insira o alimento manualmente.", "Allow installs from this app, then tap Update again.": "Permita instalações deste app e toque em Atualizar de novo.", "Allow more": "Permitir mais", + "Also grading the days since {0}.": "Avaliando também os dias desde {0}.", "Always": "Sempre", "Always on: paired AI tools on this network can read your health data. Tap to stop.": "Sempre ligado: ferramentas de IA pareadas nesta rede podem ler seus dados de saúde. Toque para parar.", "An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker. It talks to the ring directly over Bluetooth — no vendor cloud, no account — and layers an AI coach on top of your own data.": "Um app de saúde nativo de LLM que transforma um anel inteligente Bluetooth barato em um monitor de saúde de verdade, com conversa. Ele se comunica com o anel diretamente via Bluetooth — sem nuvem do fabricante, sem conta — e adiciona um coach de IA sobre os seus próprios dados.", @@ -916,6 +917,8 @@ "In sync": "Em sincronia", "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.": "No app Oura: Configurações → Health Connect, e ative o compartilhamento. Depois volte e verifique novamente.", "Inactivity": "Inatividade", + "Include": "Incluir", + "Include past days": "Incluir dias passados", "Includes {0} added by you, not staged or scored": "Inclui {0} adicionados por você, sem fase nem pontuação", "Increase duration by 5 minutes": "Aumentar a duração em 5 minutos", "Increase {0}": "Aumentar {0}", @@ -1303,6 +1306,7 @@ "On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.": "Ativado. O PulseLoop sincroniza seu anel a cada 30 minutos, mesmo com o celular ocioso.", "Once per dose, at its time, for what you add with + Log → Medication or supplement.": "Uma vez por dose, no horário, para o que você adicionar em + Registrar → Medicamento ou suplemento.", "One tap for the usual ones": "Um toque para as de sempre", + "Only days since this ring was paired. The Health Connect export isn't affected: those days were exported already.": "Só os dias desde que este anel foi pareado. A exportação para o Health Connect não muda: esses dias já foram exportados.", "Only needed if you started the server with --api-key. Leave blank otherwise.": "Só é necessário se você iniciou o servidor com --api-key. Caso contrário, deixe em branco.", "Only new data from now on": "Apenas dados novos daqui em diante", "Only providers that don't retain data": "Apenas provedores que não retêm dados", @@ -2147,6 +2151,7 @@ "Your preference: ": "Sua preferência: ", "Your resting heart rate is up on last week. Prioritise recovery and sleep.": "Sua frequência cardíaca em repouso subiu em relação à semana passada. Priorize recuperação e sono.", "Your ring and phone agree within 5% ({0} days).": "Seu anel e seu celular concordam dentro de 5% ({0} dias).", + "Your ring and the reference already hold past days. Grading them too gives an answer sooner.": "Seu anel e a referência já guardam dias passados. Avaliá-los também dá uma resposta mais cedo.", "Your ring counts about {0}% fewer steps than your phone ({1} days).": "Seu anel conta cerca de {0}% menos passos que seu celular ({1} dias).", "Your ring counts about {0}% more steps than your phone ({1} days).": "Seu anel conta cerca de {0}% mais passos que seu celular ({1} dias).", "Your ring logs heart rate every few minutes, so short sessions may show none.": "Seu anel registra a frequência cardíaca a cada poucos minutos, então sessões curtas podem não mostrar nenhuma.", diff --git a/app/src/main/java/com/pulseloop/data/DataArchive.kt b/app/src/main/java/com/pulseloop/data/DataArchive.kt index eb3d27a0..9850fa7b 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchive.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchive.kt @@ -93,6 +93,7 @@ data class PulseArchive( val state: String, val endReason: String? = null, val resumeChoice: String? = null, val bandsRaw: String? = null, val pauseRefreshedAt: Long? = null, val scoredAt: Long? = null, val firmware: String? = null, + val historyFrom: Long? = null, ) @Serializable data class AccuracyPausedUnitDTO(val checkId: String, val unit: String, val pausedFrom: Long) diff --git a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt index 9a420598..6ce47291 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt @@ -343,6 +343,7 @@ object DataArchiveService { state = c.str("state"), endReason = c.strOrNull("endReason"), resumeChoice = c.strOrNull("resumeChoice"), bandsRaw = c.strOrNull("bandsRaw"), pauseRefreshedAt = c.longOrNull("pauseRefreshedAt"), scoredAt = c.longOrNull("scoredAt"), firmware = c.strOrNull("firmware"), + historyFrom = c.longOrNull("historyFrom"), ) }, accuracyPausedUnits = collect("accuracy_paused_units") { c -> @@ -506,6 +507,7 @@ object DataArchiveService { referenceLabel = a.referenceLabel, startedAt = a.startedAt, plannedEndAt = a.plannedEndAt, endedAt = a.endedAt, state = a.state, endReason = a.endReason, resumeChoice = a.resumeChoice, bandsRaw = a.bandsRaw, pauseRefreshedAt = a.pauseRefreshedAt, scoredAt = a.scoredAt, firmware = a.firmware, + historyFrom = a.historyFrom, )) } if (archive.accuracyPausedUnits.isNotEmpty()) { diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index ef976b59..cfba74b3 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -60,7 +60,7 @@ import com.pulseloop.data.entity.* LabResultEntity::class, ComparisonReadingEntity::class, ], - version = 38, + version = 39, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -730,6 +730,13 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** v39: an accuracy check can grade past days (`historyFrom`). */ + private val MIGRATION_38_39 = object : Migration(38, 39) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE `accuracy_checks` ADD COLUMN `historyFrom` INTEGER") + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -834,6 +841,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_35_36, MIGRATION_36_37, MIGRATION_37_38, + MIGRATION_38_39, ) // 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/entity/AccuracyEntities.kt b/app/src/main/java/com/pulseloop/data/entity/AccuracyEntities.kt index 1dc3be78..6ed1da30 100644 --- a/app/src/main/java/com/pulseloop/data/entity/AccuracyEntities.kt +++ b/app/src/main/java/com/pulseloop/data/entity/AccuracyEntities.kt @@ -35,7 +35,15 @@ data class AccuracyCheckEntity( val scoredAt: Long? = null, /** The ring's firmware when the check started, so a correction can tell it went stale. */ val firmware: String? = null, + /** + * Where grading starts when the check also covers past days ([startedAt] is still when the + * check, and the export pause, began). Null = from [startedAt]. + */ + val historyFrom: Long? = null, ) { + /** The first moment the check grades: [historyFrom] when it reaches back, else [startedAt]. */ + val gradeFrom: Long get() = historyFrom?.coerceAtMost(startedAt) ?: startedAt + val isOpen: Boolean get() = state == STATE_RUNNING || state == STATE_AWAITING_RESUME companion object { diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckController.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckController.kt index e1f3b7b2..c74edba8 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckController.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckController.kt @@ -17,6 +17,7 @@ import com.pulseloop.health.HealthConnectPrefsStore import com.pulseloop.health.HealthConnectSdk import kotlinx.coroutines.sync.withLock import java.time.Instant +import java.time.ZoneId import kotlin.reflect.KClass /** Which ring a check or a correction belongs to. */ @@ -45,6 +46,9 @@ object AccuracyCheckController { private const val TAG = "AccuracyCheck" val DURATIONS_DAYS = listOf(3, 5, 7, 14) const val DEFAULT_DAYS = 7 + /** Past days a check can also grade, from what the app and Health Connect already hold. */ + val LOOK_BACK_DAYS = listOf(0, 7, 14, 30) + const val DEFAULT_LOOK_BACK_DAYS = 14 private const val DAY_MS = 86_400_000L sealed interface StartResult { @@ -59,6 +63,7 @@ object AccuracyCheckController { source: ReferenceSourceSurvey, referenceLabel: String, days: Int, + lookBackDays: Int = 0, now: Long = System.currentTimeMillis(), ): StartResult { val db = PulseLoopDatabase.getInstance(context) @@ -76,6 +81,7 @@ object AccuracyCheckController { plannedEndAt = now + days.coerceAtLeast(DURATIONS_DAYS.first()) * DAY_MS, pauseRefreshedAt = now, firmware = ring.firmwareVersion, + historyFrom = historyStart(now, lookBackDays, ring.createdAt), ) dao.upsert(check) dao.insertPausedUnits(units.map { AccuracyPausedUnitEntity(check.id, it.name, pausedFrom = now) }) @@ -84,6 +90,38 @@ object AccuracyCheckController { return StartResult.Started(check) } + /** + * Where grading starts for a check that also covers [lookBackDays] past days: local midnight + * that many days ago, but never before this ring was paired ([ringPairedAt]), because ring + * rows carry no device id and an earlier ring's days would be graded as this one's. Null when + * there is nothing to reach back over. The export pause is unaffected: past days were + * exported long ago, and the reference reads filter on `DataOrigin`, so those exports can't + * come back as the reference. + */ + fun historyStart(now: Long, lookBackDays: Int, ringPairedAt: Long, zone: ZoneId = ZoneId.systemDefault()): Long? { + if (lookBackDays <= 0) return null + val midnight = Instant.ofEpochMilli(now).atZone(zone).toLocalDate().minusDays(lookBackDays.toLong()) + .atStartOfDay(zone).toInstant().toEpochMilli() + return maxOf(midnight, ringPairedAt).takeIf { it < now } + } + + /** + * Widens a running check to also grade [lookBackDays] past days. Only ever moves grading + * earlier; the end and the export pause stay as they are. Returns the widened check. + */ + suspend fun includePastDays(context: Context, lookBackDays: Int, now: Long = System.currentTimeMillis()): AccuracyCheckEntity? { + val db = PulseLoopDatabase.getInstance(context) + val dao = db.accuracyDao() + val check = dao.open()?.takeIf { it.state == AccuracyCheckEntity.STATE_RUNNING } ?: return null + val ring = db.deviceDao().currentReal() ?: return null + val start = historyStart(now, lookBackDays, ring.createdAt) ?: return check + if (start >= check.gradeFrom) return check + val widened = check.copy(historyFrom = start, scoredAt = null) + dao.upsert(widened) + Log.i(TAG, "${check.id} now grades from ${Instant.ofEpochMilli(start)}") + return widened + } + /** RUNNING → AWAITING_RESUME. Export stays paused until [resolve]. */ suspend fun end(context: Context, reason: String, at: Long = System.currentTimeMillis()): AccuracyCheckEntity? { val dao = PulseLoopDatabase.getInstance(context).accuracyDao() diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt index 6c659eb4..5fc4eb59 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt @@ -102,7 +102,7 @@ object AccuracyScorer { val dao = db.accuracyDao() val client = HealthConnectClient.getOrCreate(context) val zone = ZoneId.systemDefault() - val from = check.startedAt + val from = check.gradeFrom val to = check.endedAt ?: minOf(now, check.plannedEndAt) val readable = AccuracyCheckPermissions.readable(ReferenceSourceScanner.grantedPermissions(context)) val compared = dao.pausedUnits(check.id).mapNotNull { ExportUnit.byName(it.unit)?.metric }.toSet() intersect readable @@ -125,7 +125,7 @@ object AccuracyScorer { out += r.records token = r.pageToken pages++ - } while (token != null && pages < 40) + } while (token != null && pages < 150) // a check reaching 30 days back reads a month of samples return out } diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt index 587a3242..17dfc8f7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -247,9 +247,9 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { context = context, source = src, onDismiss = { starting = null }, - onStart = { label, days -> + onStart = { label, days, lookBack -> scope.launch { - note = when (AccuracyCheckController.start(context, src, label, days)) { + note = when (AccuracyCheckController.start(context, src, label, days, lookBack)) { is AccuracyCheckController.StartResult.Started -> null AccuracyCheckController.StartResult.AlreadyOpen -> tr("A check is already open.") AccuracyCheckController.StartResult.NoRing -> tr("Pair your ring first.") @@ -267,7 +267,8 @@ internal object AccuracyUiText { /** "Oct 21" / "21 de out.": the locale's own order and month names, never a forced "d MMM". */ fun date(ms: Long): String = com.pulseloop.ui.components.PhoneFormat.date("MMMd", ms) - fun span(c: AccuracyCheckEntity): String = "${date(c.startedAt)} – ${date(c.endedAt ?: c.plannedEndAt)}" + /** What the check grades: from its earliest past day when it reaches back. */ + fun span(c: AccuracyCheckEntity): String = "${date(c.gradeFrom)} – ${date(c.endedAt ?: c.plannedEndAt)}" fun dayOf(c: AccuracyCheckEntity, now: Long = System.currentTimeMillis()): Pair { val total = ((c.plannedEndAt - c.startedAt + 43_200_000L) / 86_400_000L).toInt().coerceAtLeast(1) @@ -285,6 +286,20 @@ internal object AccuracyUiText { ExportUnit.entries.filter { it in units }.joinToString(", ") { it.metric.label.lowercase() }.replaceFirstChar { it.uppercase() } } +/** Past-days choice: none (from today), or 7 / 14 / 30 days back. Wraps, like "How long". */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun LookBackChips(selected: Int, includeNone: Boolean = true, onPick: (Int) -> Unit) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + AccuracyCheckController.LOOK_BACK_DAYS.filter { includeNone || it > 0 }.forEach { d -> + FilterChip( + selected = selected == d, onClick = { onPick(d) }, + label = { Text(if (d == 0) tr("None") else trf("{0} days", d)) }, + ) + } + } +} + @Composable private fun RunningCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.CoroutineScope) { val context = LocalContext.current @@ -292,13 +307,40 @@ private fun RunningCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Co val paused by remember(db) { db.accuracyDao().allPausedUnitsFlow() }.collectAsState(initial = emptyList()) val units = paused.filter { it.checkId == check.id }.mapNotNull { ExportUnit.byName(it.unit) } var confirmEnd by remember { mutableStateOf(false) } + var pickPast by remember { mutableStateOf(false) } val (day, total) = AccuracyUiText.dayOf(check) AccuracyCard { Text(trf("Accuracy check · day {0} of {1}", day, total), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = com.pulseloop.ui.calm.Look.text) Text(trf("{0} vs {1}, until {2}.", check.deviceLabel, check.referenceLabel, AccuracyUiText.date(check.plannedEndAt)), fontSize = 14.sp, color = com.pulseloop.ui.calm.Look.textSecondary) Text(trf("Wear both as usual. Health Connect export paused for: {0}.", AccuracyUiText.units(units)), fontSize = 12.sp, color = PulseColors.warning) + if (check.historyFrom == null) { + Text(tr("Your ring and the reference already hold past days. Grading them too gives an answer sooner."), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textSecondary) + PulseButton(PulseButtonStyle.Tonal, onClick = { pickPast = true }) { Text(tr("Include past days")) } + } else { + Text(trf("Also grading the days since {0}.", AccuracyUiText.date(check.gradeFrom)), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textSecondary) + } PulseButton(PulseButtonStyle.Outlined, onClick = { confirmEnd = true }) { Text(tr("End now")) } } + if (pickPast) { + var lookBack by remember { mutableStateOf(AccuracyCheckController.DEFAULT_LOOK_BACK_DAYS) } + AlertDialog( + onDismissRequest = { pickPast = false }, + title = { Text(tr("Include past days")) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + LookBackChips(lookBack, includeNone = false) { lookBack = it } + Text(tr("Only days since this ring was paired. The Health Connect export isn't affected: those days were exported already."), fontSize = 12.sp) + } + }, + confirmButton = { + PulseButton(PulseButtonStyle.Text, onClick = { + pickPast = false + scope.launch { AccuracyCheckController.includePastDays(context, lookBack) } + }) { Text(tr("Include")) } + }, + dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = { pickPast = false }) { Text(tr("Cancel")) } }, + ) + } if (confirmEnd) { AlertDialog( onDismissRequest = { confirmEnd = false }, @@ -347,7 +389,7 @@ private fun StartDialog( context: Context, source: ReferenceSourceSurvey, onDismiss: () -> Unit, - onStart: (label: String, days: Int) -> Unit, + onStart: (label: String, days: Int, lookBackDays: Int) -> Unit, ) { val defaultLabel = remember(source) { val app = ReferenceAppLabels.label(context, source.packageName) @@ -356,6 +398,7 @@ private fun StartDialog( } var label by remember { mutableStateOf(defaultLabel) } var days by remember { mutableStateOf(AccuracyCheckController.DEFAULT_DAYS) } + var lookBack by remember { mutableStateOf(AccuracyCheckController.DEFAULT_LOOK_BACK_DAYS) } val units = source.metrics.map { ExportUnit.of(it.metric) } AlertDialog( onDismissRequest = onDismiss, @@ -376,6 +419,8 @@ private fun StartDialog( FilterChip(selected = days == d, onClick = { days = d }, label = { Text(trf("{0} days", d)) }) } } + Text(tr("Include past days"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold) + LookBackChips(lookBack) { lookBack = it } Text( trf("Compared: {0}. These stop exporting to Health Connect until the check ends and you choose what to do with those days.", AccuracyUiText.units(units)), fontSize = 12.sp, @@ -383,7 +428,7 @@ private fun StartDialog( Text(tr("Wear both devices as you normally would, including at night."), fontSize = 12.sp) } }, - confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { onStart(label.trim(), days) }) { Text(tr("Start")) } }, + confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { onStart(label.trim(), days, lookBack) }) { Text(tr("Start")) } }, dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = onDismiss) { Text(tr("Cancel")) } }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index d5207752..9022b507 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -101,7 +101,8 @@ internal fun AccuracyReportSection( // An open check refreshes on view. A finished one keeps its stored result, unless days were // still waiting for the reference to deliver when it was last scored, or it was scored under // older rules (AccuracyScorer.SCORING_VERSION), which re-scores it once. - LaunchedEffect(check.id) { + // Keyed on gradeFrom too: reaching back over past days re-scores at once. + LaunchedEffect(check.id, check.gradeFrom) { val waiting = db.accuracyDao().days(check.id).any { it.note == AccuracyScorer.NOTE_WAITING } val outdated = AccuracyScorer.outdated(context, check.id) if (check.isOpen || check.scoredAt == null || waiting || outdated) rescore(force = outdated) diff --git a/app/src/test/java/com/pulseloop/health/accuracy/AccuracyHistoryStartTest.kt b/app/src/test/java/com/pulseloop/health/accuracy/AccuracyHistoryStartTest.kt new file mode 100644 index 00000000..99bfb946 --- /dev/null +++ b/app/src/test/java/com/pulseloop/health/accuracy/AccuracyHistoryStartTest.kt @@ -0,0 +1,31 @@ +package com.pulseloop.health.accuracy + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import java.time.LocalDateTime +import java.time.ZoneId + +/** A check that reaches back grades from local midnight N days ago, never before the ring was paired. */ +class AccuracyHistoryStartTest { + private val zone = ZoneId.of("America/Sao_Paulo") + private fun at(y: Int, m: Int, d: Int, h: Int = 0) = LocalDateTime.of(y, m, d, h, 0).atZone(zone).toInstant().toEpochMilli() + private val now = at(2026, 11, 18, 15) + + @Test fun noLookBackMeansNoHistory() { + assertNull(AccuracyCheckController.historyStart(now, 0, at(2026, 1, 1), zone)) + } + + @Test fun startsAtLocalMidnightNDaysAgo() { + assertEquals(at(2026, 11, 4), AccuracyCheckController.historyStart(now, 14, at(2026, 1, 1), zone)) + } + + @Test fun neverBeforeTheRingWasPaired() { + val paired = at(2026, 11, 10, 9) + assertEquals(paired, AccuracyCheckController.historyStart(now, 30, paired, zone)) + } + + @Test fun aRingPairedJustNowHasNoPast() { + assertNull(AccuracyCheckController.historyStart(now, 7, now, zone)) + } +} diff --git a/audits/2026-11-18-accuracy-past-days.md b/audits/2026-11-18-accuracy-past-days.md new file mode 100644 index 00000000..e5bc5826 --- /dev/null +++ b/audits/2026-11-18-accuracy-past-days.md @@ -0,0 +1,90 @@ +# Audit: the accuracy check grades past days + +Date: 2026-11-18 · PR: see the PR linking this file · Auditor: Claude Code. +- **impeccable:** applied to the **rendered** running card (both states) and the past-days chips. + They were drawn on the JVM with Robolectric under the screen's own calm theme, at 1.0× and 1.3×. + The harness is local only. +- **Device check:** owed. +- **ux-user-flows, graphic-design-fundamentals, less-is-more:** applied by hand. + +## Scope + +The owner asked for historical data to count: "Make sure you grab historical data. This can be +valuable." A check used to grade only from the moment it started. Now it can also grade days the +app, the second ring and Health Connect already hold. + +Two controls: +- **Include past days** chips in the start dialog: None, 7, 14 or 30 days, 14 by default. +- The same choice on a running check, behind one button. + +Rules: `AccuracyCheckController.historyStart`, `includePastDays`; `AccuracyCheckEntity.historyFrom` +(DB v39). + +## ux-user-flows (§13 flow review checklist) + +- **Entry:** + - start a check: one more chip row, already preset to 14 days; + - a running check: "Include past days" on its card. +- **Steps:** + 1. Pick a span, then Include. + 2. The report re-scores at once (keyed on `gradeFrom`). +- **States:** + - **Not reaching back:** the button plus one line on why it helps. + - **Reaching back:** "Also grading the days since [date]". The button goes, because a check only + reaches back further by starting a new one. + - **A ring paired recently:** grading starts at pairing, so 30 days may mean fewer. The dialog + says "Only days since this ring was paired". + - **Ring paired today:** nothing to reach back over; the check stays as it was. +- **Exits:** Cancel in either dialog, which changes nothing. +- **Nothing irreversible:** the export pause and the day count are unchanged, and the dialog says + so. + +## impeccable + +### Audit (native, on renders) + +| # | Dimension | Score | Key finding | +|---|---|---|---| +| 1 | Accessibility | 4 | Chips and buttons are standard controls with text labels. | +| 2 | Performance | 3 | 30 days of reference samples is a larger Health Connect read; the page cap rose from 40 to 150 pages. | +| 3 | Appearance & theming | 4 | Calm card, Look colours, sizes on the scale. | +| 4 | Platform conformance | 4 | FilterChip, AlertDialog, `PulseButton`. | +| 5 | Adaptivity | 4 | At 1.3× the chips wrap ("30 days" moves to a second line), and the copy wraps without clipping. | +| | **Total** | **19/20** | | + +### Critique + +| # | Heuristic | Score | Key issue | +|---|---|---|---| +| 1 | Visibility of status | 4 | The card says from when it grades. | +| 3 | User control | 4 | Cancel leaves things as they were; reaching back never touches the export. | +| 5 | Error prevention | 4 | Days before the ring was paired are excluded. | +| 8 | Minimalist | 4 | One chip row, one button that disappears once used. | +| 10 | Help | 4 | One line on why, one on what's unaffected. | +| | **Total (of the five that apply)** | **20/20** | | + +### Polish (from the renders) + +- [fixed] "Include past days" and "End now" were two outlined buttons of equal weight. + "Include past days" is now tonal, the more useful action; "End now" stays outlined. +- [P3] The card then shows two stacked buttons. Kept: side by side they would wrap in Portuguese. + +No P0 or P1. + +## graphic-design-fundamentals (§13 checklist) + +- **Hierarchy:** title, then status, then a 12sp explainer, then the actions. +- **Colour:** no new colours; the tonal fill is `cardRaised`. +- **Consistency:** the chips match "How long" just above them in the dialog. +- **Real size:** checked at 411dp, 1.0 and 1.3. + +## less-is-more + +| Element | Verdict | +|---|---| +| Past-days chips | Kept: the owner's ask, and preset so starting a check takes no extra tap | +| A date picker for any start date | Left out: four chips cover it | +| Button on a running check | Kept: the owner's check may already be running; it disappears once used | +| A "re-score" step | Left out: the report re-scores by itself | + +No action gained a tap: the dialog's default already reaches back 14 days. diff --git a/docs/ring-comparison.md b/docs/ring-comparison.md index 1fea16ff..7b21fc74 100644 --- a/docs/ring-comparison.md +++ b/docs/ring-comparison.md @@ -74,6 +74,15 @@ The report opens with **Both rings against [reference]**: The per-measure cards and corrections below stay the main ring's. +**Past days count too** (owner, 2026-11-18: "make sure you grab historical data"). A check can +also grade days already stored: the start dialog's **Include past days** (none, 7, 14 or 30; +14 by default), or the same button on a running check. Grading then starts at local midnight +that many days back (`AccuracyCheckEntity.historyFrom`, DB v39), never before the main ring was +paired, since ring rows carry no device id. `startedAt` stays the real start, so the day count +and the export pause are unchanged: past days were exported long ago, and the reference reads +filter on `DataOrigin`, so those exports can't come back as the reference. The second ring +contributes whatever `comparison_readings` holds (its own backfill, about a week on a Colmi). + ## Not yet ⬜ - The background sync worker syncs only the main ring. The second ring catches up whenever the app