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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1137,6 +1137,30 @@ sources: `docs/postpartum-breastfeeding-research.md`.
switching off takes exactly that back.
- **No F*cking Health jokes here**: postpartum text is on the voice's safety list.

## Lab reports: read once, checked by the user, never a diagnosis

**Read this before touching `service/LabReports.kt`, `ui/screens/LabReportsUi.kt` or the coach's
`labs` block.** Any lab report (blood, urine, hormones, anything) is added as a PDF from
My Health → Lab reports, and every marker is charted exam by exam.

- **Pages go to the model as images, not as a PDF** (`PdfRenderer`, 1600 px, up to 10 pages), so
every coach provider reads them, the custom/local one included. The PDF is sent once, when the
user adds it; afterwards the coach reads the stored values (`LabContext`), never the file.
- **Nothing is saved until the user checks it.** The read lands on a review screen where every
value, unit and range is editable and rows can be removed. Don't add an auto-save path.
- **The flag is computed, not taken from the model**: a numeric value with a printed range is judged
against that range (`LabReports.flagFor`); the model's marking only stands when there is no number
or no range. The range is the lab's own and is stored per result, because labs and methods differ.
- **One marker, one key, across labs and languages** (`markerKey`, from the model's snake_case
English `key`, normalised). The chart follows the key, so a key change splits a marker's history.
- **It never diagnoses.** No condition named, no value called fine or dangerous beyond "inside / outside
the lab's range", anything outside the range or trending badly goes to "your doctor", and never a
medication, supplement or dose. The coach's `LabContext.note` and its prompt line say the same; keep
them in step. Goals change only through `set_goal` after the user agrees to the exact numbers.
- **The coach's use of the results is a switch on the Lab reports screen** (`LabPrefs.coachUses`).
- **Reports, results and each PDF (as base64) ride in the backup archive**, and the switch rides in
`ArchivedSettings`. Deleting a report removes its results (FK cascade) and its PDF file.

## The design files and the app move together, both ways

**Every change to the app's UI updates the design files in the same piece of work, and every
Expand Down
64 changes: 64 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class PulseLoopApplication : Application() {
CrashLogger.install(this)
com.pulseloop.service.DrinkPrefs.init(this)
com.pulseloop.service.Postpartum.init(this)
com.pulseloop.service.LabPrefs.init(this)
com.pulseloop.ui.theme.FairyMode.init(this)
com.pulseloop.ui.i18n.L10n.init(this)
com.pulseloop.health.source.HealthConnectSource.isEnabled(this) // warms [HealthConnectSource.enabledNow]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ object CoachContextBuilder {
primaryGoal = runCatching { com.pulseloop.service.GoalPlan.load(db, now) }.getOrNull(),
drinks = com.pulseloop.service.DrinksContext.build(db, now),
postpartum = com.pulseloop.service.PostpartumContext.build(),
labs = runCatching { com.pulseloop.service.LabContext.build(db) }.getOrNull(),
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Core behavior:
- When a goal exists, tie advice to it. Call get_goal for anything about progress, calories or what to eat or do; start from its `levers` marked short, and use its numbers as given: the scale's trend, the suggested intake against what they burn and log, protein, sleep and steps. Name the one or two levers that matter most this week (e.g. "you average 2,350 eaten against a 1,950 target", "sleep under 6 h raises hunger"). Never go below its intake floor, never set weight targets the user didn't ask for, and never judge their body.
- Meal suggestions: the Nutrition screen shows a next-meal idea (call suggest_next_meal to see the same one). When the user wants alternatives, offer two or three everyday Brazilian options or common fruits that fit the calories left and the protein gap, with rough kcal. When they push back with something they prefer, check it against the goal (get_goal) and the calories left: if it fits, agree and call save_food_preference so future suggestions use it; if it doesn't, say why and offer a version that fits (a smaller portion, a different time). Don't save a preference the user didn't agree to.
- Drinks: when the packet has a `drinks` block, the user is cutting down on alcohol and tracks it. Be warm and matter-of-fact, never moralising; no "relapse", "sober" or labels. Use their own numbers (this week against the limit, dry days, tonight's plan, what drinking did to their nights from `lastNightEffect`) and say these effects are a pattern in their data, not proof. Help them plan: a number for tonight decided in advance (set_drink_plan once they agree), alternating with water or something alcohol-free, eating first, a set time to stop, a first drink that isn't alcohol. Log a drink with log_drink only when they tell you they had one. If they describe drinking most days, heavy amounts, morning drinking, or shakes or sweating when they stop, tell them not to stop all at once (withdrawal can be dangerous) and to see a doctor; in Brazil, CAPS AD gives free care. Without a `drinks` block, don't bring alcohol up unless they do.
- Lab results: when the packet has a `labs` block, the user added their own lab reports and checked the values. Follow its `note`. Use the numbers as given, with the date and the lab's own range; say how a marker moved across reports (`earlier`). Never diagnose or name what a result means medically, and never call a value fine or dangerous beyond whether it is inside the printed range; anything outside the range or moving the wrong way is for their doctor, so say so plainly. Never suggest a medication, supplement or dose. When they ask for a plan, link the markers to habits in their own data (steps, sleep, active minutes, meals), propose exact daily goals, and call set_goal only after they agree to those numbers; food changes are suggestions, not goals.
- When the context packet includes an `environment` block (the user's city + current weather), use it to ground practical suggestions — outdoor vs indoor workouts, hydration on hot days, planning around rain. Never reference the user's location more precisely than the city.

Data limitations:
Expand Down Expand Up @@ -77,6 +78,8 @@ data class CoachContextPacket(
val drinks: com.pulseloop.service.DrinksContext? = null,
/** The postpartum life stage, when she switched it on in her profile; null otherwise. */
val postpartum: com.pulseloop.service.PostpartumContext? = null,
/** Lab results the user added and checked; null when none, or when they switched it off. */
val labs: com.pulseloop.service.LabContext? = null,
) {
@kotlinx.serialization.Serializable
data class ProfileContext(
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ object ArchivedSettings {
"activity_detection" to emptySet(),
// Rest Mode, while it lasts.
"rest_mode" to emptySet(),
// Whether the coach may use the lab results.
"lab_reports" to emptySet(),
)

/**
Expand Down
16 changes: 16 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchive.kt
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,22 @@ data class PulseArchive(
* before it existed, and a restore then leaves this phone's own values alone.
*/
val settings: Map<String, Map<String, PrefValue>> = emptyMap(),
/** Lab reports (v37), each with its PDF as base64 so a new phone can open it again. */
val labReports: List<LabReportDTO> = emptyList(),
val labResults: List<LabResultDTO> = emptyList(),
)

@Serializable data class LabReportDTO(
val id: String, val collectedDay: Long, val lab: String? = null, val kindsCsv: String = "",
val fileName: String? = null, val pdfFile: String? = null, val pageCount: Int = 0, val createdAt: Long,
val pdfBase64: String? = null,
)

@Serializable data class LabResultDTO(
val id: String, val reportId: String, val panel: String, val name: String, val markerKey: String,
val valueNum: Double? = null, val valueText: String? = null, val unit: String? = null,
val refLow: Double? = null, val refHigh: Double? = null, val refText: String? = null,
val flag: String = "UNKNOWN", val position: Int = 0,
)

@Serializable data class AccuracyCheckDTO(
Expand Down
41 changes: 41 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,26 @@ object DataArchiveService {
)
},
settings = context?.let { ArchivedSettings.export(it) } ?: emptyMap(),
labReports = collect("lab_reports") { c ->
val pdf = c.strOrNull("pdfFile")
LabReportDTO(
id = c.str("id"), collectedDay = c.long("collectedDay"), lab = c.strOrNull("lab"),
kindsCsv = c.strOrNull("kindsCsv") ?: "", fileName = c.strOrNull("fileName"), pdfFile = pdf,
pageCount = c.intOrNull("pageCount") ?: 0, createdAt = c.long("createdAt"),
pdfBase64 = if (context != null && pdf != null) runCatching {
com.pulseloop.service.LabReports.pdfFile(context, pdf).takeIf { it.exists() }
?.readBytes()?.let { android.util.Base64.encodeToString(it, android.util.Base64.NO_WRAP) }
}.getOrNull() else null,
)
},
labResults = collect("lab_results") { c ->
LabResultDTO(
id = c.str("id"), reportId = c.str("reportId"), panel = c.str("panel"), name = c.str("name"),
markerKey = c.str("markerKey"), valueNum = c.dblOrNull("valueNum"), valueText = c.strOrNull("valueText"),
unit = c.strOrNull("unit"), refLow = c.dblOrNull("refLow"), refHigh = c.dblOrNull("refHigh"),
refText = c.strOrNull("refText"), flag = c.strOrNull("flag") ?: "UNKNOWN", position = c.intOrNull("position") ?: 0,
)
},
accuracyCorrections = collect("accuracy_corrections") { c ->
AccuracyCorrectionDTO(
deviceKey = c.str("deviceKey"), metric = c.str("metric"), kind = c.str("kind"),
Expand Down Expand Up @@ -516,6 +536,27 @@ object DataArchiveService {
for (p in archive.periods) {
db.periodDao().upsert(PeriodEntity(id = p.id, startDay = p.startDay, endDay = p.endDay, createdAt = p.createdAt))
}
for (r in archive.labReports) {
// The PDF goes back to the app's own storage before its row points at it.
val b64 = r.pdfBase64
val name = r.pdfFile
val pdf = if (b64 != null && name != null) runCatching {
com.pulseloop.service.LabReports.pdfFile(context, name)
.writeBytes(android.util.Base64.decode(b64, android.util.Base64.NO_WRAP))
name
}.getOrNull() else null
db.labDao().upsertReport(LabReportEntity(
id = r.id, collectedDay = r.collectedDay, lab = r.lab, kindsCsv = r.kindsCsv,
fileName = r.fileName, pdfFile = pdf, pageCount = r.pageCount, createdAt = r.createdAt,
))
}
if (archive.labResults.isNotEmpty()) db.labDao().upsertResults(archive.labResults.map { x ->
LabResultEntity(
id = x.id, reportId = x.reportId, panel = x.panel, name = x.name, markerKey = x.markerKey,
valueNum = x.valueNum, valueText = x.valueText, unit = x.unit, refLow = x.refLow,
refHigh = x.refHigh, refText = x.refText, flag = x.flag, position = x.position,
)
})
for (d in archive.drinks) {
db.drinkDao().upsert(DrinkEntryEntity(
id = d.id, timestamp = d.timestamp, day = d.day, type = d.type, volumeMl = d.volumeMl,
Expand Down
28 changes: 27 additions & 1 deletion app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ import com.pulseloop.data.entity.*
AccuracyPausedUnitEntity::class,
AccuracyCheckDayEntity::class,
AccuracyCorrectionEntity::class,
LabReportEntity::class,
LabResultEntity::class,
],
version = 36,
version = 37,
exportSchema = false,
)
abstract class PulseLoopDatabase : RoomDatabase() {
Expand Down Expand Up @@ -105,6 +107,8 @@ abstract class PulseLoopDatabase : RoomDatabase() {
abstract fun foodProductDao(): FoodProductDao
/** Journal tags for "what affects you" insights. */
abstract fun journalDao(): JournalDao
/** Lab reports the user added as PDFs, and the markers read from them (v37). */
abstract fun labDao(): LabDao

/**
* Empty every table, atomically. Goes through Room's [withTransaction] rather than a raw
Expand Down Expand Up @@ -149,6 +153,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
"periods",
"meds", "med_doses",
"accuracy_checks", "accuracy_paused_units", "accuracy_check_days", "accuracy_corrections",
"lab_reports", "lab_results",
)

@Volatile private var INSTANCE: PulseLoopDatabase? = null
Expand Down Expand Up @@ -691,6 +696,26 @@ abstract class PulseLoopDatabase : RoomDatabase() {
}
}

/** v36 → v37: lab reports added as PDFs, and the markers read from them. */
private val MIGRATION_36_37 = object : Migration(36, 37) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `lab_reports` (`id` TEXT NOT NULL, `collectedDay` INTEGER NOT NULL, " +
"`lab` TEXT, `kindsCsv` TEXT NOT NULL, `fileName` TEXT, `pdfFile` TEXT, `pageCount` INTEGER NOT NULL, " +
"`createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
db.execSQL("CREATE INDEX IF NOT EXISTS `index_lab_reports_collectedDay` ON `lab_reports` (`collectedDay`)")
db.execSQL(
"CREATE TABLE IF NOT EXISTS `lab_results` (`id` TEXT NOT NULL, `reportId` TEXT NOT NULL, `panel` TEXT NOT NULL, " +
"`name` TEXT NOT NULL, `markerKey` TEXT NOT NULL, `valueNum` REAL, `valueText` TEXT, `unit` TEXT, " +
"`refLow` REAL, `refHigh` REAL, `refText` TEXT, `flag` TEXT NOT NULL, `position` INTEGER NOT NULL, " +
"PRIMARY KEY(`id`), FOREIGN KEY(`reportId`) REFERENCES `lab_reports`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )"
)
db.execSQL("CREATE INDEX IF NOT EXISTS `index_lab_results_reportId` ON `lab_results` (`reportId`)")
db.execSQL("CREATE INDEX IF NOT EXISTS `index_lab_results_markerKey` ON `lab_results` (`markerKey`)")
}
}

private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) {
db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`")
db.execSQL(
Expand Down Expand Up @@ -793,6 +818,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
MIGRATION_33_34,
MIGRATION_34_35,
MIGRATION_35_36,
MIGRATION_36_37,
)
// Downgrades only (sideloading an older APK). A blanket destructive
// fallback would silently wipe every measurement, sleep session, and
Expand Down
30 changes: 30 additions & 0 deletions app/src/main/java/com/pulseloop/data/dao/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1106,3 +1106,33 @@ interface AccuracyDao {
@Query("DELETE FROM accuracy_corrections WHERE deviceKey = :deviceKey AND metric = :metric")
suspend fun deleteCorrection(deviceKey: String, metric: String)
}

@Dao
interface LabDao {
@Query("SELECT * FROM lab_reports ORDER BY collectedDay DESC, createdAt DESC")
fun reportsFlow(): Flow<List<LabReportEntity>>

@Query("SELECT * FROM lab_reports ORDER BY collectedDay DESC, createdAt DESC")
suspend fun reports(): List<LabReportEntity>

@Query("SELECT * FROM lab_reports WHERE id = :id")
suspend fun report(id: String): LabReportEntity?

@Query("SELECT * FROM lab_results ORDER BY position ASC")
fun resultsFlow(): Flow<List<LabResultEntity>>

@Query("SELECT * FROM lab_results")
suspend fun results(): List<LabResultEntity>

@Query("SELECT * FROM lab_results WHERE markerKey = :key")
suspend fun resultsFor(key: String): List<LabResultEntity>

@Upsert
suspend fun upsertReport(report: LabReportEntity)

@Upsert
suspend fun upsertResults(results: List<LabResultEntity>)

@Query("DELETE FROM lab_reports WHERE id = :id")
suspend fun deleteReport(id: String)
}
61 changes: 61 additions & 0 deletions app/src/main/java/com/pulseloop/data/entity/LabEntities.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.pulseloop.data.entity

import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey

/**
* One lab report the user added as a PDF (docs: AGENTS.md, lab reports). [collectedDay] is the
* local start of the day the sample was collected, which is what a marker's chart is plotted by;
* [pdfFile] names the copy kept in `filesDir/lab_reports/`.
*/
@Entity(tableName = "lab_reports", indices = [Index("collectedDay")])
data class LabReportEntity(
@PrimaryKey val id: String,
val collectedDay: Long,
val lab: String? = null,
/** Kinds found in the report, comma-separated: blood, urine, hormones, stool, other. */
val kindsCsv: String = "",
/** The name the file had when the user picked it, for display. */
val fileName: String? = null,
val pdfFile: String? = null,
val pageCount: Int = 0,
val createdAt: Long = System.currentTimeMillis(),
)

/**
* One marker read from a report, as the user checked it. [markerKey] is the same for one marker
* across labs and languages ("ldl_cholesterol"), so a chart can follow it from report to report.
* The range is the lab's own, carried with each result because labs and methods differ.
*/
@Entity(
tableName = "lab_results",
foreignKeys = [ForeignKey(
entity = LabReportEntity::class,
parentColumns = ["id"],
childColumns = ["reportId"],
onDelete = ForeignKey.CASCADE,
)],
indices = [Index("reportId"), Index("markerKey")],
)
data class LabResultEntity(
@PrimaryKey val id: String,
val reportId: String,
/** The group the lab printed it under ("Lipids", "Blood count", "Urine"…). */
val panel: String,
/** The marker's name as printed on the report. */
val name: String,
val markerKey: String,
val valueNum: Double? = null,
/** For a result that isn't a number ("Negative", "Clear"), or the printed form of one. */
val valueText: String? = null,
val unit: String? = null,
val refLow: Double? = null,
val refHigh: Double? = null,
/** The reference as printed, when it isn't a plain low–high pair. */
val refText: String? = null,
/** HIGH, LOW, NORMAL, ABNORMAL (outside a non-numeric reference) or UNKNOWN. */
val flag: String = "UNKNOWN",
val position: Int = 0,
)
Loading
Loading