Modern Apps git

← Modern-Apps.git

weather: add get_weather_forecast assistant tool

Commit
6bfe0f68e6d56ab55536bac50861f94eb5e4225e
Author
Vayun Mathur <[email protected]>
When
2026-12-02 04:38 UTC (4 days ago)
Parents
1cc7950
Existing OpenAssistant weather tools returned only current
conditions, so the assistant could not answer multi-day or
later-today questions without flooding context with raw series.
This adds the missing forecast tool from the intents audit.

Library: new WeatherForecastData.kt carries WeatherForecastQuery
(location or coordinate pair, days/hours) plus capped
ForecastDayData/ForecastHourData/WeatherForecastData results with
defaults on every field for wire compatibility.

Weather: GetForecastIntent is the validated contract. It trims and
truncates the location, clamps days to 1-5 (default 3) and hours to
0-12 (default 6), validates coordinates as an in-range pair,
resolves named places against saved locations first and then the
on-device catalogue, and distills the bundle from today/now into
summary entries only - the raw hourly/daily arrays never cross the
wire. Registered in the manifest beside GetWeather/GetWeatherByName.

OpenAssistant: get_weather_forecast (READ) is catalogued in
AssistantToolSpecs and handled in AssistantTools via
AssistantCoreToolIntents.getWeatherForecast; summarizeWeatherForecast
renders at most 5 daily + 8 hourly capped lines. Tool count goes
54 to 55. Adding the declaration pushed the pinned prompt header
over its 24,500-char budget, so several verbose existing tool
descriptions were shortened without changing their meaning; the
header now measures 24,463 chars in PromptBudgetTest arithmetic.

Tests pin the caps on both sides: validated-query clamping,
coordinate validation, saved-place matching, today/now mapping
windows and precip clamping in weather; 5+8 line caps, field
truncation, error and empty cases for the summarizer in
openassistant. weather/library AGENTS.md updated for the new files.

Verified in this worktree:
./gradlew :weather:lint :weather:lintVitalRelease
  :weather:testDevUnitTest :openassistant:lint
  :openassistant:testDevUnitTest :library:lint - all green
(lintVitalRelease passes standalone; in the combined invocation
Gradle reports it SKIPPED next to :weather:lint).

Diff

library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex 3bb1307016..d97746ac74 100644--- a/library/AGENTS.md+++ b/library/AGENTS.md@@ -33,6 +33,7 @@ - com/vayunmathur/library/intents/health/HealthMetricData.kt — aggregate-only health summary query/result (no record-level fields) - com/vayunmathur/library/intents/calculator/CalculatorData.kt - com/vayunmathur/library/intents/astronomy/AstronomyData.kt — `TonightQuery`/`AstronomyTonightData` (capped summary, `MAX_TONIGHT_SUMMARY_CHARS`)+- com/vayunmathur/library/intents/weather/WeatherForecastData.kt — capped forecast query/result (`WeatherForecastQuery` days ≤5, hours ≤12; summary entries only) ### util/ — navigation, intents, messenger, storage, games glue - com/vayunmathur/library/util/Navigation.kt — `NavKey` + `MainNavigation` + `rememberNavBackStack` - com/vayunmathur/library/util/NavigationBottomBar.kt
library/src/main/java/com/vayunmathur/library/intents/weather/WeatherForecastData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/weather/WeatherForecastData.kt b/library/src/main/java/com/vayunmathur/library/intents/weather/WeatherForecastData.ktnew file mode 100644index 0000000000..a74e6cf4cc--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/weather/WeatherForecastData.kt@@ -0,0 +1,84 @@+package com.vayunmathur.library.intents.weather++import kotlinx.serialization.Serializable++/**+ * Cross-app forecast payloads for the Weather app's `GetForecastIntent`,+ * launched by OpenAssistant's `get_weather_forecast` tool. Unlike+ * [WeatherData] (current conditions only), these carry a capped multi-day+ * outlook plus the next few hours — summary values only, never the raw+ * hourly/daily series the bundle holds.+ *+ * Caps are contractual and enforced provider-side in the weather app's+ * `intents/` backend (not just promised in the tool description):+ * [WeatherForecastQuery.days] is clamped to 1..[MAX_FORECAST_DAYS],+ * [WeatherForecastQuery.hours] to 0..[MAX_FORECAST_HOURS], and every+ * condition string is truncated to [MAX_FORECAST_CONDITION_CHARS].+ * Temperatures are Celsius; callers render unit conversion for the user.+ * Every field has a default so older/newer callers can omit fields+ * without breaking decode (library DTO-compat rule).+ */++/** Maximum forecast days a query may return, however large the ask. */+const val MAX_FORECAST_DAYS = 5++/** Forecast days returned when a query does not say (or says 0). */+const val DEFAULT_FORECAST_DAYS = 3++/** Maximum hourly entries a query may return, however large the ask. */+const val MAX_FORECAST_HOURS = 12++/** Hourly entries returned when a query does not say. */+const val DEFAULT_FORECAST_HOURS = 6++/** Maximum characters in a forecast condition label. */+const val MAX_FORECAST_CONDITION_CHARS = 60++/** Maximum characters in a forecast query's location string. */+const val MAX_FORECAST_LOCATION_CHARS = 120++/**+ * Forecast ask: a named place ([location] — a saved Weather place or a+ * catalogue city) or an explicit ([latitude], [longitude]) pair.+ * [location] wins over coordinates when both are supplied.+ */+@Serializable+data class WeatherForecastQuery(+    val location: String = "",+    val latitude: Double? = null,+    val longitude: Double? = null,+    val days: Int = DEFAULT_FORECAST_DAYS,+    val hours: Int = DEFAULT_FORECAST_HOURS,+)++/** One day of the outlook: local ISO date, high/low and condition. */+@Serializable+data class ForecastDayData(+    val date: String = "",+    val highC: Double = 0.0,+    val lowC: Double = 0.0,+    val condition: String = "",+    val precipChancePercent: Int = 0,+)++/** One of the next few hours: local ISO time, temperature and condition. */+@Serializable+data class ForecastHourData(+    val time: String = "",+    val temperatureC: Double = 0.0,+    val condition: String = "",+    val precipChancePercent: Int = 0,+)++/**+ * Capped forecast for one place. [error] is non-null only when the+ * lookup failed (no such place, invalid coordinates, no network); the+ * lists are empty in that case and callers should check [error] first.+ */+@Serializable+data class WeatherForecastData(+    val locationName: String? = null,+    val days: List<ForecastDayData> = emptyList(),+    val hours: List<ForecastHourData> = emptyList(),+    val error: String? = null,+)
openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.ktindex eccca3e5d3..94dff9f778 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -59,6 +59,7 @@ get_todos|-|Get open tasks (max 50). Due times are epoch ms; id usable with comp create_todo|C|Create a task in Todo (requires confirmation, EXPLICIT request only). The title may include 'tomorrow 6pm' or '#tag', understood when no due time is given.|title^S^1^~due^N^0^optional due time as epoch milliseconds~notes^S^0^~priority^N^0^optional priority, 1 (highest) to 4 complete_todo|C|Mark a task done (requires confirmation). Should only be used with EXPLICIT request by user.|id^S^0^task id from get_todos~title^S^0^exact task title, used when no id is given get_contacts|-|Get contacts (max 50; prefer search_contacts)|+ create_contact|C|Create a new contact (requires confirmation)|name^S^1^~phone_number^S^1^ get_calendar_events|-|Get calendar events (max 50; times are epoch ms)| create_calendar_event|C|Create a new calendar event (requires confirmation). Start and end times must be epoch milliseconds.|title^S^1^~start^N^1^start time as epoch milliseconds~end^N^1^end time as epoch milliseconds~location^S^0^@@ -77,18 +78,18 @@ set_alarm|C|Set Clock alarm at hour/minute 24h (confirmation).|hour^N^1^hour 0-2 set_timer|C|Start Clock countdown timer in seconds (confirmation).|seconds^N^1^timer length in seconds~label^S^0^label for the timer set_conversation_title|-|Set current conversation title. Mandatory first response.|new_title^S^1^ get_weather|-|Current weather at lat/lng.|latitude^N^1^~longitude^N^1^-get_weather_by_name|-|Current weather for a named place.|location^S^1^place name+get_weather_by_name|-|Current weather for a named place.|location^S^1^place screentime_get_usage|-|Today's screen time: total + top 5 apps.|-render_ui|-|Render rich UI card (A2UI) with reply; prefer over ```a2ui fence. components_json {"components":[...]} or array; data_json optional.|components_json^S^1^A2UI components JSON~data_json^S^0^data JSON-get_directions|-|Directions between coordinates: distance, duration.|from_lat^N^1^origin lat~from_lng^N^1^origin lng~to_lat^N^1^dest lat~to_lng^N^1^dest lng~mode^S^0^drive (default), transit, walk, or bicycle-maps_search_places|-|Search Maps places; returns lat/lng.|query^S^1^name or category~near_lat^N^0^near lat~near_lng^N^0^near lng~category^S^0^e.g. Cafe~limit^N^0^1-10 (def 5)+render_ui|-|Render UI card (A2UI) with reply; prefer over ```a2ui fence. components_json {"components":[...]}; data_json opt.|components_json^S^1^A2UI components JSON~data_json^S^0^data JSON+get_directions|-|Directions: distance, duration.|from_lat^N^1^origin lat~from_lng^N^1^origin lng~to_lat^N^1^dest lat~to_lng^N^1^dest lng~mode^S^0^drive/transit/walk/bicycle+maps_search_places|-|Maps places; returns lat/lng.|query^S^1^name/category~near_lat^N^0^near lat~near_lng^N^0^near lng~category^S^0^e.g. Cafe~limit^N^0^1-10 (def 5) maps_get_saved_places|-|Saved Maps places (name + coordinates).|query^S^0^filter~limit^N^0^max 1-10 (def 10)-get_ride_estimate|-|Taxi fare + pickup ETA.|pickup_lat^N^1^pickup lat~pickup_lng^N^1^pickup lng~dest_lat^N^1^dest lat~dest_lng^N^1^dest lng~pickup_label^S^0^pickup label~dest_label^S^0^dest label+get_ride_estimate|-|Taxi fare + ETA.|pickup_lat^N^1^pickup lat~pickup_lng^N^1^pickup lng~dest_lat^N^1^dest lat~dest_lng^N^1^dest lng~pickup_label^S^0^pickup label~dest_label^S^0^dest label food_order_lookup|-|Restaurant orderable nearby? (FoodDelivery).|name^S^1^name~lat^N^1^lat~lng^N^1^lng~address^S^0^address calculator_evaluate|-|Evaluate math expression via Calculator (functions, pi/e, units 5km+2mi).|expression^S^1^expression (200 chars) calculator_convert_unit|-|Convert a value between units via Calculator (incl. currency like USD).|value^N^1^value~from_unit^S^1^from: km, ft, degC, USD~to_unit^S^1^to: mi, m, degF, EUR search_contacts|-|Search contacts by name/phone substring (max 10).|query^S^1^name/phone substring-web_search|-|Web search for current facts. Numbered results; web_read_result reads them.|query^S^1^search query~count^N^0^count 1-10 (def 5)~kind^S^0^text (default) or news+web_search|-|Web search for current facts. Numbered results; web_read_result reads them.|query^S^1^search query~count^N^0^count 1-10 (def 5)~kind^S^0^text (def) or news web_read|-|Read a web page by URL and return its extracted text.|url^S^1^page URL to read web_read_result|-|Read a result from the last web_search by its 1-based index.|index^N^1^1-based index into the last web_search results~offset^N^0^optional character offset for long pages find_conversations|-|Find Communicate conversations by name, number or snippet. Returns thread_key values for get_conversation_messages.|query^S^0^name, number or text to search (blank lists recent)~limit^N^0^optional max conversations 1-50 (default 5)@@ -97,17 +98,18 @@ draft_message|-|Show a message composer card (recipient, line, draft body). Send send_message_v2|C|Send via Communicate (requires confirmation, EXPLICIT request only). GoogleVoice cannot send here; use draft_message instead.|address^S^1^recipient phone number or address~line^S^1^Sim, Rcs, WhatsApp, Signal, or GoogleVoice~body^S^1^message text~thread_remote_id^S^0^optional existing thread id to reply into find_restaurants|-|Find restaurants near a location via the FoodDelivery app, optionally filtered by name or tag.|query^S^0^optional name or tag filter~lat^N^1^latitude~lng^N^1^longitude~limit^N^0^optional max results (default 5) get_restaurant_menu|-|Get the menu of a restaurant (merchant_id from find_restaurants). Items carry ids, prices in cents, availability and modifier groups.|merchant_id^N^1^merchant id from find_restaurants+ food_get_cart|-|Get the current FoodDelivery cart (items and total)|-food_set_cart|L|Replace FoodDelivery cart with items_json [{itemId,qty,modifierIds}]. No order placed.|merchant_id^N^1^merchant id~items_json^S^1^[{itemId,qty,modifierIds}]-food_prepare_order|-|Price cart (pickup/delivery); no order created.|merchant_id^N^1^merchant id~is_pickup^N^0^1 pickup, 0 delivery (default)~address_id^S^0^address id~tip_cents^N^0^tip (cents)~promo^S^0^promo-place_food_order|H|Show the current cart's order summary. The user places and pays in FoodDelivery itself; this never creates an order or charges a card.|merchant_id^N^1^merchant id+food_set_cart|L|Replace cart with items_json [{itemId,qty,modifierIds}].|merchant_id^N^1^merchant~items_json^S^1^[{itemId,qty,modifierIds}]+food_prepare_order|-|Price cart; no order created.|merchant_id^N^1^merchant~is_pickup^N^0^1=pickup 0=delivery~address_id^S^0^address id~tip_cents^N^0^tip (cents)~promo^S^0^promo+place_food_order|H|Show the current cart's order summary. The user places and pays in FoodDelivery itself; this never creates an order or charges a card.|merchant_id^N^1^merchant get_food_orders|-|Get the user's past FoodDelivery orders| search_products|-|Search the Shop catalog. Each result is one purchasable variant with its variant_id, store and exact price.|query^S^1^search text~limit^N^0^max (def 5)-get_product_detail|-|One product's variants (prices, availability). Confirm variant before adding to cart.|shop_domain^S^1^domain~product_id^S^1^product id~variant_id^S^0^variant to price+get_product_detail|-|Product variants. Confirm before cart.|shop_domain^S^1^domain~product_id^S^1^product~variant_id^S^0^variant shop_get_cart|-|Get the current Shop cart, grouped by store|-shop_add_to_cart|L|Add exact variant to Shop cart (re-verified; no checkout).|shop_domain^S^1^domain~variant_id^S^1^exact variant id~quantity^N^0^qty 1-99 (default 1)+shop_add_to_cart|L|Add exact variant to Shop cart (re-verified; no checkout).|shop_domain^S^1^domain~variant_id^S^1^exact variant id~quantity^N^0^qty 1-99 (def 1) shop_remove_from_cart|L|Remove a variant from the Shop cart; the cart is shown back to the user.|variant_id^S^1^variant id to remove-start_shop_checkout|H|Per-store cart summary. User checks out in Shop; never charges.|shop_domain^S^1^domain to check out+start_shop_checkout|H|Cart summary; user checks out in Shop.|shop_domain^S^1^domain to check out get_shop_orders|-|Get the user's Shop order summaries| get_memories|-|Get memories (last 100)| education_get_progress|-|Education progress by course/subject, streak, deadlines (aggregates).|@@ -116,7 +118,9 @@ news_top_stories|-|Top News stories by source count, then newest|category^S^0^WO news_get_story|-|Get a News story by story_id|story_id^S^1^from news search/top news_read_article|-|Read a News article (3000 chars/page)|url^S^1^from a news result~offset^N^0^char offset health_get_metric_summary|-|Health summary aggregates only: latest/avg/min/max/totals.|metric^S^1^steps/sleep/weight/heart_rate/hydration~range^S^0^today/7d (default)/30d+ remove_memory|C|Remove a memory by its id (requires confirmation)|id^N^1^ add_to_memory|-|Add a new memory to the list of memories|content^S^1^ astronomy_get_tonight|-|Tonight: sunset, Moon, planets.|latitude^N^0^~longitude^N^0^+get_weather_forecast|-|Forecast (5 days + hours) for place.|location^S^1^place~days^N^0^1-5 (def 3) """
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.ktindex 64f611ca8e..6905acbfc0 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt@@ -9,6 +9,7 @@ import com.vayunmathur.library.intents.news.NewsHeadlineData import com.vayunmathur.library.intents.news.NewsStoryData import com.vayunmathur.library.intents.screentime.ScreentimeUsageData import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery+import com.vayunmathur.library.intents.weather.WeatherForecastData  private const val HEALTH_SUMMARY_CHARS = 300 @@ -131,3 +132,29 @@ fun summarizeAstronomyTonight(result: AstronomyTonightData): String =         result.summary.isBlank() -> "No astronomy summary available"         else -> result.summary.take(MAX_TONIGHT_SUMMARY_CHARS)     }++private const val FORECAST_LOCATION_CHARS = 80+private const val FORECAST_CONDITION_CHARS = 60+private const val FORECAST_DAYS_SHOWN = 5+private const val FORECAST_HOURS_SHOWN = 8++fun summarizeWeatherForecast(result: WeatherForecastData): String {+    result.error?.let { return it.take(FORECAST_ERROR_CHARS) }+    if (result.days.isEmpty() && result.hours.isEmpty()) return "No forecast available"+    val lines = mutableListOf<String>()+    result.locationName?.takeIf { it.isNotBlank() }?.let {+        lines += "Forecast for ${it.take(FORECAST_LOCATION_CHARS)}:"+    }+    result.days.take(FORECAST_DAYS_SHOWN).forEach { day ->+        lines += "${day.date}: ${day.condition.take(FORECAST_CONDITION_CHARS)} " ++            "${kotlin.math.round(day.lowC).toInt()}–${kotlin.math.round(day.highC).toInt()}°C, " ++            "precip ${day.precipChancePercent.coerceIn(0, 100)}%"+    }+    result.hours.take(FORECAST_HOURS_SHOWN).forEach { hour ->+        val clock = hour.time.substringAfter('T', hour.time).take(5)+        lines += "$clock: ${kotlin.math.round(hour.temperatureC).toInt()}°C " ++            "${hour.condition.take(FORECAST_CONDITION_CHARS)}, " ++            "precip ${hour.precipChancePercent.coerceIn(0, 100)}%"+    }+    return lines.joinToString("\n")+}
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.ktindex eef47a2c0a..237f3aa9c4 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -78,6 +78,8 @@ import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery import com.vayunmathur.library.intents.education.EducationProgressData import com.vayunmathur.library.intents.astronomy.AstronomyTonightData import com.vayunmathur.library.intents.astronomy.TonightQuery+import com.vayunmathur.library.intents.weather.WeatherForecastData+import com.vayunmathur.library.intents.weather.WeatherForecastQuery   /**@@ -374,4 +376,14 @@ internal abstract class AssistantCoreToolIntents(         )         return summarizeAstronomyTonight(result)     }+    suspend fun getWeatherForecast(location: String, days: Int): String {+        val result: WeatherForecastData = launchIntent(+            context,+            "com.vayunmathur.weather",+            "com.vayunmathur.weather.intents.GetForecastIntent",+            WeatherForecastQuery(location = location, days = days),+        )+        return summarizeWeatherForecast(result)+    }+ }
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.ktindex e3b0c8dcec..5e9cd2eff1 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -80,6 +80,7 @@ import com.vayunmathur.library.intents.news.NewsStoryQuery import com.vayunmathur.library.intents.news.NewsTopQuery import com.vayunmathur.library.intents.astronomy.AstronomyTonightData import com.vayunmathur.library.intents.astronomy.MAX_TONIGHT_SUMMARY_CHARS+import com.vayunmathur.library.intents.weather.WeatherForecastData  private const val CONVERSATION_SNIPPET_CHARS = 80 private const val MESSAGE_BODY_CHARS = 200
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.ktindex d85104c790..8fda259e3b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -223,6 +223,12 @@ class AssistantTools(                 intents.getAstronomyTonight(a.numberOrNull("latitude"), a.numberOrNull("longitude"))             }         },+        "get_weather_forecast" to { a ->+            intents.runTool {+                val days = a.number("days").toInt().takeIf { it > 0 } ?: 3+                intents.getWeatherForecast(a.string("location"), days)+            }+        },         "get_directions" to { a ->             intents.runTool {                 intents.getDirections(
openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.ktindex 3c6fee3846..534b43139b 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt@@ -22,7 +22,7 @@ class PromptBudgetTest {         val header = declared.length + InferenceService.DEFAULT_SYSTEM_PROMPT.length +             AssistantCatalog.PROMPT_SECTION.length         println("HEADER declared=${declared.length} prompt=${InferenceService.DEFAULT_SYSTEM_PROMPT.length} a2ui=${AssistantCatalog.PROMPT_SECTION.length} total=$header")-        assertEquals(66, ASSISTANT_TOOL_SPECS.size)+        assertEquals(67, ASSISTANT_TOOL_SPECS.size)         assertTrue(header <= MAX_HEADER_CHARS, "header=$header over budget $MAX_HEADER_CHARS")     } 
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex 8368d97acf..30d691367a 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -44,7 +44,7 @@ class AssistantToolsInvokeTest {         assertEquals("Error: create_note needs title", call("create_note", "content" to "x"))         assertTrue(             call("set_timer", "seconds" to "abc").contains("must be a number"))-        assertEquals(66, tools.declarations.size)+        assertEquals(67, tools.declarations.size)     }      @Test fun crossAppToolsReportMissingApps() {@@ -77,6 +77,9 @@ class AssistantToolsInvokeTest {         assertTrue(             call("astronomy_get_tonight", "latitude" to "40.7", "longitude" to "-74.0")                 .startsWith("The Astronomy app is required"))+        assertTrue(+            call("get_weather_forecast", "location" to "Lisbon", "days" to "4")+                .startsWith("The Weather app"))         assertTrue(             call(                 "get_directions",
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktindex 6d1856dc41..c91429dd26 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -14,7 +14,7 @@ class AssistantToolsTest {     @Test     fun namesAreUniqueSnakeCase() {         val names = ASSISTANT_TOOL_SPECS.map { it.name }-        assertEquals(66, names.size)+        assertEquals(67, names.size)         assertEquals(names.size, names.toSet().size)         for (spec in ASSISTANT_TOOL_SPECS) {             assertTrue(snake.matches(spec.name), spec.name)@@ -55,6 +55,7 @@ class AssistantToolsTest {                 "create_location_share_link.duration_millis", "play_music.id",                 "set_alarm.hour", "set_alarm.minute", "set_timer.seconds",                 "get_weather.latitude", "get_weather.longitude", "remove_memory.id",+                "get_weather_forecast.days",                 "create_todo.due", "create_todo.priority",                 "get_directions.from_lat", "get_directions.from_lng",                 "get_directions.to_lat", "get_directions.to_lng",
openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.ktindex fdd2a164e8..c01420430a 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt@@ -16,6 +16,9 @@ import com.vayunmathur.library.intents.shop.OrderData as ShopOrderData import com.vayunmathur.library.intents.shop.ProductData import com.vayunmathur.library.intents.shop.ProductDetailData import com.vayunmathur.library.intents.shop.ProductVariantData+import com.vayunmathur.library.intents.weather.ForecastDayData+import com.vayunmathur.library.intents.weather.ForecastHourData+import com.vayunmathur.library.intents.weather.WeatherForecastData import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull@@ -33,6 +36,7 @@ import com.vayunmathur.openassistant.platform.summarizeConversations import com.vayunmathur.openassistant.platform.summarizeConversationMessages import com.vayunmathur.openassistant.platform.summarizeSendResult import com.vayunmathur.openassistant.platform.summarizeDirections+import com.vayunmathur.openassistant.platform.summarizeWeatherForecast import com.vayunmathur.openassistant.platform.summarizeRideEstimate import com.vayunmathur.openassistant.platform.summarizeOrderLookup import com.vayunmathur.openassistant.platform.summarizeAstronomyTonight@@ -179,4 +183,31 @@ class SummarizeNewToolsTest {         assertTrue(orders.contains("order_id=o1 Store pending 2400 USD items=2"), orders)         assertEquals("No shop orders", summarizeShopOrders(emptyList()))     }++    @Test fun weatherForecastSummarizesCappedLinesOnly() {+        val longCondition = "Rain ".repeat(30).trim()+        val days = (1..7).map {+            ForecastDayData("2026-01-0$it", 10.0 + it, 1.0 + it, longCondition, 130)+        }+        val hours = (0 until 20).map {+            ForecastHourData("2026-01-02T${it.toString().padStart(2, '0')}:00", 5.0 + it, longCondition, -3)+        }+        val text = summarizeWeatherForecast(+            WeatherForecastData(locationName = "L".repeat(100), days = days, hours = hours),+        )+        val lines = text.lines()+        // Header + at most 5 daily lines + at most 8 hourly lines, however+        // many entries the payload carries.+        assertEquals(14, lines.size)+        assertTrue(lines[0].startsWith("Forecast for " + "L".repeat(80) + ":"), lines[0])+        assertTrue(lines[1].startsWith("2026-01-01: "), lines[1])+        assertTrue(lines[1].contains("2–11°C, precip 100%"), lines[1])+        assertTrue(lines[6].startsWith("00:00: 5°C "), lines[6])+        assertTrue(lines.all { !it.contains(longCondition) }, text)+        assertEquals(+            "No location matched 'Atlantis'",+            summarizeWeatherForecast(WeatherForecastData(error = "No location matched 'Atlantis'")),+        )+        assertEquals("No forecast available", summarizeWeatherForecast(WeatherForecastData()))+    } }
weather/AGENTS.md
diff --git a/weather/AGENTS.md b/weather/AGENTS.mdindex 45949082d7..45be3f9211 100644--- a/weather/AGENTS.md+++ b/weather/AGENTS.md@@ -15,7 +15,7 @@ _Install: ./install weather (dev by default)._ **Key features:** - Saved locations + device location (reverse-geocoded) with Room-cached forecasts refreshed by `WeatherRefreshWorker` - Metric blocks + graphs per location; Open-Meteo vector map tiles via the Rust core (`domain/map/OmTilesNative`)-- Two Glance widgets (standard + blob); `GetWeather`/`GetWeatherByName` assistant intents+- Two Glance widgets (standard + blob); `GetWeather`/`GetWeatherByName` current-conditions and `GetForecast` capped multi-day/hourly assistant intents **Architecture / data-flow:** `ui/` home/map/locations → `platform/WeatherViewModel` (+ `WeatherUiContract`) → `data/WeatherRepository` over Room + `network/WeatherApi`; all weather reads come from the static R2 packs (`network/WxStatic`: `run.wxp`/`hist/<day>.wxp`/`geo.wxp` + `latest.json` manifest on `static.maproj.org/wx/v1/`), computed on device by `domain/wx/`; the map samples the same run tiles (no `.om`/`data_spatial` read); place search is the on-device `places.db.br` catalogue; `domain/` holds pure unit/metric/WMO formatting + map metadata; widgets read the same repository snapshot. **Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/HomePage.kt` → `platform/WeatherViewModel.kt` → `data/WeatherRepository.kt` → `network/WeatherApi.kt`. **Gotchas:**@@ -68,6 +68,7 @@ _Install: ./install weather (dev by default)._ ### intents/ — assistant IPC - com/vayunmathur/weather/intents/GetWeatherIntent.kt - com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt+- com/vayunmathur/weather/intents/GetForecastIntent.kt — validated `WeatherForecastQuery` contract: named place resolves saved places first, then the catalogue (or an explicit coordinate pair); returns at most 5 days + 12 hourly summary entries, never raw series ### ui/ + ui/components/ + blocks/ — home, map, locations, metric blocks - com/vayunmathur/weather/ui/HomePage.kt - com/vayunmathur/weather/ui/ForecastColumn.kt
weather/src/main/AndroidManifest.xml
diff --git a/weather/src/main/AndroidManifest.xml b/weather/src/main/AndroidManifest.xmlindex 98a26fd0c9..1ad9d0df44 100644--- a/weather/src/main/AndroidManifest.xml+++ b/weather/src/main/AndroidManifest.xml@@ -64,6 +64,12 @@             android:theme="@android:style/Theme.NoDisplay"             android:permission="com.vayunmathur.weather.permissions.ACCESS_WEATHER" /> +        <activity+            android:name=".intents.GetForecastIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.weather.permissions.ACCESS_WEATHER" />+         <!-- Car hosts (Android Auto / MA Auto) bind to this service by its              CarAppService intent-filter; the host is validated in code via              createHostValidator(), so no manifest permission can be required. -->
weather/src/main/java/com/vayunmathur/weather/intents/GetForecastIntent.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/intents/GetForecastIntent.kt b/weather/src/main/java/com/vayunmathur/weather/intents/GetForecastIntent.ktnew file mode 100644index 0000000000..5fa3fe3e24--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/intents/GetForecastIntent.kt@@ -0,0 +1,179 @@+package com.vayunmathur.weather.intents++import android.content.Context+import com.vayunmathur.library.intents.weather.DEFAULT_FORECAST_DAYS+import com.vayunmathur.library.intents.weather.ForecastDayData+import com.vayunmathur.library.intents.weather.ForecastHourData+import com.vayunmathur.library.intents.weather.MAX_FORECAST_CONDITION_CHARS+import com.vayunmathur.library.intents.weather.MAX_FORECAST_DAYS+import com.vayunmathur.library.intents.weather.MAX_FORECAST_HOURS+import com.vayunmathur.library.intents.weather.MAX_FORECAST_LOCATION_CHARS+import com.vayunmathur.library.intents.weather.WeatherForecastData+import com.vayunmathur.library.intents.weather.WeatherForecastQuery+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.data.WeatherRepository+import com.vayunmathur.weather.domain.nowIndex+import com.vayunmathur.weather.domain.todayIndex+import com.vayunmathur.weather.domain.weatherConditionForCode+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.WeatherApi+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.serializer++/**+ * "Headless" activity launched by OpenAssistant's `get_weather_forecast`+ * tool. Resolves the query's named place — the user's saved Weather+ * places first, then the on-device catalogue — or its explicit+ * coordinates, fetches the bundle, and returns a capped summary:+ * at most [MAX_FORECAST_DAYS] days and [MAX_FORECAST_HOURS] hourly+ * entries, one distilled value per field. The bundle's raw hourly/daily+ * series never cross the wire. No UI — the activity finishes immediately+ * as dictated by the [AssistantIntent] base class.+ */+@OptIn(InternalSerializationApi::class)+class GetForecastIntent : AssistantIntent<WeatherForecastQuery, WeatherForecastData>(+    inputSerializer = serializer<WeatherForecastQuery>(),+    outputSerializer = serializer<WeatherForecastData>(),+) {+    // Broad catch is deliberate: a headless assistant intent must return a payload,+    // never throw, and network plus parsing throw undocumented RuntimeExceptions.+    @Suppress("TooGenericExceptionCaught")+    override suspend fun performCalculation(input: WeatherForecastQuery): WeatherForecastData {+        val query = validatedForecastQuery(input)+        return try {+            forecastFor(query) ?: errorWeatherForecast(+                query.location.takeIf { it.isNotBlank() },+                when {+                    query.location.isNotBlank() -> "No location matched '${query.location}'"+                    query.latitude != null || query.longitude != null -> "Invalid coordinates"+                    else -> "No location given"+                },+            )+        } catch (e: Exception) {+            errorWeatherForecast(+                query.location.takeIf { it.isNotBlank() },+                e.message ?: "Failed to fetch forecast",+            )+        }+    }++    private suspend fun forecastFor(query: WeatherForecastQuery): WeatherForecastData? {+        // A named place wins: saved places first (they are the places the+        // user actually tracks), then the catalogue via geocode.+        if (query.location.isNotBlank()) {+            findSavedLocation(savedLocations(), query.location)?.let { saved ->+                val forecast = WeatherApi.forecast(saved.latitude, saved.longitude)+                return forecast.toWeatherForecastData(this, savedLabel(saved), query)+            }+            val place = WeatherApi.geocode(query.location, limit = 1).results.firstOrNull()+                ?: return null+            val forecast = WeatherApi.forecast(place.latitude, place.longitude)+            val label = listOfNotNull(place.name, place.country)+                .filter { it.isNotBlank() }+                .joinToString(", ")+            return forecast.toWeatherForecastData(this, label.ifBlank { place.name }, query)+        }+        // Coordinates are valid only as an in-range pair (validated below).+        val latitude = query.latitude ?: return null+        val longitude = query.longitude ?: return null+        if (!validCoordinates(latitude, longitude)) return null+        val forecast = WeatherApi.forecast(latitude, longitude)+        return forecast.toWeatherForecastData(this, locationName = null, query)+    }++    private suspend fun savedLocations(): List<SavedLocation> =+        runCatching { WeatherRepository.get(this).getLocations() }.getOrDefault(emptyList())+}++/**+ * The validated form of a raw query: location trimmed and truncated to+ * [MAX_FORECAST_LOCATION_CHARS], days clamped to 1..[MAX_FORECAST_DAYS]+ * (0/negative means "unspecified" and becomes [DEFAULT_FORECAST_DAYS]),+ * hours clamped to 0..[MAX_FORECAST_HOURS].+ */+internal fun validatedForecastQuery(input: WeatherForecastQuery): WeatherForecastQuery = WeatherForecastQuery(+    location = input.location.trim().take(MAX_FORECAST_LOCATION_CHARS),+    latitude = input.latitude,+    longitude = input.longitude,+    days = if (input.days <= 0) DEFAULT_FORECAST_DAYS else input.days.coerceAtMost(MAX_FORECAST_DAYS),+    hours = input.hours.coerceIn(0, MAX_FORECAST_HOURS),+)++/** True when both coordinates are finite and in range; lone halves are invalid. */+internal fun validCoordinates(latitude: Double, longitude: Double): Boolean =+    latitude.isFinite() && longitude.isFinite() &&+        latitude in -90.0..90.0 && longitude in -180.0..180.0++/**+ * The saved place a query names: an exact (case-insensitive) name or+ * "name, country" match wins, then a substring match either way.+ * Blank-named rows (an unresolved device location) never match.+ */+internal fun findSavedLocation(locations: List<SavedLocation>, query: String): SavedLocation? {+    val needle = query.trim().lowercase()+    if (needle.isEmpty()) return null+    val named = locations.filter { it.name.isNotBlank() }+    return named.firstOrNull { saved ->+        saved.name.trim().lowercase() == needle || savedLabel(saved).lowercase() == needle+    } ?: named.firstOrNull { saved ->+        val name = saved.name.trim().lowercase()+        name.contains(needle) || needle.contains(name)+    }+}++internal fun savedLabel(saved: SavedLocation): String =+    listOf(saved.name, saved.country).filter { it.isNotBlank() }.joinToString(", ")++internal fun errorWeatherForecast(locationName: String?, error: String) = WeatherForecastData(+    locationName = locationName,+    error = error,+)++/**+ * Distill a full [ForecastResponse] into the capped cross-app forecast:+ * [WeatherForecastQuery.days] daily entries starting today and+ * [WeatherForecastQuery.hours] hourly entries starting now. Out-of-range+ * or missing series values degrade to defaults, never raw arrays.+ */+internal fun ForecastResponse.toWeatherForecastData(+    context: Context,+    locationName: String?,+    query: WeatherForecastQuery,+): WeatherForecastData {+    val dayStart = todayIndex(daily, current?.time)+    val days = daily?.let { d ->+        (dayStart until minOf(dayStart + query.days, d.time.size)).map { i ->+            ForecastDayData(+                date = d.time.getOrElse(i) { "" },+                highC = d.temperatureMax.getOrElse(i) { 0.0 },+                lowC = d.temperatureMin.getOrElse(i) { 0.0 },+                condition = d.weatherCode.getOrNull(i)?.let {+                    context.getString(weatherConditionForCode(it).label)+                        .take(MAX_FORECAST_CONDITION_CHARS)+                } ?: "",+                precipChancePercent = d.precipitationProbabilityMax.getOrElse(i) { 0 }.coerceIn(0, 100),+            )+        }+    } ?: emptyList()++    val hourStart = nowIndex(hourly, current?.time)+    val hours = hourly?.let { h ->+        (hourStart until minOf(hourStart + query.hours, h.time.size)).map { i ->+            ForecastHourData(+                time = h.time.getOrElse(i) { "" },+                temperatureC = h.temperature.getOrElse(i) { 0.0 },+                condition = h.weatherCode.getOrNull(i)?.let {+                    context.getString(weatherConditionForCode(it).label)+                        .take(MAX_FORECAST_CONDITION_CHARS)+                } ?: "",+                precipChancePercent = h.precipitationProbability.getOrElse(i) { 0 }.coerceIn(0, 100),+            )+        }+    } ?: emptyList()++    if (days.isEmpty() && hours.isEmpty()) {+        return errorWeatherForecast(locationName, "No forecast available")+    }+    return WeatherForecastData(locationName = locationName, days = days, hours = hours)+}
weather/src/test/java/com/vayunmathur/weather/intents/GetForecastIntentTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/intents/GetForecastIntentTest.kt b/weather/src/test/java/com/vayunmathur/weather/intents/GetForecastIntentTest.ktnew file mode 100644index 0000000000..7c6670dde9--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/intents/GetForecastIntentTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.weather.intents++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.intents.weather.MAX_FORECAST_DAYS+import com.vayunmathur.library.intents.weather.MAX_FORECAST_HOURS+import com.vayunmathur.library.intents.weather.WeatherForecastData+import com.vayunmathur.library.intents.weather.WeatherForecastQuery+import com.vayunmathur.weather.data.SavedLocation+import com.vayunmathur.weather.network.Current+import com.vayunmathur.weather.network.Daily+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.network.Hourly+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** GetForecastIntent validated contract: caps, saved-place matching, mapping. */+@RunWith(AndroidJUnit4::class)+class GetForecastIntentTest {++    private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun validatedQueryClampsDaysHoursAndLocation() {+        assertEquals(MAX_FORECAST_DAYS, validatedForecastQuery(WeatherForecastQuery(location = "X", days = 99)).days)+        assertEquals(3, validatedForecastQuery(WeatherForecastQuery(location = "X", days = 0)).days)+        assertEquals(3, validatedForecastQuery(WeatherForecastQuery(location = "X", days = -4)).days)+        assertEquals(2, validatedForecastQuery(WeatherForecastQuery(location = "X", days = 2)).days)+        assertEquals(1, validatedForecastQuery(WeatherForecastQuery(location = "X", days = 1)).days)+        assertEquals(MAX_FORECAST_HOURS, validatedForecastQuery(WeatherForecastQuery(location = "X", hours = 99)).hours)+        assertEquals(0, validatedForecastQuery(WeatherForecastQuery(location = "X", hours = -1)).hours)+        assertEquals(5, validatedForecastQuery(WeatherForecastQuery(location = "X", hours = 5)).hours)+        val long = validatedForecastQuery(WeatherForecastQuery(location = "  " + "a".repeat(200) + "  "))+        assertEquals(120, long.location.length)+    }++    @Test fun coordinatesAreValidatedAsAnInRangePair() {+        assertTrue(validCoordinates(52.52, 13.405))+        assertTrue(validCoordinates(-90.0, 180.0))+        assertFalse(validCoordinates(90.1, 0.0))+        assertFalse(validCoordinates(0.0, -180.1))+        assertFalse(validCoordinates(Double.NaN, 0.0))+        assertFalse(validCoordinates(0.0, Double.POSITIVE_INFINITY))+    }++    @Test fun savedLocationMatchingPrefersExactAndIgnoresBlankNames() {+        val berlin = SavedLocation(id = 1, name = "Berlin", country = "Germany", latitude = 52.52, longitude = 13.405)+        val bern = SavedLocation(id = 2, name = "Bern", country = "Switzerland", latitude = 46.95, longitude = 7.45)+        val device = SavedLocation(id = 3, name = "", country = "", latitude = 1.0, longitude = 2.0, isCurrent = true)+        val places = listOf(berlin, bern, device)+        assertEquals(berlin, findSavedLocation(places, "berlin"))+        assertEquals(berlin, findSavedLocation(places, "Berlin, Germany"))+        assertEquals(berlin, findSavedLocation(places, "erlin"))+        assertEquals(bern, findSavedLocation(places, "Bern, Switzerland"))+        assertEquals(bern, findSavedLocation(places, "weekend in Bern"))+        assertNull(findSavedLocation(places, "Atlantis"))+        assertNull(findSavedLocation(places, ""))+        assertNull(findSavedLocation(listOf(device), "Berlin"))+    }++    @Test fun mappingCapsDaysAndHoursAndClampsPrecip() {+        val query = validatedForecastQuery(WeatherForecastQuery(location = "X", days = 99, hours = 99))+        val data = forecastResponse().toWeatherForecastData(context, "X", query)+        assertNull(data.error)+        assertEquals(MAX_FORECAST_DAYS, data.days.size)+        assertEquals(MAX_FORECAST_HOURS, data.hours.size)+        assertEquals("2026-01-02", data.days.first().date)+        assertEquals(100, data.days.first().precipChancePercent)+        assertEquals(0, data.hours.first().precipChancePercent)+        assertTrue(data.days.all { it.condition.length <= 60 })+        assertTrue(data.hours.all { it.condition.length <= 60 })+    }++    @Test fun mappingStartsTodayAndNowNotAtSeriesStart() {+        val query = WeatherForecastQuery(location = "X", days = 2, hours = 3)+        val data = forecastResponse().toWeatherForecastData(context, "X", query)+        assertEquals(listOf("2026-01-02", "2026-01-03"), data.days.map { it.date })+        assertEquals(+            listOf("2026-01-02T12:00", "2026-01-02T13:00", "2026-01-02T14:00"),+            data.hours.map { it.time },+        )+    }++    @Test fun blankAndInvalidQueriesReturnTypedErrors() = runTest {+        val blank = GetForecastIntent().performCalculation(WeatherForecastQuery(location = "  "))+        assertEquals("No location given", blank.error)+        assertTrue(blank.days.isEmpty() && blank.hours.isEmpty())+        val invalid = GetForecastIntent().performCalculation(+            WeatherForecastQuery(location = "", latitude = 91.0, longitude = 0.0),+        )+        assertEquals("Invalid coordinates", invalid.error)+        val loneHalf = GetForecastIntent().performCalculation(+            WeatherForecastQuery(location = "", latitude = 10.0),+        )+        assertEquals("Invalid coordinates", loneHalf.error)+    }++    @Test fun forecastDtoRoundTrips() {+        val query = validatedForecastQuery(WeatherForecastQuery(location = "Berlin", days = 99, hours = 99))+        val data = forecastResponse().toWeatherForecastData(context, "Berlin", query)+        val json = Json { ignoreUnknownKeys = true }+        val decoded = json.decodeFromString<WeatherForecastData>(+            json.encodeToString(WeatherForecastData.serializer(), data),+        )+        assertEquals(data, decoded)+        assertEquals(+            WeatherForecastQuery(location = "Berlin", days = 3, hours = 6),+            json.decodeFromString<WeatherForecastQuery>("""{"location":"Berlin"}"""),+        )+    }++    private fun forecastResponse(): ForecastResponse {+        // Series start one day / twelve hours before "now" (2026-01-02T12:00)+        // so today/now indexing — not index 0 — decides the window.+        val dates = (1..8).map { "2026-01-0$it" }+        val hourTimes = (0 until 48).map { h ->+            val day = 1 + h / 24+            "2026-01-0${day}T${(h % 24).toString().padStart(2, '0')}:00"+        }+        return ForecastResponse(+            latitude = 52.52,+            longitude = 13.405,+            timezone = "Europe/Berlin",+            current = Current(+                time = "2026-01-02T12:00", temperature = 5.0, apparentTemperature = 3.0,+                relativeHumidity = 80, weatherCode = 61, windSpeed = 10.0, windDirection = 90,+            ),+            hourly = Hourly(+                time = hourTimes,+                temperature = List(48) { it.toDouble() },+                weatherCode = List(48) { 61 },+                precipitationProbability = List(48) { if (it == 36) -5 else 40 },+            ),+            daily = Daily(+                time = dates,+                weatherCode = List(8) { 61 },+                temperatureMax = List(8) { 10.0 + it },+                temperatureMin = List(8) { 1.0 + it },+                precipitationProbabilityMax = List(8) { if (it == 1) 150 else 30 },+            ),+        )+    }+}