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
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 @@ -26,6 +26,7 @@ class PulseLoopApplication : Application() {
override fun onCreate() {
super.onCreate()
CrashLogger.install(this)
com.pulseloop.service.DrinkPrefs.init(this)
// Application-scoped so capture runs whether or not the Debug screen is open.
DiagnosticsSubscriber(PulseLoopDatabase.getInstance(this)).start(appScope)
// One-time cleanup of activity totals corrupted by the old bucket handling; runs off the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ object CoachContextBuilder {
dataQualityWarnings = warnings,
environment = environment,
primaryGoal = runCatching { com.pulseloop.service.GoalPlan.load(db, now) }.getOrNull(),
drinks = com.pulseloop.service.DrinksContext.build(db, now),
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Core behavior:
- Goals: when the context packet's `primaryGoal` is null, ask the user — once per conversation, early, and never instead of answering what they asked — what they want to achieve and by when. Offer the common ones briefly: lose weight, get stronger / build muscle, lose fat and keep muscle, sleep better, get fitter, move more, reduce stress, eat better. Map what they say to the closest kind ("get stronger" → build_muscle, "run a 5k" → get_fitter) and keep their own words in the description. When they answer, call set_goal, then tell them in one line what it changed in their Settings (its `settings_goals`), and that they can edit those numbers. If a weight goal needs more than 1% of body weight a week, say so plainly, propose a realistic date or target, and only save once they agree.
- 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.
- 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 @@ -69,6 +70,8 @@ data class CoachContextPacket(
val environment: EnvironmentContext? = null,
/** The goal the user set with the coach, with progress; null when none is set yet. */
val primaryGoal: com.pulseloop.service.GoalPlan.Plan? = null,
/** Drinks, when the user tracks them (docs/drinks-plan.md); null otherwise. */
val drinks: com.pulseloop.service.DrinksContext? = null,
) {
@kotlinx.serialization.Serializable
data class ProfileContext(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ object PendingActionExecutor {
PendingActionKind.DELETE_MEAL_ENTRY -> {
val name = entry.name
db.mealEntryDao().deleteById(entry.id)
com.pulseloop.service.DrinksRepository.onMealDeleted(db, entry.id)
"Deleted \"$name\"."
}
PendingActionKind.UPDATE_MEAL_ENTRY -> {
Expand Down
137 changes: 137 additions & 0 deletions app/src/main/java/com/pulseloop/coach/tools/DrinkTools.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package com.pulseloop.coach.tools

import com.pulseloop.service.DrinkInsights
import com.pulseloop.service.DrinkPrefs
import com.pulseloop.service.DrinkType
import com.pulseloop.service.DrinksRepository
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

/**
* Drinks in chat (docs/drinks-plan.md): read the week, log a drink the user says they had, and set
* tonight's plan once they agree to a number. All three refuse while Drinks is off, so the coach
* never starts tracking alcohol for someone who didn't ask.
*/
object DrinkTools {

val all: List<CoachToolDef> get() = listOf(makeSummary(), makeLog(), makePlan())

private val TYPES = DrinkType.entries.map { it.key }
private const val OFF = """{"error":"Drinks tracking is off. The user can turn it on from Today's tiles, Settings → Drinks, or the Journal."}"""

private fun noArgs() = JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(emptyMap()),
"required" to JsonArray(emptyList()),
"additionalProperties" to JsonPrimitive(false),
))

private fun makeSummary() = CoachToolDef(
name = "get_drinks",
publicLabel = "Checking your drinks",
description = "The user's drinks: this week in standard drinks against their weekly limit, dry days against their " +
"target, the current and best dry streak, tonight's plan, the last 8 weeks, and what drinking did to their " +
"nights (last night, after 1–2 and after 3+ drinks, compared with their dry nights).",
parameters = noArgs(),
) { _, ctx ->
val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true)
if (!DrinkPrefs.enabled) return@CoachToolDef ToolResult(OFF, isError = true)
val s = kotlinx.coroutines.runBlocking { DrinksRepository.load(db) }
fun impact(i: DrinkInsights.Impact?) = i?.let {
buildJsonObject {
put("nights", it.nights)
it.hrvPct?.let { v -> put("hrv_pct_vs_dry", v) }
it.restingHr?.let { v -> put("resting_hr_bpm_vs_dry", v) }
it.asleepMinutes?.let { v -> put("asleep_min_vs_dry", v) }
}
}
ToolResult(buildJsonObject {
put("standard_drink_grams", s.gramsPerStandard)
put("week_standard_drinks", DrinkInsights.fmt(s.week.standardDrinks))
put("weekly_limit", s.weeklyLimit)
put("dry_days_this_week", s.week.dryDays)
put("dry_days_target", s.dryDaysTarget)
put("heavy_days_this_week", s.week.heavyDays)
put("today_standard_drinks", DrinkInsights.fmt(s.todayStandard))
s.planToday?.let { put("tonight_plan", it) }
put("dry_streak_current", s.streaks.current)
put("dry_streak_best", s.streaks.best)
put("last_8_weeks", JsonArray(s.weeks.map { JsonPrimitive(DrinkInsights.fmt(it.second)) }))
s.morningAfter?.let { put("last_night", DrinksRepository.morningAfterLine(it)) }
impact(s.dose.light)?.let { put("after_1_to_2_drinks", it) }
impact(s.dose.heavier)?.let { put("after_3_plus_drinks", it) }
put("dry_nights_compared", s.dose.dryNights)
s.recoveryNights?.let { put("nights_for_hrv_to_recover", "%.1f".format(it)) }
}.toString())
}

private fun makeLog() = CoachToolDef(
name = "log_drink",
publicLabel = "Logging your drink",
description = "Log drinks the user says they had. type: beer (350 ml can), beer_600, draft (chopp), wine (glass), " +
"spirit (shot), caipirinha, cocktail, or other. count: how many (1–12). hours_ago: when, 0 for now.",
parameters = JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(mapOf(
"type" to JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(TYPES.map { JsonPrimitive(it) }))),
"count" to JsonObject(mapOf("type" to JsonPrimitive("integer"))),
"hours_ago" to JsonObject(mapOf("type" to JsonPrimitive("integer"))),
)),
"required" to JsonArray(listOf(JsonPrimitive("type"))),
"additionalProperties" to JsonPrimitive(false),
)),
strict = false,
) { args, ctx ->
val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true)
if (!DrinkPrefs.enabled) return@CoachToolDef ToolResult(OFF, isError = true)
val p = runCatching { Json.parseToJsonElement(args).jsonObject }.getOrNull()
?: return@CoachToolDef ToolResult("""{"error":"invalid arguments"}""", isError = true)
val key = p["type"]?.jsonPrimitive?.contentOrNull?.takeIf { it in TYPES }
?: return@CoachToolDef ToolResult("""{"error":"type must be one of $TYPES"}""", isError = true)
val count = (p["count"]?.jsonPrimitive?.intOrNull ?: 1).coerceIn(1, 12)
val hoursAgo = (p["hours_ago"]?.jsonPrimitive?.intOrNull ?: 0).coerceIn(0, 36)
val type = DrinkType.of(key)
kotlinx.coroutines.runBlocking {
DrinksRepository.log(db, type, count, System.currentTimeMillis() - hoursAgo * 3_600_000L)
}
val s = kotlinx.coroutines.runBlocking { DrinksRepository.load(db) }
ToolResult(buildJsonObject {
put("ok", true)
put("logged", "$count × ${type.label}")
put("today_standard_drinks", DrinkInsights.fmt(s.todayStandard))
put("week_standard_drinks", DrinkInsights.fmt(s.week.standardDrinks))
put("weekly_limit", s.weeklyLimit)
s.planToday?.let { put("tonight_plan", it) }
}.toString())
}

private fun makePlan() = CoachToolDef(
name = "set_drink_plan",
publicLabel = "Setting tonight's plan",
description = "Save how many drinks the user plans to have tonight, once they have agreed to the number (0 for a " +
"dry night). The Drinks screen then tracks tonight against it.",
parameters = JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(mapOf("drinks" to JsonObject(mapOf("type" to JsonPrimitive("integer"))))),
"required" to JsonArray(listOf(JsonPrimitive("drinks"))),
"additionalProperties" to JsonPrimitive(false),
)),
) { args, ctx ->
if (ctx.db == null) return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true)
if (!DrinkPrefs.enabled) return@CoachToolDef ToolResult(OFF, isError = true)
val n = runCatching { Json.parseToJsonElement(args).jsonObject["drinks"]?.jsonPrimitive?.intOrNull }.getOrNull()
?.takeIf { it in 0..12 }
?: return@CoachToolDef ToolResult("""{"error":"drinks must be 0–12"}""", isError = true)
val tonight = com.pulseloop.service.MealJournal.eveningOf(System.currentTimeMillis())
DrinkPrefs.setPlan(tonight, n)
ToolResult(buildJsonObject { put("ok", true); put("tonight_plan", n) }.toString())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ToolRegistry(private val flags: CoachFeatureFlags) {
// Nutrition read tools are grounding (always available, like the other read tools);
// the write tools are gated on flags.writeToolsEnabled, mirroring iOS's
// enableWriteTools split in NutritionTools.swift (iOS PR #96).
val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + MealSuggestionTools.all
val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + MealSuggestionTools.all + DrinkTools.all
val writable = if (flags.writeToolsEnabled) MemoryTools.all + ActionTools.writeTools + NutritionTools.writeTools else emptyList()
val live = if (flags.liveMeasurementsEnabled) ActionTools.measurementTools else emptyList()
tools = (all + writable + live).associateBy { it.name }
Expand Down
8 changes: 8 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchive.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ data class PulseArchive(
val coachGoals: List<CoachGoalDTO> = emptyList(),
/** Food preferences agreed with the coach (v31). */
val foodPreferences: List<FoodPreferenceDTO> = emptyList(),
/** Drinks (v32). */
val drinks: List<DrinkEntryDTO> = emptyList(),
)

@Serializable data class FoodPreferenceDTO(
Expand All @@ -56,6 +58,12 @@ data class PulseArchive(
val timesAgreed: Int = 1, val createdAt: Long, val updatedAt: Long,
)

@Serializable data class DrinkEntryDTO(
val id: String, val timestamp: Long, val day: Long, val type: String,
val volumeMl: Double, val abvPct: Double, val grams: Double, val kcal: Double,
val price: Double? = null, val mealId: String? = null, val note: String? = null, val createdAt: Long,
)

@Serializable data class CoachGoalDTO(
val id: String, val kind: String, val description: String,
val startWeightKg: Double? = null, val targetWeightKg: Double? = null,
Expand Down
16 changes: 16 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,15 @@ object DataArchiveService {
timesAgreed = c.intOrNull("timesAgreed") ?: 1, createdAt = c.long("createdAt"), updatedAt = c.long("updatedAt"),
)
},
drinks = collect("drink_entries") { c ->
DrinkEntryDTO(
id = c.str("id"), timestamp = c.long("timestamp"), day = c.long("day"), type = c.str("type"),
volumeMl = c.dblOrNull("volumeMl") ?: 0.0, abvPct = c.dblOrNull("abvPct") ?: 0.0,
grams = c.dblOrNull("grams") ?: 0.0, kcal = c.dblOrNull("kcal") ?: 0.0,
price = c.dblOrNull("price"), mealId = c.strOrNull("mealId"), note = c.strOrNull("note"),
createdAt = c.long("createdAt"),
)
},
coachGoals = collect("coach_goals") { c ->
CoachGoalDTO(
id = c.str("id"), kind = c.str("kind"), description = c.str("description"),
Expand Down Expand Up @@ -419,6 +428,13 @@ object DataArchiveService {
timesAgreed = f.timesAgreed, createdAt = f.createdAt, updatedAt = f.updatedAt,
))
}
for (d in archive.drinks) {
db.drinkDao().upsert(DrinkEntryEntity(
id = d.id, timestamp = d.timestamp, day = d.day, type = d.type, volumeMl = d.volumeMl,
abvPct = d.abvPct, grams = d.grams, kcal = d.kcal, price = d.price, mealId = d.mealId,
note = d.note, createdAt = d.createdAt,
))
}
for (g in archive.coachGoals) {
db.coachGoalDao().upsert(CoachGoalEntity(
id = g.id, kind = g.kind, description = g.description,
Expand Down
20 changes: 19 additions & 1 deletion app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ import com.pulseloop.data.entity.*
BodyMeasurementEntity::class,
CoachGoalEntity::class,
FoodPreferenceEntity::class,
DrinkEntryEntity::class,
],
version = 31,
version = 32,
exportSchema = false,
)
abstract class PulseLoopDatabase : RoomDatabase() {
Expand All @@ -75,6 +76,8 @@ abstract class PulseLoopDatabase : RoomDatabase() {
abstract fun bodyMeasurementDao(): BodyMeasurementDao
abstract fun coachGoalDao(): CoachGoalDao
abstract fun foodPreferenceDao(): FoodPreferenceDao
/** Drinks (docs/drinks-plan.md, v32). */
abstract fun drinkDao(): DrinkDao
abstract fun coachSummaryDao(): CoachSummaryDao
abstract fun wearableLogDao(): WearableLogDao
abstract fun rawPacketDao(): RawPacketDao
Expand Down Expand Up @@ -125,6 +128,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
"body_measurements",
"coach_goals",
"food_preferences",
"drink_entries",
)

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

/** v31 → v32: drinks (docs/drinks-plan.md). */
private val MIGRATION_31_32 = object : Migration(31, 32) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `drink_entries` (`id` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, " +
"`day` INTEGER NOT NULL, `type` TEXT NOT NULL, `volumeMl` REAL NOT NULL, `abvPct` REAL NOT NULL, " +
"`grams` REAL NOT NULL, `kcal` REAL NOT NULL, `price` REAL, `mealId` TEXT, `note` TEXT, " +
"`createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
db.execSQL("CREATE INDEX IF NOT EXISTS `index_drink_entries_day` ON `drink_entries` (`day`)")
}
}

private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) {
db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`")
db.execSQL(
Expand Down Expand Up @@ -677,6 +694,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
MIGRATION_28_29,
MIGRATION_29_30,
MIGRATION_30_31,
MIGRATION_31_32,
)
// Downgrades only (sideloading an older APK). A blanket destructive
// fallback would silently wipe every measurement, sleep session, and
Expand Down
31 changes: 31 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 @@ -934,3 +934,34 @@ interface FoodPreferenceDao {
@Query("DELETE FROM food_preferences WHERE id = :id")
suspend fun delete(id: String)
}

@Dao
interface DrinkDao {
@Query("SELECT * FROM drink_entries ORDER BY timestamp DESC")
suspend fun all(): List<DrinkEntryEntity>

@Query("SELECT * FROM drink_entries ORDER BY timestamp DESC")
fun allFlow(): Flow<List<DrinkEntryEntity>>

/** Drinks whose evening starts in [from, to). */
@Query("SELECT * FROM drink_entries WHERE day >= :from AND day < :to ORDER BY timestamp ASC")
suspend fun between(from: Long, to: Long): List<DrinkEntryEntity>

@Query("SELECT * FROM drink_entries WHERE mealId = :mealId")
suspend fun byMeal(mealId: String): List<DrinkEntryEntity>

@Query("SELECT * FROM drink_entries ORDER BY timestamp DESC LIMIT 1")
suspend fun latest(): DrinkEntryEntity?

@Upsert
suspend fun upsert(entry: DrinkEntryEntity)

@Query("DELETE FROM drink_entries WHERE id = :id")
suspend fun delete(id: String)

@Query("DELETE FROM drink_entries WHERE mealId = :mealId")
suspend fun deleteByMeal(mealId: String)

@Query("DELETE FROM drink_entries")
suspend fun clear()
}
Loading
Loading