Modern Apps git

← Modern-Apps.git

health: canonical stored units enforced by a typed write seam

Commit
58f35addac849ce25170a67391968cd434fd37e1
Author
Vayun Mathur <[email protected]>
When
2026-11-21 20:23 UTC (14 days ago)
Parents
43966b0
Record values were raw doubles whose unit was convention
(mg/dL vs mmol/L, stored-m vs displayed-cm height), so one
wrong-unit producer could poison every chart aggregate. Now
a StoredUnit table declares the canonical unit per record
type (the invariant Health Connect typed units and FHIR
UCUM already guarantee at the boundary - no schema change,
no per-row units), value classes type the unit-sensitive
quantities (Kilograms, Centimeters->Meters,
MilligramsPerDeciliter, MillimetersOfMercury, Percent,
Liters, CelsiusDelta), the repository and producers
(SyncWorker, HealthViewModel, HealthAPI) write through typed
factories, and BodyLoggingDialog's Height /100 special case
is just Centimeters construction. The old Double entry points
stay deprecated toward the seam.

Verified: compile + targeted suites incl. 13 new round-trip
tests (HC->Room->HC per mirrored type, 41 nutrition fields
both directions). The full health suite times out at 2h on
pre-existing UI-test bulk - 3 unrelated failures documented
(HealthTodayW6Test never inits HealthAPI; a RecipeEditor
order flake) - and is triaged next.

Diff

health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/data/HealthAPI.ktindex de6ac659e2..a8c9dc175a 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt@@ -144,7 +144,10 @@ object HealthAPI {         }     } -    private fun nutritionRecord(record: Record): NutritionRecord? {+    // The builders below are internal (not private) as the export half of the typed+    // seam: UnitSafetyRoundTripTest feeds their output back through the Health+    // Connect import to prove HC -> Room -> HC round-trips per mirrored type.+    internal fun nutritionRecord(record: Record): NutritionRecord? {         val nd = record.nutritionData ?: return null         val startInstant = record.startTime         val endInstant = record.endTime@@ -199,7 +202,7 @@ object HealthAPI {         )     } -    private fun hydrationRecord(record: Record): HydrationRecord {+    internal fun hydrationRecord(record: Record): HydrationRecord {         val startInstant = record.startTime         val endInstant = record.endTime         return HydrationRecord(@@ -207,51 +210,51 @@ object HealthAPI {             startZoneOffset = systemOffsetAt(startInstant),             endTime = endInstant,             endZoneOffset = systemOffsetAt(endInstant),-            volume = Volume.liters(record.value),+            volume = Volume.liters(record.storedHydration().value),             metadata = Metadata.manualEntry(clientRecordId = record.id),         )     } -    private fun weightRecord(record: Record): WeightRecord = WeightRecord(+    internal fun weightRecord(record: Record): WeightRecord = WeightRecord(         time = record.startTime,         zoneOffset = systemOffsetAt(record.startTime),-        weight = Mass.kilograms(record.value),+        weight = Mass.kilograms(record.storedWeight().value),         metadata = Metadata.manualEntry(clientRecordId = record.id),     ) -    private fun heightRecord(record: Record): HeightRecord = HeightRecord(+    internal fun heightRecord(record: Record): HeightRecord = HeightRecord(         time = record.startTime,         zoneOffset = systemOffsetAt(record.startTime),-        height = Length.meters(record.value),+        height = Length.meters(record.storedHeight().value),         metadata = Metadata.manualEntry(clientRecordId = record.id),     ) -    private fun bodyFatRecord(record: Record): BodyFatRecord = BodyFatRecord(+    internal fun bodyFatRecord(record: Record): BodyFatRecord = BodyFatRecord(         time = record.startTime,         zoneOffset = systemOffsetAt(record.startTime),-        percentage = Percentage(record.value),+        percentage = Percentage(record.storedBodyFat().value),         metadata = Metadata.manualEntry(clientRecordId = record.id),     ) -    private fun leanBodyMassRecord(record: Record): LeanBodyMassRecord = LeanBodyMassRecord(+    internal fun leanBodyMassRecord(record: Record): LeanBodyMassRecord = LeanBodyMassRecord(         time = record.startTime,         zoneOffset = systemOffsetAt(record.startTime),-        mass = Mass.kilograms(record.value),+        mass = Mass.kilograms(record.storedLeanBodyMass().value),         metadata = Metadata.manualEntry(clientRecordId = record.id),     ) -    private fun boneMassRecord(record: Record): BoneMassRecord = BoneMassRecord(+    internal fun boneMassRecord(record: Record): BoneMassRecord = BoneMassRecord(         time = record.startTime,         zoneOffset = systemOffsetAt(record.startTime),-        mass = Mass.kilograms(record.value),+        mass = Mass.kilograms(record.storedBoneMass().value),         metadata = Metadata.manualEntry(clientRecordId = record.id),     ) -    private fun bodyWaterMassRecord(record: Record): BodyWaterMassRecord =+    internal fun bodyWaterMassRecord(record: Record): BodyWaterMassRecord =         BodyWaterMassRecord(             time = record.startTime,             zoneOffset = systemOffsetAt(record.startTime),-            mass = Mass.kilograms(record.value),+            mass = Mass.kilograms(record.storedBodyWaterMass().value),             metadata = Metadata.manualEntry(clientRecordId = record.id),         ) 
health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.ktindex d362acb2a1..fa1b75cbee 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -1,7 +1,13 @@ package com.vayunmathur.health.data  import android.content.Context+import com.vayunmathur.health.domain.Centimeters+import com.vayunmathur.health.domain.Kilograms+import com.vayunmathur.health.domain.Liters+import com.vayunmathur.health.domain.Meters+import com.vayunmathur.health.domain.Percent import com.vayunmathur.library.room.RoomRepository+import java.time.Instant import kotlinx.coroutines.flow.Flow  /**@@ -73,6 +79,43 @@ class HealthRepository private constructor(context: Context) :     suspend fun upsert(records: List<Record>) = dao.upsert(records)     suspend fun deleteByIds(ids: List<String>) = dao.deleteByIds(ids) +    // ------------------------------------------------------------------+    // Typed write seam — unit-sensitive logging entry points.+    //+    // These are the repository boundary for the types whose stored unit is a+    // physical quantity (see RecordType.storedUnit): callers hand over a typed+    // value (Kilograms, Meters/Centimeters, Percent, Liters) and the record is+    // built by the TypedRecords factories, so the canonical stored double is+    // produced in exactly one place. Prefer these over building a Record by+    // hand for these types; the plain upsert above stays for the+    // non-unit-sensitive types, payload records and test fixtures.+    // ------------------------------------------------------------------++    suspend fun upsertWeight(id: String, time: Instant, weight: Kilograms) =+        upsert(listOf(storedWeightRecord(id, time, weight)))++    suspend fun upsertHeight(id: String, time: Instant, height: Meters) =+        upsert(listOf(storedHeightRecord(id, time, height)))++    /** Height as entered/displayed (cm): stored as metres via [Centimeters.toMeters]. */+    suspend fun upsertHeight(id: String, time: Instant, height: Centimeters) =+        upsert(listOf(storedHeightRecord(id, time, height)))++    suspend fun upsertBodyFat(id: String, time: Instant, bodyFat: Percent) =+        upsert(listOf(storedBodyFatRecord(id, time, bodyFat)))++    suspend fun upsertLeanBodyMass(id: String, time: Instant, mass: Kilograms) =+        upsert(listOf(storedLeanBodyMassRecord(id, time, mass)))++    suspend fun upsertBoneMass(id: String, time: Instant, mass: Kilograms) =+        upsert(listOf(storedBoneMassRecord(id, time, mass)))++    suspend fun upsertBodyWaterMass(id: String, time: Instant, mass: Kilograms) =+        upsert(listOf(storedBodyWaterMassRecord(id, time, mass)))++    suspend fun upsertHydration(id: String, start: Instant, end: Instant, volume: Liters) =+        upsert(listOf(storedHydrationRecord(id, start, end, volume)))+     // Ingredients / Recipes     suspend fun insertIngredient(ingredient: Ingredient) = dao.insertIngredient(ingredient)     suspend fun updateIngredient(ingredient: Ingredient) = dao.updateIngredient(ingredient)
health/src/main/java/com/vayunmathur/health/data/StoredUnit.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/StoredUnit.kt b/health/src/main/java/com/vayunmathur/health/data/StoredUnit.ktnew file mode 100644index 0000000000..85f14994c1--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/data/StoredUnit.kt@@ -0,0 +1,171 @@+package com.vayunmathur.health.data++/**+ * A physical unit a stored [Record.value] (or [Record.secondaryValue]) is expressed in.+ *+ * [ucumCode] is the UCUM code — the same code FHIR `valueQuantity` carries+ * (`domain/FhirObservations.kt`, system `http://unitsofmeasure.org`) — and+ * [displaySymbol] is the symbol the UI shows for it (see `HealthMetricConfig.unit`).+ * Count-like metrics use [Count] (UCUM `1`, a dimensionless count of things).+ */+enum class StoredUnit(val ucumCode: String, val displaySymbol: String) {+    Count("1", "count"),+    Kilometers("km", "km"),+    Kilocalories("kcal", "cal"),+    KilocaloriesPerDay("kcal/d", "cal/day"),+    Meters("m", "m"),+    BeatsPerMinute("/min", "bpm"),+    Milliseconds("ms", "ms"),+    BreathsPerMinute("/min", "brpm"),+    Percent("%", "%"),+    MillimetersOfMercury("mm[Hg]", "mmHg"),+    MilligramsPerDeciliter("mg/dL", "mg/dL"),+    MillilitersPerMinuteKilogram("mL/(kg.min)", "ml/kg/min"),+    CelsiusDelta("Cel", "°C"),+    Kilograms("kg", "kg"),+    Grams("g", "g"),+    Milligrams("mg", "mg"),+    Micrograms("ug", "µg"),+    Hours("h", "hr"),+    Minutes("min", "min"),+    Liters("L", "L"),++    /** No physical unit: the number is a code (Exercise `secondaryValue` is an exercise-type id). */+    UnitlessCode("1", ""),+}++/**+ * The canonical stored unit of one [RecordType]: what [Record.value] means, what+ * [Record.secondaryValue] means when it is used at all, and any entry/display unit+ * that differs from the stored one.+ */+data class StoredUnitInfo(+    val unit: StoredUnit,+    val secondaryUnit: StoredUnit? = null,+    val note: String? = null,+)++/**+ * THE canonical-unit table: the stored unit of every [RecordType], enforced at the+ * repository boundary by the typed factories in `TypedRecords.kt`.+ *+ * This is a documented invariant, not a schema change: [Record] keeps its plain+ * `value`/`secondaryValue` doubles and there are deliberately no value+unit columns.+ * The invariant is already guaranteed from outside — Health Connect hands us typed+ * units (`Mass.inKilograms`, `Length.inMeters`, `Pressure.inMillimetersOfMercury`, …)+ * and FHIR quantities carry UCUM codes — so every producer converts to exactly the+ * unit below at its conversion line, and this table is what those lines agree on.+ * The round-trip tests (`UnitSafetyRoundTripTest`) are the checked contract for it.+ *+ * Height is the one metric whose stored unit differs from its entered/displayed+ * unit: stored metres, entered and displayed in centimetres (`HealthMetricConfig.HEIGHT`+ * shows "cm", `HealthChartData.scaleForDisplay` multiplies stored metres by 100).+ * That conversion lives only in `Centimeters.toMeters()` / `Meters.toCentimeters()`.+ */+fun RecordType.storedUnit(): StoredUnitInfo = when (this) {+    RecordType.Steps -> StoredUnitInfo(StoredUnit.Count, note = "Step count.")+    RecordType.Wheelchair -> StoredUnitInfo(StoredUnit.Count, note = "Wheelchair push count.")+    RecordType.Distance -> StoredUnitInfo(StoredUnit.Kilometers)+    RecordType.CaloriesTotal -> StoredUnitInfo(StoredUnit.Kilocalories)+    RecordType.CaloriesActive -> StoredUnitInfo(StoredUnit.Kilocalories)+    RecordType.CaloriesBasal -> StoredUnitInfo(StoredUnit.KilocaloriesPerDay)+    RecordType.Floors -> StoredUnitInfo(StoredUnit.Count, note = "Floors climbed.")+    RecordType.Elevation -> StoredUnitInfo(StoredUnit.Meters)+    RecordType.HeartRate -> StoredUnitInfo(StoredUnit.BeatsPerMinute)+    RecordType.RestingHeartRate -> StoredUnitInfo(StoredUnit.BeatsPerMinute)+    RecordType.HeartRateVariabilityRmssd -> StoredUnitInfo(StoredUnit.Milliseconds)+    RecordType.RespiratoryRate -> StoredUnitInfo(StoredUnit.BreathsPerMinute)+    RecordType.OxygenSaturation -> StoredUnitInfo(+        StoredUnit.Percent, note = "0–100 scale, not a fraction."+    )+    RecordType.BloodPressure -> StoredUnitInfo(+        StoredUnit.MillimetersOfMercury,+        secondaryUnit = StoredUnit.MillimetersOfMercury,+        note = "value = systolic, secondaryValue = diastolic, both mmHg.",+    )+    RecordType.BloodGlucose -> StoredUnitInfo(StoredUnit.MilligramsPerDeciliter)+    RecordType.Vo2Max -> StoredUnitInfo(StoredUnit.MillilitersPerMinuteKilogram)+    RecordType.SkinTemperature -> StoredUnitInfo(+        StoredUnit.CelsiusDelta, note = "Temperature delta vs baseline, not an absolute temperature."+    )+    RecordType.Weight -> StoredUnitInfo(StoredUnit.Kilograms)+    RecordType.Height -> StoredUnitInfo(+        StoredUnit.Meters,+        note = "Stored m, entered/displayed cm: entry converts via Centimeters.toMeters().",+    )+    RecordType.BodyFat -> StoredUnitInfo(StoredUnit.Percent, note = "0–100 scale, not a fraction.")+    RecordType.LeanBodyMass -> StoredUnitInfo(StoredUnit.Kilograms)+    RecordType.BoneMass -> StoredUnitInfo(StoredUnit.Kilograms)+    RecordType.BodyWaterMass -> StoredUnitInfo(StoredUnit.Kilograms)+    RecordType.Sleep -> StoredUnitInfo(+        StoredUnit.Hours, note = "Session duration; stage durations are SleepData millis."+    )+    RecordType.Mindfulness -> StoredUnitInfo(StoredUnit.Minutes, note = "Session duration.")+    RecordType.Hydration -> StoredUnitInfo(StoredUnit.Liters)+    RecordType.Nutrition -> StoredUnitInfo(+        StoredUnit.Kilocalories,+        note = "value = energy; NutritionData fields use NutritionStoredUnits (g / mg / µg / kcal).",+    )+    RecordType.Exercise -> StoredUnitInfo(+        StoredUnit.Minutes,+        secondaryUnit = StoredUnit.UnitlessCode,+        note = "value = duration minutes; secondaryValue = Health Connect exercise-type code.",+    )+}++/**+ * The stored unit of every `NutritionData` field, keyed by field name.+ *+ * Health Connect splits nutrients across three mass units, so the field — not the+ * record — carries the unit: macros in grams, most micronutrients in milligrams,+ * trace elements and several vitamins in micrograms, energy in kilocalories. The+ * Health Connect import (`HealthSyncWorker.toNutritionRecord`) reads each field+ * with the matching accessor (`inGrams` / `inMilligrams` / `inMicrograms`) and the+ * export (`HealthAPI` nutrition builder) writes it with the matching constructor;+ * `UnitSafetyRoundTripTest` pairs those two sides field by field.+ */+object NutritionStoredUnits {+    val byField: Map<String, StoredUnit> = mapOf(+        "protein" to StoredUnit.Grams,+        "carbohydrates" to StoredUnit.Grams,+        "fat" to StoredUnit.Grams,+        "fiber" to StoredUnit.Grams,+        "sugar" to StoredUnit.Grams,+        "sodium" to StoredUnit.Milligrams,+        "biotin" to StoredUnit.Micrograms,+        "caffeine" to StoredUnit.Milligrams,+        "calcium" to StoredUnit.Milligrams,+        "chloride" to StoredUnit.Milligrams,+        "cholesterol" to StoredUnit.Milligrams,+        "chromium" to StoredUnit.Micrograms,+        "copper" to StoredUnit.Milligrams,+        "folate" to StoredUnit.Micrograms,+        "folicAcid" to StoredUnit.Micrograms,+        "iodine" to StoredUnit.Micrograms,+        "iron" to StoredUnit.Milligrams,+        "magnesium" to StoredUnit.Milligrams,+        "manganese" to StoredUnit.Milligrams,+        "molybdenum" to StoredUnit.Micrograms,+        "monounsaturatedFat" to StoredUnit.Grams,+        "niacin" to StoredUnit.Milligrams,+        "pantothenicAcid" to StoredUnit.Milligrams,+        "phosphorus" to StoredUnit.Milligrams,+        "polyunsaturatedFat" to StoredUnit.Grams,+        "potassium" to StoredUnit.Milligrams,+        "riboflavin" to StoredUnit.Milligrams,+        "saturatedFat" to StoredUnit.Grams,+        "selenium" to StoredUnit.Micrograms,+        "thiamin" to StoredUnit.Milligrams,+        "transFat" to StoredUnit.Grams,+        "unsaturatedFat" to StoredUnit.Grams,+        "vitaminA" to StoredUnit.Micrograms,+        "vitaminB12" to StoredUnit.Micrograms,+        "vitaminB6" to StoredUnit.Milligrams,+        "vitaminC" to StoredUnit.Milligrams,+        "vitaminD" to StoredUnit.Micrograms,+        "vitaminE" to StoredUnit.Milligrams,+        "vitaminK" to StoredUnit.Micrograms,+        "zinc" to StoredUnit.Milligrams,+        "calories" to StoredUnit.Kilocalories,+    )+}
health/src/main/java/com/vayunmathur/health/data/TypedRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/TypedRecords.kt b/health/src/main/java/com/vayunmathur/health/data/TypedRecords.ktnew file mode 100644index 0000000000..4b14c03671--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/data/TypedRecords.kt@@ -0,0 +1,170 @@+package com.vayunmathur.health.data++import com.vayunmathur.health.domain.CelsiusDelta+import com.vayunmathur.health.domain.Centimeters+import com.vayunmathur.health.domain.Kilograms+import com.vayunmathur.health.domain.Liters+import com.vayunmathur.health.domain.Meters+import com.vayunmathur.health.domain.MilligramsPerDeciliter+import com.vayunmathur.health.domain.MillimetersOfMercury+import com.vayunmathur.health.domain.Percent+import java.time.Instant++/**+ * The typed write seam for unit-sensitive records — the one place a typed quantity+ * becomes a stored [Record] (and, via the `stored…()` accessors below, the one place+ * a stored [Record] is read back as a typed quantity).+ *+ * Why this exists: [Record.value] is a bare [Double], so before this seam a caller+ * could store centimetres where metres were expected and nothing anywhere would+ * notice — the logging dialog carried a hand-written `/ 100` for height to prevent+ * exactly that. Now the unit-sensitive producers (Health Connect import in+ * `sync/HealthSyncWorker.kt`, manual logging in `platform/HealthViewModel.kt`, and+ * the Health Connect export in `HealthAPI`) build and read records only through+ * these functions, each of which pins the canonical stored unit from+ * [RecordType.storedUnit]. The conversions themselves do not change: producers wrap+ * the double they already computed (`weight.inKilograms`, `height.inMeters`, …)+ * in the matching value class at the same line.+ *+ * Direct `Record(...)` construction remains available for the types that are not+ * unit-sensitive (counts, durations, codes, the Nutrition/Sleep/Exercise payloads —+ * Nutrition's per-field units live in [NutritionStoredUnits]) and for test fixtures.+ * New writes of a unit-sensitive type must go through here instead: constructing+ * one directly re-opens the unit hole this seam closes.+ */++// ---------------------------------------------------------------------------+// Body composition (stored kg / m / %, see StoredUnit table)+// ---------------------------------------------------------------------------++/** A Weight record: [weight] stored as kilograms. */+fun storedWeightRecord(id: String, time: Instant, weight: Kilograms, metadata: String? = "Weight"): Record =+    Record(id, 0, RecordType.Weight, time, time, weight.value, metadata = metadata)++/** A Height record: [height] stored as metres. */+fun storedHeightRecord(id: String, time: Instant, height: Meters, metadata: String? = "Height"): Record =+    Record(id, 0, RecordType.Height, time, time, height.value, metadata = metadata)++/** A Height record from the entered/displayed unit: centimetres in, stored metres out. */+fun storedHeightRecord(id: String, time: Instant, height: Centimeters, metadata: String? = "Height"): Record =+    storedHeightRecord(id, time, height.toMeters(), metadata)++/** A BodyFat record: [bodyFat] stored as a 0–100 percent. */+fun storedBodyFatRecord(id: String, time: Instant, bodyFat: Percent, metadata: String? = "Body Fat"): Record =+    Record(id, 0, RecordType.BodyFat, time, time, bodyFat.value, metadata = metadata)++/** A LeanBodyMass record: [mass] stored as kilograms. */+fun storedLeanBodyMassRecord(id: String, time: Instant, mass: Kilograms, metadata: String? = "Lean Body Mass"): Record =+    Record(id, 0, RecordType.LeanBodyMass, time, time, mass.value, metadata = metadata)++/** A BoneMass record: [mass] stored as kilograms. */+fun storedBoneMassRecord(id: String, time: Instant, mass: Kilograms, metadata: String? = "Bone Mass"): Record =+    Record(id, 0, RecordType.BoneMass, time, time, mass.value, metadata = metadata)++/** A BodyWaterMass record: [mass] stored as kilograms. */+fun storedBodyWaterMassRecord(id: String, time: Instant, mass: Kilograms, metadata: String? = "Body Water Mass"): Record =+    Record(id, 0, RecordType.BodyWaterMass, time, time, mass.value, metadata = metadata)++// ---------------------------------------------------------------------------+// Vitals (stored mg/dL / mmHg / % / °C-delta)+// ---------------------------------------------------------------------------++/** A BloodGlucose record: [level] stored as milligrams per decilitre. */+fun storedBloodGlucoseRecord(+    id: String,+    time: Instant,+    level: MilligramsPerDeciliter,+    metadata: String? = "Blood Glucose",+): Record = Record(id, 0, RecordType.BloodGlucose, time, time, level.value, metadata = metadata)++/** A BloodPressure record: systolic in `value`, diastolic in `secondaryValue`, both mmHg. */+fun storedBloodPressureRecord(+    id: String,+    time: Instant,+    systolic: MillimetersOfMercury,+    diastolic: MillimetersOfMercury,+    metadata: String? = "Blood Pressure",+): Record = Record(+    id, 0, RecordType.BloodPressure, time, time,+    systolic.value, diastolic.value, metadata = metadata,+)++/** An OxygenSaturation record: [saturation] stored as a 0–100 percent. */+fun storedOxygenSaturationRecord(+    id: String,+    time: Instant,+    saturation: Percent,+    metadata: String? = "Oxygen Saturation",+): Record = Record(id, 0, RecordType.OxygenSaturation, time, time, saturation.value, metadata = metadata)++/** One SkinTemperature sample ([index] within its source record): a Celsius delta. */+fun storedSkinTemperatureRecord(+    id: String,+    index: Int,+    time: Instant,+    delta: CelsiusDelta,+    metadata: String? = "Skin Temperature",+): Record = Record(id, index, RecordType.SkinTemperature, time, time, delta.value, metadata = metadata)++// ---------------------------------------------------------------------------+// Hydration (stored L)+// ---------------------------------------------------------------------------++/** A Hydration record over [start]–[end]: [volume] stored as litres. */+fun storedHydrationRecord(+    id: String,+    start: Instant,+    end: Instant,+    volume: Liters,+    metadata: String? = "Hydration",+): Record = Record(id, 0, RecordType.Hydration, start, end, volume.value, metadata = metadata)++// ---------------------------------------------------------------------------+// Typed reads back out of a stored record (the Health Connect export side)+// ---------------------------------------------------------------------------++private fun Record.requireType(expected: RecordType) {+    require(type == expected) { "Expected a $expected record, was $type" }+}++/** This Weight record's stored kilograms. */+fun Record.storedWeight(): Kilograms {+    requireType(RecordType.Weight)+    return Kilograms(value)+}++/** This Height record's stored metres. */+fun Record.storedHeight(): Meters {+    requireType(RecordType.Height)+    return Meters(value)+}++/** This BodyFat record's stored 0–100 percent. */+fun Record.storedBodyFat(): Percent {+    requireType(RecordType.BodyFat)+    return Percent(value)+}++/** This LeanBodyMass record's stored kilograms. */+fun Record.storedLeanBodyMass(): Kilograms {+    requireType(RecordType.LeanBodyMass)+    return Kilograms(value)+}++/** This BoneMass record's stored kilograms. */+fun Record.storedBoneMass(): Kilograms {+    requireType(RecordType.BoneMass)+    return Kilograms(value)+}++/** This BodyWaterMass record's stored kilograms. */+fun Record.storedBodyWaterMass(): Kilograms {+    requireType(RecordType.BodyWaterMass)+    return Kilograms(value)+}++/** This Hydration record's stored litres. */+fun Record.storedHydration(): Liters {+    requireType(RecordType.Hydration)+    return Liters(value)+}
health/src/main/java/com/vayunmathur/health/domain/MeasuredValues.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/MeasuredValues.kt b/health/src/main/java/com/vayunmathur/health/domain/MeasuredValues.ktnew file mode 100644index 0000000000..198be64125--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/domain/MeasuredValues.kt@@ -0,0 +1,66 @@+package com.vayunmathur.health.domain++/**+ * Typed quantities for the unit-sensitive health metrics.+ *+ * A bare [Double] carries no unit, so a centimetre value can be stored where a metre was+ * expected (and did: height needed a `/ 100` special case at the logging dialog). These+ * value classes make the unit part of the type at every logging / repository boundary:+ * callers state what they measured, and the conversion to the canonical stored unit+ * (see `StoredUnit` in `data/`) happens in exactly one place per pair.+ *+ * Pure Kotlin: no Android, no Health Connect types. The Health Connect conversions+ * (`Mass.kilograms(...)`, `Length.meters(...)`, ...) stay at the Health Connect+ * boundary in `data/HealthAPI.kt` and `sync/HealthSyncWorker.kt`, which wrap their+ * already-converted doubles in these types when building a stored record.+ */++/** Mass in kilograms: the canonical stored unit for Weight / LeanBodyMass / BoneMass / BodyWaterMass. */+@JvmInline+value class Kilograms(val value: Double)++/** Length in metres: the canonical stored unit for Height (and Elevation). */+@JvmInline+value class Meters(val value: Double) {+    /** The same length in centimetres, the unit height is entered and displayed in. */+    fun toCentimeters(): Centimeters = Centimeters(value * CENTIMETERS_PER_METER)++    /** Shared constants and helpers for Meters. */+    companion object {+        const val CENTIMETERS_PER_METER: Double = 100.0+    }+}++/** Length in centimetres: the unit height is entered and displayed in — never stored. */+@JvmInline+value class Centimeters(val value: Double) {+    /** The canonical stored form of this length. This is the one height conversion. */+    fun toMeters(): Meters = Meters(value / Meters.CENTIMETERS_PER_METER)+}++/** Blood glucose in milligrams per decilitre: the canonical stored unit for BloodGlucose. */+@JvmInline+value class MilligramsPerDeciliter(val value: Double)++/** Pressure in millimetres of mercury: systolic (stored `value`) and diastolic (`secondaryValue`). */+@JvmInline+value class MillimetersOfMercury(val value: Double)++/**+ * A percentage on the 0–100 scale Health Connect's `Percentage` uses (98.0 means 98%):+ * the canonical stored unit for OxygenSaturation and BodyFat. Not a 0.0–1.0 fraction.+ */+@JvmInline+value class Percent(val value: Double)++/** Volume in litres: the canonical stored unit for Hydration. */+@JvmInline+value class Liters(val value: Double)++/**+ * A skin-temperature *difference* in degrees Celsius, as Health Connect reports it+ * (`TemperatureDelta`): the canonical stored unit for SkinTemperature. A delta, not an+ * absolute temperature, so negative values are ordinary readings.+ */+@JvmInline+value class CelsiusDelta(val value: Double)
health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.ktindex aaf0246396..0ef53d0416 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt@@ -28,6 +28,18 @@ import com.vayunmathur.health.data.RecipeIngredient import com.vayunmathur.health.data.Record import com.vayunmathur.health.data.RecordType import com.vayunmathur.health.data.ServingUnit+import com.vayunmathur.health.data.storedBodyFatRecord+import com.vayunmathur.health.data.storedBodyWaterMassRecord+import com.vayunmathur.health.data.storedBoneMassRecord+import com.vayunmathur.health.data.storedHeightRecord+import com.vayunmathur.health.data.storedHydrationRecord+import com.vayunmathur.health.data.storedLeanBodyMassRecord+import com.vayunmathur.health.data.storedWeightRecord+import com.vayunmathur.health.domain.Centimeters+import com.vayunmathur.health.domain.Kilograms+import com.vayunmathur.health.domain.Liters+import com.vayunmathur.health.domain.Meters+import com.vayunmathur.health.domain.Percent import com.vayunmathur.health.ui.HealthMetricConfig import com.vayunmathur.health.ui.HistoryItem import com.vayunmathur.health.ui.MetricDashboardData@@ -272,25 +284,68 @@ class HealthViewModel(         viewModelScope.launch { HealthAPI.deleteRecord(record) }     } -    fun logHydration(liters: Double, time: java.time.Instant) {+    /** Stores [record] in Room, mirrors it to Health Connect, and refreshes the body metrics. */+    private fun logStoredRecord(record: Record, refreshBodyMetrics: Boolean = true) {         viewModelScope.launch {-            val record = Record(-                id = Uuid.random().toString(),-                index = 0,-                type = RecordType.Hydration,-                startTime = time,-                endTime = time,-                value = liters,-                metadata = "Hydration",-            )             repository.upsert(listOf(record))             HealthAPI.writeHealthRecord(record)+            if (refreshBodyMetrics) loadMainPageMetrics()         }     } +    /** Logs hydration as a typed volume: stored litres, mirrored as litres. */+    fun logHydration(volume: Liters, time: java.time.Instant) {+        logStoredRecord(+            storedHydrationRecord(Uuid.random().toString(), time, time, volume),+            refreshBodyMetrics = false,+        )+    }++    @Deprecated(+        "Bare doubles carry no unit; log a typed value instead (Liters for hydration, " ++            "Kilograms/Meters/Centimeters/Percent for body metrics) so the stored unit is checked. " ++            "See the typed write seam in data/TypedRecords.kt.",+    )+    fun logHydration(liters: Double, time: java.time.Instant) = logHydration(Liters(liters), time)++    /** Logs weight as a typed mass: stored kilograms, mirrored as kilograms. */+    fun logWeight(weight: Kilograms, time: java.time.Instant) =+        logStoredRecord(storedWeightRecord(Uuid.random().toString(), time, weight, RecordType.Weight.name))++    /** Logs height as a typed length: stored metres, mirrored as metres. */+    fun logHeight(height: Meters, time: java.time.Instant) =+        logStoredRecord(storedHeightRecord(Uuid.random().toString(), time, height, RecordType.Height.name))++    /** Logs height as entered/displayed (cm): the cm→m conversion is [Centimeters.toMeters]. */+    fun logHeight(height: Centimeters, time: java.time.Instant) = logHeight(height.toMeters(), time)++    /** Logs body fat as a typed percent: stored 0–100, mirrored as a percentage. */+    fun logBodyFat(bodyFat: Percent, time: java.time.Instant) =+        logStoredRecord(storedBodyFatRecord(Uuid.random().toString(), time, bodyFat, RecordType.BodyFat.name))++    /** Logs lean body mass as a typed mass: stored kilograms. */+    fun logLeanBodyMass(mass: Kilograms, time: java.time.Instant) = logStoredRecord(+        storedLeanBodyMassRecord(Uuid.random().toString(), time, mass, RecordType.LeanBodyMass.name)+    )++    /** Logs bone mass as a typed mass: stored kilograms. */+    fun logBoneMass(mass: Kilograms, time: java.time.Instant) =+        logStoredRecord(storedBoneMassRecord(Uuid.random().toString(), time, mass, RecordType.BoneMass.name))++    /** Logs body water mass as a typed mass: stored kilograms. */+    fun logBodyWaterMass(mass: Kilograms, time: java.time.Instant) = logStoredRecord(+        storedBodyWaterMassRecord(Uuid.random().toString(), time, mass, RecordType.BodyWaterMass.name)+    )++    @Deprecated(+        "Bare doubles carry no unit; log a typed value instead (Kilograms, Meters, " ++            "Centimeters or Percent via logWeight/logHeight/logBodyFat/...) so the stored " ++            "unit is checked. See the typed write seam in data/TypedRecords.kt. This overload " ++            "keeps its original semantics: [value] is already in the stored unit.",+    )     fun logBodyMetric(type: RecordType, value: Double, time: java.time.Instant) {-        viewModelScope.launch {-            val record = Record(+        logStoredRecord(+            Record(                 id = Uuid.random().toString(),                 index = 0,                 type = type,@@ -299,10 +354,7 @@ class HealthViewModel(                 value = value,                 metadata = type.name,             )-            repository.upsert(listOf(record))-            HealthAPI.writeHealthRecord(record)-            loadMainPageMetrics()-        }+        )     }      /** Type representing log meal target. */@@ -335,6 +387,9 @@ class HealthViewModel(                 is LogMealTarget.FromRecipe -> target.name                 is LogMealTarget.FromIngredient -> target.ingredient.displayName             }+            // Nutrition is a payload record, not a unit-sensitive scalar (value is+            // kilocalories; per-field units are NutritionStoredUnits), so it keeps+            // direct construction. Unit-sensitive scalars go through TypedRecords.             val record = Record(                 id = Uuid.random().toString(),                 index = 0,
health/src/main/java/com/vayunmathur/health/sync/HealthSyncWorker.kt
diff --git a/health/src/main/java/com/vayunmathur/health/sync/HealthSyncWorker.kt b/health/src/main/java/com/vayunmathur/health/sync/HealthSyncWorker.ktindex 530c64c335..0a54d1f605 100644--- a/health/src/main/java/com/vayunmathur/health/sync/HealthSyncWorker.kt+++ b/health/src/main/java/com/vayunmathur/health/sync/HealthSyncWorker.kt@@ -48,6 +48,24 @@ import com.vayunmathur.health.data.CLASSES import com.vayunmathur.health.data.HealthRepository import com.vayunmathur.health.data.Record import com.vayunmathur.health.data.RecordType+import com.vayunmathur.health.data.storedBloodGlucoseRecord+import com.vayunmathur.health.data.storedBloodPressureRecord+import com.vayunmathur.health.data.storedBodyFatRecord+import com.vayunmathur.health.data.storedBodyWaterMassRecord+import com.vayunmathur.health.data.storedBoneMassRecord+import com.vayunmathur.health.data.storedHeightRecord+import com.vayunmathur.health.data.storedHydrationRecord+import com.vayunmathur.health.data.storedLeanBodyMassRecord+import com.vayunmathur.health.data.storedOxygenSaturationRecord+import com.vayunmathur.health.data.storedSkinTemperatureRecord+import com.vayunmathur.health.data.storedWeightRecord+import com.vayunmathur.health.domain.CelsiusDelta+import com.vayunmathur.health.domain.Kilograms+import com.vayunmathur.health.domain.Liters+import com.vayunmathur.health.domain.Meters+import com.vayunmathur.health.domain.MilligramsPerDeciliter+import com.vayunmathur.health.domain.MillimetersOfMercury+import com.vayunmathur.health.domain.Percent import com.vayunmathur.health.platform.HealthConnectAvailability import com.vayunmathur.health.platform.HealthConnectSetup import com.vayunmathur.library.util.DataStoreUtils@@ -285,31 +303,25 @@ private fun androidx.health.connect.client.records.Record.toVitalsRecord(): List         is RespiratoryRateRecord -> simpleRecord(             RecordType.RespiratoryRate, this.time, this.time, this.rate, "Respiratory Rate"         )-        is OxygenSaturationRecord -> simpleRecord(-            RecordType.OxygenSaturation,-            this.time,-            this.time,-            this.percentage.value,-            "Oxygen Saturation",+        is OxygenSaturationRecord -> listOf(+            storedOxygenSaturationRecord(+                this.metadata.id, this.time, Percent(this.percentage.value)+            )         )         is BloodPressureRecord -> listOf(-            Record(+            storedBloodPressureRecord(                 this.metadata.id,-                0,-                RecordType.BloodPressure,                 this.time,-                this.time,-                this.systolic.inMillimetersOfMercury,-                this.diastolic.inMillimetersOfMercury,-                metadata = "Blood Pressure",+                MillimetersOfMercury(this.systolic.inMillimetersOfMercury),+                MillimetersOfMercury(this.diastolic.inMillimetersOfMercury),             )         )-        is BloodGlucoseRecord -> simpleRecord(-            RecordType.BloodGlucose,-            this.time,-            this.time,-            this.level.inMilligramsPerDeciliter,-            "Blood Glucose",+        is BloodGlucoseRecord -> listOf(+            storedBloodGlucoseRecord(+                this.metadata.id,+                this.time,+                MilligramsPerDeciliter(this.level.inMilligramsPerDeciliter),+            )         )         is Vo2MaxRecord -> simpleRecord(             RecordType.Vo2Max,@@ -337,44 +349,30 @@ private fun HeartRateRecord.toHeartRateRecords(): List<Record> =  private fun SkinTemperatureRecord.toSkinTemperatureRecords(): List<Record> =     this.deltas.mapIndexed { idx, delta ->-        Record(-            this.metadata.id,-            idx,-            RecordType.SkinTemperature,-            delta.time,-            delta.time,-            delta.delta.inCelsius,-            metadata = "Skin Temperature",+        storedSkinTemperatureRecord(+            this.metadata.id, idx, delta.time, CelsiusDelta(delta.delta.inCelsius)         )     }  private fun androidx.health.connect.client.records.Record.toBodyRecord(): List<Record> =     when (this) {-        is WeightRecord -> simpleRecord(-            RecordType.Weight, this.time, this.time, this.weight.inKilograms, "Weight"+        is WeightRecord -> listOf(+            storedWeightRecord(this.metadata.id, this.time, Kilograms(this.weight.inKilograms))         )-        is HeightRecord -> simpleRecord(-            RecordType.Height, this.time, this.time, this.height.inMeters, "Height"+        is HeightRecord -> listOf(+            storedHeightRecord(this.metadata.id, this.time, Meters(this.height.inMeters))         )-        is BodyFatRecord -> simpleRecord(-            RecordType.BodyFat, this.time, this.time, this.percentage.value, "Body Fat"+        is BodyFatRecord -> listOf(+            storedBodyFatRecord(this.metadata.id, this.time, Percent(this.percentage.value))         )-        is LeanBodyMassRecord -> simpleRecord(-            RecordType.LeanBodyMass,-            this.time,-            this.time,-            this.mass.inKilograms,-            "Lean Body Mass",+        is LeanBodyMassRecord -> listOf(+            storedLeanBodyMassRecord(this.metadata.id, this.time, Kilograms(this.mass.inKilograms))         )-        is BoneMassRecord -> simpleRecord(-            RecordType.BoneMass, this.time, this.time, this.mass.inKilograms, "Bone Mass"+        is BoneMassRecord -> listOf(+            storedBoneMassRecord(this.metadata.id, this.time, Kilograms(this.mass.inKilograms))         )-        is BodyWaterMassRecord -> simpleRecord(-            RecordType.BodyWaterMass,-            this.time,-            this.time,-            this.mass.inKilograms,-            "Body Water Mass",+        is BodyWaterMassRecord -> listOf(+            storedBodyWaterMassRecord(this.metadata.id, this.time, Kilograms(this.mass.inKilograms))         )         else -> throw IllegalArgumentException("Unsupported body record type")     }@@ -388,6 +386,10 @@ private fun androidx.health.connect.client.records.Record.simpleRecord(     metadata: String, ): List<Record> = listOf(Record(this.metadata.id, 0, type, start, end, value, metadata = metadata)) +// The Sleep/Mindfulness/Exercise/Nutrition builders below construct Record directly:+// they are not unit-sensitive scalars (durations and payload data; Nutrition's+// per-field units are NutritionStoredUnits). Unit-sensitive scalars must instead go+// through the TypedRecords factories — see data/TypedRecords.kt. private fun SleepSessionRecord.toSleepRecord(): List<Record> {     val stages = this.stages.map { stage ->         SleepStage(stage.startTime.toEpochMilli(), stage.endTime.toEpochMilli(), stage.stage)@@ -467,14 +469,8 @@ private fun ExerciseSessionRecord.toExerciseRecord(): List<Record> { }  private fun HydrationRecord.toHydrationRecord(): List<Record> = listOf(-    Record(-        this.metadata.id,-        0,-        RecordType.Hydration,-        this.startTime,-        this.endTime,-        this.volume.inLiters,-        metadata = "Hydration",+    storedHydrationRecord(+        this.metadata.id, this.startTime, this.endTime, Liters(this.volume.inLiters)     ) ) 
health/src/main/java/com/vayunmathur/health/ui/BodyLoggingDialog.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/BodyLoggingDialog.kt b/health/src/main/java/com/vayunmathur/health/ui/BodyLoggingDialog.ktindex c16652773c..9759c695f7 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BodyLoggingDialog.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BodyLoggingDialog.kt@@ -17,13 +17,18 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import com.vayunmathur.health.R+import com.vayunmathur.health.domain.Centimeters+import com.vayunmathur.health.domain.Kilograms+import com.vayunmathur.health.domain.Percent import com.vayunmathur.health.platform.HealthViewModel import java.time.Instant  /**  * Simple single-value logger for a body composition metric (weight, height, body fat, etc.).- * The entered value is in [HealthMetricConfig.unit]; height is converted from cm to meters- * before storage to match how records are persisted.+ * The entered value is in [HealthMetricConfig.unit] and is handed to the typed logging+ * seam as that unit: height is entered in centimetres and the centimetres→metres+ * conversion (the stored unit) happens inside [Centimeters.toMeters] — there is+ * deliberately no arithmetic on the raw double here.  */ @Composable fun LogBodyMetricDialog(@@ -54,9 +59,22 @@ fun LogBodyMetricDialog(                 enabled = isValid,                 onClick = {                     if (value != null) {-                        val storedValue =-                            if (config == HealthMetricConfig.HEIGHT) value / 100.0 else value-                        viewModel.logBodyMetric(config.recordType, storedValue, Instant.now())+                        // Typed seam: the entered unit is stated in the type, and the+                        // cm→m height conversion lives in Centimeters.toMeters().+                        when (config) {+                            HealthMetricConfig.HEIGHT -> viewModel.logHeight(Centimeters(value), Instant.now())+                            HealthMetricConfig.WEIGHT -> viewModel.logWeight(Kilograms(value), Instant.now())+                            HealthMetricConfig.BODY_FAT -> viewModel.logBodyFat(Percent(value), Instant.now())+                            HealthMetricConfig.LEAN_BODY_MASS ->+                                viewModel.logLeanBodyMass(Kilograms(value), Instant.now())+                            HealthMetricConfig.BONE_MASS -> viewModel.logBoneMass(Kilograms(value), Instant.now())+                            HealthMetricConfig.BODY_WATER_MASS ->+                                viewModel.logBodyWaterMass(Kilograms(value), Instant.now())+                            else -> {+                                @Suppress("DEPRECATION")+                                viewModel.logBodyMetric(config.recordType, value, Instant.now())+                            }+                        }                         onDismiss()                     }                 },
health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt b/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.ktindex 06f6bb1776..2a78c1ee0a 100644--- a/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt@@ -36,6 +36,7 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.health.R import com.vayunmathur.health.data.Ingredient import com.vayunmathur.health.data.Recipe+import com.vayunmathur.health.domain.Liters import com.vayunmathur.health.platform.HealthViewModel import java.time.Instant @@ -105,7 +106,7 @@ fun LogHydrationDialog(viewModel: HealthViewModel, initialTime: Instant? = null,                         onClick = {                             if (quantity != null) {                                 val time = initialTime ?: Instant.now()-                                viewModel.logHydration(quantity * selectedUnit.toLiters, time)+                                viewModel.logHydration(Liters(quantity * selectedUnit.toLiters), time)                                 onDismiss()                             }                         }
health/src/test/java/com/vayunmathur/health/data/UnitSafetyRoundTripTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/data/UnitSafetyRoundTripTest.kt b/health/src/test/java/com/vayunmathur/health/data/UnitSafetyRoundTripTest.ktnew file mode 100644index 0000000000..efc013064e--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/data/UnitSafetyRoundTripTest.kt@@ -0,0 +1,337 @@+package com.vayunmathur.health.data++import androidx.health.connect.client.records.BodyFatRecord+import androidx.health.connect.client.records.BodyWaterMassRecord+import androidx.health.connect.client.records.BoneMassRecord+import androidx.health.connect.client.records.HeightRecord+import androidx.health.connect.client.records.HydrationRecord+import androidx.health.connect.client.records.LeanBodyMassRecord+import androidx.health.connect.client.records.NutritionRecord+import androidx.health.connect.client.records.WeightRecord+import androidx.health.connect.client.records.metadata.Metadata+import androidx.health.connect.client.units.Energy+import androidx.health.connect.client.units.Length+import androidx.health.connect.client.units.Mass+import androidx.health.connect.client.units.Percentage+import androidx.health.connect.client.units.Volume+import com.vayunmathur.health.domain.CelsiusDelta+import com.vayunmathur.health.domain.Centimeters+import com.vayunmathur.health.domain.Kilograms+import com.vayunmathur.health.domain.Liters+import com.vayunmathur.health.domain.Meters+import com.vayunmathur.health.domain.MilligramsPerDeciliter+import com.vayunmathur.health.domain.MillimetersOfMercury+import com.vayunmathur.health.domain.Percent+import com.vayunmathur.health.sync.toRecord+import java.time.Instant+import java.time.ZoneOffset+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * The checked contract for the canonical stored units ([RecordType.storedUnit]):+ * Health Connect -> Room -> Health Connect round-trips for every mirrored type,+ * the cm -> m -> cm height path, and the nutrition field pairing between the+ * HealthAPI export constructors and the HealthSyncWorker import accessors.+ */+class UnitSafetyRoundTripTest {++    private val start: Instant = Instant.parse("2026-03-04T07:00:00Z")+    private val end: Instant = Instant.parse("2026-03-04T08:00:00Z")+    private val zone: ZoneOffset = ZoneOffset.UTC+    private fun meta(id: String) = Metadata.manualEntry(id)++    // ------------------------------------------------------------------+    // Step 1: the stored-unit table+    // ------------------------------------------------------------------++    @Test+    fun `stored unit table covers every record type`() {+        // storedUnit() is an exhaustive when, so this also fails to compile if a+        // RecordType is ever added without a canonical unit.+        assertEquals(RecordType.entries.size, RecordType.entries.map { it.storedUnit() }.size)+        assertEquals(StoredUnit.Kilograms, RecordType.Weight.storedUnit().unit)+        assertEquals(StoredUnit.Percent, RecordType.BodyFat.storedUnit().unit)+        assertEquals(StoredUnit.Liters, RecordType.Hydration.storedUnit().unit)+        assertEquals(StoredUnit.MilligramsPerDeciliter, RecordType.BloodGlucose.storedUnit().unit)+        assertEquals(StoredUnit.CelsiusDelta, RecordType.SkinTemperature.storedUnit().unit)+        assertEquals(StoredUnit.Kilocalories, RecordType.Nutrition.storedUnit().unit)+    }++    @Test+    fun `height is stored in metres and entered in centimetres`() {+        val info = RecordType.Height.storedUnit()+        assertEquals(StoredUnit.Meters, info.unit)+        assertEquals("m", info.unit.ucumCode)+        assertTrue(info.note!!.contains("Stored m, entered/displayed cm"), info.note)+    }++    @Test+    fun `blood pressure secondary value is also millimetres of mercury`() {+        val info = RecordType.BloodPressure.storedUnit()+        assertEquals(StoredUnit.MillimetersOfMercury, info.unit)+        assertEquals(StoredUnit.MillimetersOfMercury, info.secondaryUnit)+        assertEquals(StoredUnit.UnitlessCode, RecordType.Exercise.storedUnit().secondaryUnit)+    }++    // ------------------------------------------------------------------+    // Step 2: typed seam conversions+    // ------------------------------------------------------------------++    @Test+    fun `centimetres convert to stored metres and back`() {+        assertEquals(Meters(1.75), Centimeters(175.0).toMeters())+        assertEquals(Centimeters(175.0), Meters(1.75).toCentimeters())+        // The factory the logging dialog reaches (via logHeight(Centimeters)) stores m…+        val stored = storedHeightRecord("h-cm", start, Centimeters(175.0))+        assertEquals(RecordType.Height, stored.type)+        assertEquals(1.75, stored.value, 1e-9)+        // …and reading it back as metres converts losslessly back to entered cm.+        assertEquals(175.0, stored.storedHeight().toCentimeters().value, 1e-9)+    }++    @Test+    fun `typed factories store the canonical doubles`() {+        assertEquals(70.0, storedWeightRecord("w", start, Kilograms(70.0)).value, 1e-9)+        assertEquals(1.8, storedHeightRecord("h", start, Meters(1.8)).value, 1e-9)+        assertEquals(20.0, storedBodyFatRecord("bf", start, Percent(20.0)).value, 1e-9)+        assertEquals(55.0, storedLeanBodyMassRecord("lbm", start, Kilograms(55.0)).value, 1e-9)+        assertEquals(3.0, storedBoneMassRecord("bm", start, Kilograms(3.0)).value, 1e-9)+        assertEquals(35.0, storedBodyWaterMassRecord("bwm", start, Kilograms(35.0)).value, 1e-9)+        assertEquals(0.5, storedHydrationRecord("hy", start, end, Liters(0.5)).value, 1e-9)+        assertEquals(+            96.0,+            storedBloodGlucoseRecord("bg", start, MilligramsPerDeciliter(96.0)).value,+            1e-9,+        )+        val bp = storedBloodPressureRecord(+            "bp", start, MillimetersOfMercury(121.0), MillimetersOfMercury(79.0)+        )+        assertEquals(121.0, bp.value, 1e-9)+        assertEquals(79.0, bp.secondaryValue, 1e-9)+        assertEquals(98.0, storedOxygenSaturationRecord("o2", start, Percent(98.0)).value, 1e-9)+        // A temperature delta may be negative; the typed factory must not clamp it.+        assertEquals(+            -0.2,+            storedSkinTemperatureRecord("st", 1, start, CelsiusDelta(-0.2)).value,+            1e-9,+        )+    }++    @Test+    fun `typed reads reject the wrong record type`() {+        val weight = storedWeightRecord("w", start, Kilograms(70.0))+        assertEquals(Kilograms(70.0), weight.storedWeight())+        assertFailsWith<IllegalArgumentException> { weight.storedHeight() }+        assertFailsWith<IllegalArgumentException> { weight.storedHydration() }+    }++    // ------------------------------------------------------------------+    // Step 3a: HC -> Room -> HC for the mirrored (writable) types+    // ------------------------------------------------------------------++    @Test+    fun `weight round-trips hc to room to hc`() {+        val room = WeightRecord(start, zone, Mass.kilograms(70.0), meta("wt")).toRecord().single()+        assertEquals(70.0, room.value, 1e-9)+        val exported = HealthAPI.weightRecord(room)+        assertEquals(70.0, exported.weight.inKilograms, 1e-9)+        assertEquals(70.0, exported.toRecord().single().value, 1e-9)+    }++    @Test+    fun `height round-trips hc to room to hc in metres`() {+        val room = HeightRecord(start, zone, Length.meters(1.8), meta("ht")).toRecord().single()+        assertEquals(1.8, room.value, 1e-9)+        val exported = HealthAPI.heightRecord(room)+        assertEquals(1.8, exported.height.inMeters, 1e-9)+        assertEquals(180.0, exported.height.inMeters.let { Meters(it).toCentimeters().value }, 1e-9)+        assertEquals(1.8, exported.toRecord().single().value, 1e-9)+    }++    @Test+    fun `body composition round-trips hc to room to hc`() {+        val fat = BodyFatRecord(start, zone, Percentage(20.0), meta("bf")).toRecord().single()+        assertEquals(20.0, HealthAPI.bodyFatRecord(fat).percentage.value, 1e-9)+        assertEquals(20.0, HealthAPI.bodyFatRecord(fat).toRecord().single().value, 1e-9)++        val lean = LeanBodyMassRecord(start, zone, Mass.kilograms(55.0), meta("lbm")).toRecord().single()+        assertEquals(55.0, HealthAPI.leanBodyMassRecord(lean).mass.inKilograms, 1e-9)+        assertEquals(55.0, HealthAPI.leanBodyMassRecord(lean).toRecord().single().value, 1e-9)++        val bone = BoneMassRecord(start, zone, Mass.kilograms(3.0), meta("bm")).toRecord().single()+        assertEquals(3.0, HealthAPI.boneMassRecord(bone).mass.inKilograms, 1e-9)+        assertEquals(3.0, HealthAPI.boneMassRecord(bone).toRecord().single().value, 1e-9)++        val water = BodyWaterMassRecord(start, zone, Mass.kilograms(35.0), meta("bwm")).toRecord().single()+        assertEquals(35.0, HealthAPI.bodyWaterMassRecord(water).mass.inKilograms, 1e-9)+        assertEquals(35.0, HealthAPI.bodyWaterMassRecord(water).toRecord().single().value, 1e-9)+    }++    @Test+    fun `hydration round-trips hc to room to hc in litres`() {+        val room = HydrationRecord(start, zone, end, zone, Volume.liters(0.5), meta("hy"))+            .toRecord().single()+        assertEquals(0.5, room.value, 1e-9)+        val exported = HealthAPI.hydrationRecord(room)+        assertEquals(0.5, exported.volume.inLiters, 1e-9)+        assertEquals(0.5, exported.toRecord().single().value, 1e-9)+    }++    // ------------------------------------------------------------------+    // Step 3b: nutrition field pairing (export constructors vs import accessors)+    // ------------------------------------------------------------------++    /** One nutrient: its stored unit plus how to read it back off each side. */+    private data class NutrientCase(+        val name: String,+        val unit: StoredUnit,+        val room: (NutritionData) -> Double,+        val hcMass: (NutritionRecord) -> Mass?,+    ) {+        /** The HC value read in this field's stored unit (kcal is energy, not a mass). */+        fun hc(rec: NutritionRecord): Double? =+            if (name == "calories") {+                rec.energy?.inKilocalories+            } else {+                when (unit) {+                    StoredUnit.Grams -> hcMass(rec)?.inGrams+                    StoredUnit.Milligrams -> hcMass(rec)?.inMilligrams+                    StoredUnit.Micrograms -> hcMass(rec)?.inMicrograms+                    else -> hcMass(rec)?.inGrams+                }+            }+    }++    private val nutrientCases: List<NutrientCase> = listOf(+        NutrientCase("protein", StoredUnit.Grams, { it.protein }, { it.protein }),+        NutrientCase("carbohydrates", StoredUnit.Grams, { it.carbohydrates }, { it.totalCarbohydrate }),+        NutrientCase("fat", StoredUnit.Grams, { it.fat }, { it.totalFat }),+        NutrientCase("fiber", StoredUnit.Grams, { it.fiber }, { it.dietaryFiber }),+        NutrientCase("sugar", StoredUnit.Grams, { it.sugar }, { it.sugar }),+        NutrientCase("sodium", StoredUnit.Milligrams, { it.sodium }, { it.sodium }),+        NutrientCase("biotin", StoredUnit.Micrograms, { it.biotin }, { it.biotin }),+        NutrientCase("caffeine", StoredUnit.Milligrams, { it.caffeine }, { it.caffeine }),+        NutrientCase("calcium", StoredUnit.Milligrams, { it.calcium }, { it.calcium }),+        NutrientCase("chloride", StoredUnit.Milligrams, { it.chloride }, { it.chloride }),+        NutrientCase("cholesterol", StoredUnit.Milligrams, { it.cholesterol }, { it.cholesterol }),+        NutrientCase("chromium", StoredUnit.Micrograms, { it.chromium }, { it.chromium }),+        NutrientCase("copper", StoredUnit.Milligrams, { it.copper }, { it.copper }),+        NutrientCase("folate", StoredUnit.Micrograms, { it.folate }, { it.folate }),+        NutrientCase("folicAcid", StoredUnit.Micrograms, { it.folicAcid }, { it.folicAcid }),+        NutrientCase("iodine", StoredUnit.Micrograms, { it.iodine }, { it.iodine }),+        NutrientCase("iron", StoredUnit.Milligrams, { it.iron }, { it.iron }),+        NutrientCase("magnesium", StoredUnit.Milligrams, { it.magnesium }, { it.magnesium }),+        NutrientCase("manganese", StoredUnit.Milligrams, { it.manganese }, { it.manganese }),+        NutrientCase("molybdenum", StoredUnit.Micrograms, { it.molybdenum }, { it.molybdenum }),+        NutrientCase("monounsaturatedFat", StoredUnit.Grams, { it.monounsaturatedFat }, { it.monounsaturatedFat }),+        NutrientCase("niacin", StoredUnit.Milligrams, { it.niacin }, { it.niacin }),+        NutrientCase("pantothenicAcid", StoredUnit.Milligrams, { it.pantothenicAcid }, { it.pantothenicAcid }),+        NutrientCase("phosphorus", StoredUnit.Milligrams, { it.phosphorus }, { it.phosphorus }),+        NutrientCase("polyunsaturatedFat", StoredUnit.Grams, { it.polyunsaturatedFat }, { it.polyunsaturatedFat }),+        NutrientCase("potassium", StoredUnit.Milligrams, { it.potassium }, { it.potassium }),+        NutrientCase("riboflavin", StoredUnit.Milligrams, { it.riboflavin }, { it.riboflavin }),+        NutrientCase("saturatedFat", StoredUnit.Grams, { it.saturatedFat }, { it.saturatedFat }),+        NutrientCase("selenium", StoredUnit.Micrograms, { it.selenium }, { it.selenium }),+        NutrientCase("thiamin", StoredUnit.Milligrams, { it.thiamin }, { it.thiamin }),+        NutrientCase("transFat", StoredUnit.Grams, { it.transFat }, { it.transFat }),+        NutrientCase("unsaturatedFat", StoredUnit.Grams, { it.unsaturatedFat }, { it.unsaturatedFat }),+        NutrientCase("vitaminA", StoredUnit.Micrograms, { it.vitaminA }, { it.vitaminA }),+        NutrientCase("vitaminB12", StoredUnit.Micrograms, { it.vitaminB12 }, { it.vitaminB12 }),+        NutrientCase("vitaminB6", StoredUnit.Milligrams, { it.vitaminB6 }, { it.vitaminB6 }),+        NutrientCase("vitaminC", StoredUnit.Milligrams, { it.vitaminC }, { it.vitaminC }),+        NutrientCase("vitaminD", StoredUnit.Micrograms, { it.vitaminD }, { it.vitaminD }),+        NutrientCase("vitaminE", StoredUnit.Milligrams, { it.vitaminE }, { it.vitaminE }),+        NutrientCase("vitaminK", StoredUnit.Micrograms, { it.vitaminK }, { it.vitaminK }),+        NutrientCase("zinc", StoredUnit.Milligrams, { it.zinc }, { it.zinc }),+        // Energy is not a Mass: hcMass is unused for calories (see NutrientCase.hc).+        NutrientCase("calories", StoredUnit.Kilocalories, { it.calories }, { null }),+    )++    /** Distinct sentinel per field (index + 1) so a swapped pairing cannot pass. */+    private fun sentinel(index: Int): Double = (index + 1).toDouble()++    private fun hcNutritionWithSentinels(): NutritionRecord {+        fun g(i: Int) = Mass.grams(sentinel(i))+        fun mg(i: Int) = Mass.milligrams(sentinel(i))+        fun ug(i: Int) = Mass.micrograms(sentinel(i))+        // Argument order follows nutrientCases; values are (case index + 1).+        return NutritionRecord(+            metadata = meta("nut-pair"), startTime = start, startZoneOffset = zone,+            endTime = end, endZoneOffset = zone, name = "Pairing Meal",+            protein = g(0), totalCarbohydrate = g(1), totalFat = g(2), dietaryFiber = g(3),+            sugar = g(4), sodium = mg(5), biotin = ug(6), caffeine = mg(7), calcium = mg(8),+            chloride = mg(9), cholesterol = mg(10), chromium = ug(11), copper = mg(12),+            folate = ug(13), folicAcid = ug(14), iodine = ug(15), iron = mg(16),+            magnesium = mg(17), manganese = mg(18), molybdenum = ug(19),+            monounsaturatedFat = g(20), niacin = mg(21), pantothenicAcid = mg(22),+            phosphorus = mg(23), polyunsaturatedFat = g(24), potassium = mg(25),+            riboflavin = mg(26), saturatedFat = g(27), selenium = ug(28), thiamin = mg(29),+            transFat = g(30), unsaturatedFat = g(31), vitaminA = ug(32), vitaminB12 = ug(33),+            vitaminB6 = mg(34), vitaminC = mg(35), vitaminD = ug(36), vitaminE = mg(37),+            vitaminK = ug(38), zinc = mg(39), energy = Energy.kilocalories(sentinel(40)),+        )+    }++    private fun roomNutritionWithSentinels(): NutritionData = NutritionData(+        protein = sentinel(0), carbohydrates = sentinel(1), fat = sentinel(2),+        fiber = sentinel(3), sugar = sentinel(4), sodium = sentinel(5), biotin = sentinel(6),+        caffeine = sentinel(7), calcium = sentinel(8), chloride = sentinel(9),+        cholesterol = sentinel(10), chromium = sentinel(11), copper = sentinel(12),+        folate = sentinel(13), folicAcid = sentinel(14), iodine = sentinel(15),+        iron = sentinel(16), magnesium = sentinel(17), manganese = sentinel(18),+        molybdenum = sentinel(19), monounsaturatedFat = sentinel(20), niacin = sentinel(21),+        pantothenicAcid = sentinel(22), phosphorus = sentinel(23),+        polyunsaturatedFat = sentinel(24), potassium = sentinel(25), riboflavin = sentinel(26),+        saturatedFat = sentinel(27), selenium = sentinel(28), thiamin = sentinel(29),+        transFat = sentinel(30), unsaturatedFat = sentinel(31), vitaminA = sentinel(32),+        vitaminB12 = sentinel(33), vitaminB6 = sentinel(34), vitaminC = sentinel(35),+        vitaminD = sentinel(36), vitaminE = sentinel(37), vitaminK = sentinel(38),+        zinc = sentinel(39), calories = sentinel(40),+    )++    @Test+    fun `nutrition field pairing table matches the stored unit table`() {+        assertEquals(nutrientCases.map { it.name }.toSet(), NutritionStoredUnits.byField.keys)+        nutrientCases.forEach { case ->+            assertEquals(case.unit, NutritionStoredUnits.byField[case.name], case.name)+        }+    }++    @Test+    fun `nutrition import pairs every hc field with the same room field`() {+        val imported = hcNutritionWithSentinels().toRecord().single()+        assertEquals(sentinel(40), imported.value, 1e-9, "energy -> Record.value (kcal)")+        val data = assertNotNull(imported.nutritionData)+        nutrientCases.forEachIndexed { index, case ->+            assertEquals(sentinel(index), case.room(data), 1e-9, "import field ${case.name}")+        }+        // …and the full HC -> Room -> HC trip returns every field to its HC accessor.+        val exported = assertNotNull(HealthAPI.nutritionRecord(imported))+        nutrientCases.forEachIndexed { index, case ->+            assertEquals(sentinel(index), case.hc(exported) ?: Double.NaN, 1e-9, "round-trip ${case.name}")+        }+    }++    @Test+    fun `nutrition export pairs every room field with the same hc field`() {+        val data = roomNutritionWithSentinels()+        val record = Record(+            id = "nut-export", index = 0, type = RecordType.Nutrition,+            startTime = start, endTime = end, value = data.calories,+            nutritionData = data, metadata = "Pairing Meal",+        )+        val exported = assertNotNull(HealthAPI.nutritionRecord(record))+        nutrientCases.forEachIndexed { index, case ->+            assertEquals(sentinel(index), case.hc(exported) ?: Double.NaN, 1e-9, "export field ${case.name}")+        }+        // …and importing that export reproduces the room fields (Room -> HC -> Room).+        val reimported = assertNotNull(exported.toRecord().single().nutritionData)+        nutrientCases.forEachIndexed { index, case ->+            assertEquals(sentinel(index), case.room(reimported), 1e-9, "reimport field ${case.name}")+        }+    }+}