From 88ee5ec2cb518de77c90078c9d2c5d700222e81f Mon Sep 17 00:00:00 2001 From: javis-bot Date: Wed, 18 Nov 2026 16:10:06 +0900 Subject: [PATCH] feat(weather): the app's log names the service that gave the weather MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The source line (KMA, open-meteo or met.no for now; KMA and open-meteo day counts for a forecast) only went to debug_log, which is off by default and muted while the worker's brain answers, so a live answer such as "흐림" could not be traced to its service. It now goes to the llm log tab without the place or the key. Co-Authored-By: Claude Opus 5.5 --- src/jarvis/debug.py | 10 ++++++ src/jarvis/tools/builtin/weather.py | 12 ++++--- src/voice_worker/voice_worker.spec.md | 4 ++- tests/tools/builtin/test_weather.py | 49 +++++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/src/jarvis/debug.py b/src/jarvis/debug.py index 1035614..15722b7 100644 --- a/src/jarvis/debug.py +++ b/src/jarvis/debug.py @@ -35,3 +35,13 @@ def debug_log(message: str, category: str = "debug") -> None: print(f"[{category:^10}] {message}", file=sys.stderr) except Exception: pass + + +def notice(message: str, category: str = "debug") -> None: + """A line that is written also without debug logging, to the process's original stderr, so it + still reaches the app's log while the voice worker mutes the reply engine's output. It must carry + no question, answer, place or other text from the conversation.""" + try: + print(f"[{category:^10}] {message}", file=sys.__stderr__, flush=True) + except Exception: + pass diff --git a/src/jarvis/tools/builtin/weather.py b/src/jarvis/tools/builtin/weather.py index ccc4680..71cfe31 100644 --- a/src/jarvis/tools/builtin/weather.py +++ b/src/jarvis/tools/builtin/weather.py @@ -7,7 +7,7 @@ from datetime import datetime, timedelta, timezone import requests from typing import Dict, Any, Optional -from ...debug import debug_log +from ...debug import debug_log, notice from ...utils.location import get_location_info from ..base import Tool, ToolContext from ..types import ToolExecutionResult @@ -674,8 +674,8 @@ class WeatherTool(Tool): rest = [off for off in offsets if off not in days] if rest: days.update(_open_meteo_days(lat, lon, rest)) - debug_log(f" 🌤️ forecast days {first}-{last}: {from_kma} from KMA, " - f"{len(days) - from_kma} from open-meteo", "tools") + # Which service gave the answer, in the app's log (no place: it comes from the question). + notice(f"weather days {first}-{last}: {from_kma} from KMA, {len(days) - from_kma} from open-meteo", "llm") place = location_display.split(",")[0].strip() or location_display return [_day_sentence(off, days[off], place, detail) for off in offsets if off in days] @@ -863,12 +863,12 @@ class WeatherTool(Tool): } current: Dict[str, Any] = {} + source = "KMA" kma_key = _kma_key_now() if kma_key and country_code == "KR": current = _kma_current(lat, lon, kma_key) - if current: - debug_log(" 🌤️ current weather from KMA", "tools") if not current: + source = "open-meteo" try: weather_response = requests.get(weather_url, params=weather_params, timeout=_OPEN_METEO_TIMEOUT_SEC) @@ -877,12 +877,14 @@ class WeatherTool(Tool): except Exception as e: # Live 2026-11-18: the forecast server stopped answering while geocoding worked. debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools") + source = "met.no" current = _met_no_current(lat, lon) if not current: return ToolExecutionResult( success=False, reply_text=f"Weather data temporarily unavailable for {location_display}." ) + notice(f"weather now: {source}", "llm") # Extract current weather values temp_c = current.get("temperature_2m") diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index 64f8f1d..61344c7 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -298,7 +298,9 @@ which carry Discord's own time. highest chance of rain), then 중기예보 for the nearest of the KMA cities in `weather.py` and its region (중기기온, 중기육상). Days KMA does not give, and every KMA failure, come from open-meteo (now: then met.no; later days: open-meteo's daily forecast only). The key is in KMA's URLs, so a failure is - logged by its kind only. `detail` (only when the user asks for more detail) adds the + logged by its kind only. Which service answered is printed without debug logging (category + `llm`, no place and no key): `weather now: KMA` (or `open-meteo`, `met.no`) and + `weather days -: from KMA, from open-meteo`. `detail` (only when the user asks for more detail) adds the humidity, the wind in m/s and the rain amount: now the last hour's rain (KMA 초단기실황 RN1, open-meteo `precipitation`; none from met.no), a 단기예보 day its mean humidity and strongest wind, an open-meteo day its strongest wind and rain total; 중기예보 has none of these. A dry diff --git a/tests/tools/builtin/test_weather.py b/tests/tools/builtin/test_weather.py index f4e0fe9..15e95f4 100644 --- a/tests/tools/builtin/test_weather.py +++ b/tests/tools/builtin/test_weather.py @@ -433,6 +433,29 @@ class TestWeatherTool: assert WMO_CODES_KO[80] in result.reply_text assert str(round(8.6)) in result.reply_text + @patch('requests.get') + def test_the_log_names_met_no_when_it_gave_the_weather_now(self, mock_get, capfd): + geo = Mock(status_code=200, raise_for_status=Mock()) + geo.json.return_value = {"results": [{"latitude": 37.57, "longitude": 126.98, + "name": "서울", "country": "대한민국"}]} + met = Mock(status_code=200, raise_for_status=Mock()) + met.json.return_value = {"properties": {"timeseries": [{"data": { + "instant": {"details": {"air_temperature": 8.6}}, + "next_1_hours": {"summary": {"symbol_code": "cloudy"}}}}]}} + + def get(url, *a, **k): + if "geocoding" in url: + return geo + if "open-meteo" in url: + raise requests.exceptions.Timeout("timed out") + return met + mock_get.side_effect = get + + self.tool.run({"location": "Seoul"}, self.context) + + err = capfd.readouterr().err + assert "weather now: met.no" in err and "서울" not in err + @pytest.mark.parametrize("symbol", ["lightsleet", "sleet_day", "heavysleetshowers_night"]) def test_met_no_sleet_stays_sleet_not_freezing_rain(self, symbol): from src.jarvis.tools.builtin.weather import _met_no_wmo @@ -722,6 +745,23 @@ class TestKmaWeather: assert len(kma) == 2 and all(p["authKey"] == self.KEY for p in kma) assert all((p["nx"], p["ny"]) == (60, 127) for p in kma) + @pytest.mark.parametrize("key, source", [(True, "KMA"), (False, "open-meteo")]) + @patch('requests.get') + def test_the_log_names_the_service_that_gave_the_weather_now_and_not_the_place( + self, mock_get, key, source, monkeypatch, capfd): + """Live 2026-11-18: "흐림" could have come from either service, and nothing said which.""" + if key: + monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY) + else: + monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False) + mock_get.side_effect = self._routes() + + self.tool.run({"location": "Seoul"}, self.context) + + err = capfd.readouterr().err + assert f"weather now: {source}" in err + assert "Seoul" not in err and self.KEY not in err + @patch('requests.get') def test_precipitation_wins_over_the_sky(self, mock_get, monkeypatch): monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY) @@ -1053,6 +1093,15 @@ class TestForecast: assert "강수확률 80%" in result.reply_text assert not any(self.KEY in str(c) for c in log.call_args_list) + @pytest.mark.parametrize("fail_kma, counts", [(False, "1 from KMA, 0 from open-meteo"), + (True, "0 from KMA, 1 from open-meteo")]) + def test_the_log_says_how_many_forecast_days_each_service_gave(self, fail_kma, counts, monkeypatch, capfd): + self._run({"days_ahead": 1}, monkeypatch, fail_kma=fail_kma) + + err = capfd.readouterr().err + assert f"weather days 1-1: {counts}" in err + assert "Seoul" not in err and self.KEY not in err + def test_outside_korea_the_forecast_is_open_meteos_daily_one(self, monkeypatch): result, calls = self._run({"days_ahead": 1}, monkeypatch, country_code="JP")