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
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Core behavior:
- If a tool fails, explain the limitation gracefully and offer the next best answer.
- 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.
- 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
120 changes: 120 additions & 0 deletions app/src/main/java/com/pulseloop/coach/tools/MealSuggestionTools.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package com.pulseloop.coach.tools

import com.pulseloop.service.MealSuggester
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.doubleOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

/**
* The next-meal idea, discussed in chat. `suggest_next_meal` returns the same suggestion the
* Nutrition screen shows (Brazilian everyday food and fruit, sized to what is left of the day);
* `save_food_preference` records an alternative the user and coach agreed on, so later
* suggestions use it whenever it still fits the budget.
*/
object MealSuggestionTools {

val all: List<CoachToolDef> get() = listOf(makeSuggest(), makeSavePreference(), makeListPreferences())

private val json = Json { encodeDefaults = true }
private val SLOTS = listOf("breakfast", "lunch", "snack", "dinner", "any")

private fun makeSuggest() = CoachToolDef(
name = "suggest_next_meal",
publicLabel = "Planning your next meal",
description = "The next-meal suggestion for right now: everyday Brazilian food and common fruit, sized to the " +
"calories left today and the protein gap, using the user's agreed food preferences. Returns the slot, the " +
"items with portion, kcal and protein, the total, the kcal it leaves, and which preferences it used.",
parameters = JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(emptyMap()),
"required" to JsonArray(emptyList()),
"additionalProperties" to JsonPrimitive(false),
)),
) { _, ctx ->
val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true)
val s = kotlinx.coroutines.runBlocking { MealSuggester.load(db) }
?: return@CoachToolDef ToolResult("""{"error":"no suggestion"}""", isError = true)
ToolResult(json.encodeToString(MealSuggester.Suggestion.serializer(), s))
}

private fun makeSavePreference() = CoachToolDef(
name = "save_food_preference",
publicLabel = "Remembering your preference",
description = "Record a food preference the user and you agreed on while discussing a meal suggestion, e.g. " +
"banana instead of vegetables at dinner. Only save it once you have checked it still fits their goal " +
"(calories left, protein) and the user agreed. slot: breakfast, lunch, snack, dinner or any. action: prefer " +
"or avoid. instead_of: the food or role it replaces (e.g. \"vegetables\"). For a food that isn't common " +
"Brazilian fare or fruit, give portion, kcal and protein_g for one portion. Saving the same preference " +
"again strengthens it.",
parameters = JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(mapOf(
"slot" to JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(SLOTS.map { JsonPrimitive(it) }))),
"item" to JsonObject(mapOf("type" to JsonPrimitive("string"))),
"action" to JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(listOf(JsonPrimitive("prefer"), JsonPrimitive("avoid"))))),
"instead_of" to JsonObject(mapOf("type" to JsonPrimitive("string"))),
"portion" to JsonObject(mapOf("type" to JsonPrimitive("string"))),
"kcal" to JsonObject(mapOf("type" to JsonPrimitive("number"))),
"protein_g" to JsonObject(mapOf("type" to JsonPrimitive("number"))),
"reason" to JsonObject(mapOf("type" to JsonPrimitive("string"))),
)),
"required" to JsonArray(listOf(JsonPrimitive("slot"), JsonPrimitive("item"), JsonPrimitive("action"))),
"additionalProperties" to JsonPrimitive(false),
)),
strict = false,
) { args, ctx ->
val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true)
val p = runCatching { Json.parseToJsonElement(args).jsonObject }.getOrNull()
?: return@CoachToolDef ToolResult("""{"error":"invalid arguments"}""", isError = true)
fun str(k: String) = p[k]?.jsonPrimitive?.contentOrNull?.trim()?.takeIf { it.isNotEmpty() }
val slot = str("slot")?.takeIf { it in SLOTS }
?: return@CoachToolDef ToolResult("""{"error":"slot must be one of $SLOTS"}""", isError = true)
val item = str("item")?.take(60) ?: return@CoachToolDef ToolResult("""{"error":"item is required"}""", isError = true)
val action = str("action")?.takeIf { it == "prefer" || it == "avoid" }
?: return@CoachToolDef ToolResult("""{"error":"action must be prefer or avoid"}""", isError = true)
val kcal = p["kcal"]?.jsonPrimitive?.doubleOrNull?.takeIf { it in 1.0..2000.0 }
val row = kotlinx.coroutines.runBlocking {
MealSuggester.agree(
db, slot, item, action, str("instead_of")?.take(60), str("portion")?.take(40),
kcal, p["protein_g"]?.jsonPrimitive?.doubleOrNull?.takeIf { it in 0.0..200.0 }, str("reason")?.take(140),
)
}
ToolResult(buildJsonObject {
put("ok", true)
put("slot", row.slot)
put("item", row.item)
put("action", row.action)
row.insteadOf?.let { put("instead_of", it) }
put("times_agreed", row.timesAgreed)
}.toString())
}

private fun makeListPreferences() = CoachToolDef(
name = "get_food_preferences",
publicLabel = "Checking your food preferences",
description = "List the food preferences already agreed with the user (slot, item, prefer/avoid, what it replaces, times agreed).",
parameters = JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(emptyMap()),
"required" to JsonArray(emptyList()),
"additionalProperties" to JsonPrimitive(false),
)),
) { _, ctx ->
val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true)
val rows = kotlinx.coroutines.runBlocking { db.foodPreferenceDao().all() }
ToolResult(JsonArray(rows.map { r ->
buildJsonObject {
put("slot", r.slot); put("item", r.item); put("action", r.action)
r.insteadOf?.let { put("instead_of", it) }
put("times_agreed", r.timesAgreed)
}
}).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
val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + MealSuggestionTools.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
9 changes: 9 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchive.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ data class PulseArchive(
val journalEntries: List<JournalEntryDTO> = emptyList(),
/** The goals set with the coach (v30). */
val coachGoals: List<CoachGoalDTO> = emptyList(),
/** Food preferences agreed with the coach (v31). */
val foodPreferences: List<FoodPreferenceDTO> = emptyList(),
)

@Serializable data class FoodPreferenceDTO(
val id: String, val slot: String, val item: String, val action: String,
val insteadOf: String? = null, val portion: String? = null,
val kcal: Double? = null, val proteinG: Double? = null, val reason: String? = null,
val timesAgreed: Int = 1, val createdAt: Long, val updatedAt: Long,
)

@Serializable data class CoachGoalDTO(
Expand Down
15 changes: 15 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,14 @@ object DataArchiveService {
timestamp = c.long("timestamp"), deletedAt = c.long("deletedAt"),
)
},
foodPreferences = collect("food_preferences") { c ->
FoodPreferenceDTO(
id = c.str("id"), slot = c.str("slot"), item = c.str("item"), action = c.str("action"),
insteadOf = c.strOrNull("insteadOf"), portion = c.strOrNull("portion"),
kcal = c.dblOrNull("kcal"), proteinG = c.dblOrNull("proteinG"), reason = c.strOrNull("reason"),
timesAgreed = c.intOrNull("timesAgreed") ?: 1, createdAt = c.long("createdAt"), updatedAt = c.long("updatedAt"),
)
},
coachGoals = collect("coach_goals") { c ->
CoachGoalDTO(
id = c.str("id"), kind = c.str("kind"), description = c.str("description"),
Expand Down Expand Up @@ -404,6 +412,13 @@ object DataArchiveService {
}
)
}
for (f in archive.foodPreferences) {
db.foodPreferenceDao().upsert(FoodPreferenceEntity(
id = f.id, slot = f.slot, item = f.item, action = f.action, insteadOf = f.insteadOf,
portion = f.portion, kcal = f.kcal, proteinG = f.proteinG, reason = f.reason,
timesAgreed = f.timesAgreed, createdAt = f.createdAt, updatedAt = f.updatedAt,
))
}
for (g in archive.coachGoals) {
db.coachGoalDao().upsert(CoachGoalEntity(
id = g.id, kind = g.kind, description = g.description,
Expand Down
18 changes: 17 additions & 1 deletion app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ import com.pulseloop.data.entity.*
JournalEntryEntity::class,
BodyMeasurementEntity::class,
CoachGoalEntity::class,
FoodPreferenceEntity::class,
],
version = 30,
version = 31,
exportSchema = false,
)
abstract class PulseLoopDatabase : RoomDatabase() {
Expand All @@ -73,6 +74,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
abstract fun userGoalDao(): UserGoalDao
abstract fun bodyMeasurementDao(): BodyMeasurementDao
abstract fun coachGoalDao(): CoachGoalDao
abstract fun foodPreferenceDao(): FoodPreferenceDao
abstract fun coachSummaryDao(): CoachSummaryDao
abstract fun wearableLogDao(): WearableLogDao
abstract fun rawPacketDao(): RawPacketDao
Expand Down Expand Up @@ -122,6 +124,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
"journal_entries",
"body_measurements",
"coach_goals",
"food_preferences",
)

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

/** v30 → v31: food preferences agreed with the coach (next-meal suggestions). */
private val MIGRATION_30_31 = object : Migration(30, 31) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `food_preferences` (`id` TEXT NOT NULL, `slot` TEXT NOT NULL, " +
"`item` TEXT NOT NULL, `action` TEXT NOT NULL, `insteadOf` TEXT, `portion` TEXT, " +
"`kcal` REAL, `proteinG` REAL, `reason` TEXT, `timesAgreed` INTEGER NOT NULL, " +
"`createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
}
}

private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) {
db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`")
db.execSQL(
Expand Down Expand Up @@ -661,6 +676,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
MIGRATION_27_28,
MIGRATION_28_29,
MIGRATION_29_30,
MIGRATION_30_31,
)
// Downgrades only (sideloading an older APK). A blanket destructive
// fallback would silently wipe every measurement, sleep session, and
Expand Down
15 changes: 15 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 @@ -919,3 +919,18 @@ interface CoachGoalDao {
suspend fun upsert(goal: CoachGoalEntity)

}

@Dao
interface FoodPreferenceDao {
@Query("SELECT * FROM food_preferences ORDER BY timesAgreed DESC, updatedAt DESC")
suspend fun all(): List<FoodPreferenceEntity>

@Query("SELECT * FROM food_preferences WHERE id = :id LIMIT 1")
suspend fun byId(id: String): FoodPreferenceEntity?

@Upsert
suspend fun upsert(pref: FoodPreferenceEntity)

@Query("DELETE FROM food_preferences WHERE id = :id")
suspend fun delete(id: String)
}
31 changes: 31 additions & 0 deletions app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,34 @@ data class CoachGoalEntity(
val createdAt: Long = System.currentTimeMillis(),
val updatedAt: Long = System.currentTimeMillis(),
)

/**
* v31: a food preference the user and the coach agreed on ("banana instead of vegetables at
* night"). Meal suggestions use it whenever it still fits the day's budget. [timesAgreed] grows
* each time the same preference is agreed again, so a repeated choice weighs more.
*/
@Entity(tableName = "food_preferences")
data class FoodPreferenceEntity(
@PrimaryKey val id: String,
/** breakfast, lunch, snack, dinner, or any. */
val slot: String,
/** The food, in the user's words or a catalog name. */
val item: String,
/** prefer or avoid. */
val action: String,
/** What it replaces in a suggestion (a food or a role like "vegetables"), if anything. */
val insteadOf: String? = null,
/** Portion and its nutrition when the food isn't in the catalog. */
val portion: String? = null,
val kcal: Double? = null,
val proteinG: Double? = null,
val reason: String? = null,
val timesAgreed: Int = 1,
val createdAt: Long = System.currentTimeMillis(),
val updatedAt: Long = System.currentTimeMillis(),
) {
companion object {
/** One row per slot + item + action, so agreeing again counts up instead of duplicating. */
fun idFor(slot: String, item: String, action: String) = "$slot:${item.trim().lowercase()}:$action"
}
}
Loading
Loading