From 2ed29838cafe81857db702933afbbcc53659f886 Mon Sep 17 00:00:00 2001 From: Randy Westergren Date: Sun, 22 Nov 2026 08:46:34 -0500 Subject: [PATCH] Fix account-specific diary group resolution Use None for automatic selection so group 0 remains writable. Resolve automatic meals from account preferences and reject incomplete or ambiguous layouts before writing. Normalize explicit names across case and whitespace, preserve supplied entry times, and document the Python client sentinel change. Fixes #90 --- README.md | 16 ++ src/cronometer_api_mcp/client.py | 120 ++++++++------ src/cronometer_api_mcp/server.py | 19 ++- tests/test_client.py | 3 +- tests/test_diary_groups.py | 266 +++++++++++++++++++++++++++---- tests/test_entry_time.py | 2 +- tests/test_notes.py | 2 +- 7 files changed, 338 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 4055fb5..21fe9ae 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,22 @@ cached session, so it also overrides a stale cached timezone. All date parameters use `YYYY-MM-DD` format and default to today when omitted. +### Diary groups + +`add_food_entry`, `add_note`, and `add_exercise` accept `diary_group="auto"` +or an enabled group name from `get_diary_groups`. Names match ignoring case +and whitespace, in any language. Group 0 and Uncategorized are writable; +duplicate enabled names must be made distinct in Cronometer. + +`"auto"` requires unique enabled groups named Breakfast, Lunch, Dinner, and +Snacks, in any positions. It picks by the entry's time in the account timezone +(`time=` for food and notes, or now). If any of those names is missing, +disabled, or ambiguous, choose an explicit group name. Missing profile prefs +use compatibility defaults; explicit names and visibility flags take precedence. + +Python client callers: omit `diary_group` or pass `None` for automatic selection. +An integer, including `0`, always selects that actual group number. + ### Relative dates and recent days `get_food_log`, `get_daily_nutrition`, and `get_nutrition_scores` also accept diff --git a/src/cronometer_api_mcp/client.py b/src/cronometer_api_mcp/client.py index 897539d..08781b1 100644 --- a/src/cronometer_api_mcp/client.py +++ b/src/cronometer_api_mcp/client.py @@ -21,6 +21,7 @@ import struct import threading import time +import unicodedata from datetime import date, datetime, timedelta from datetime import time as dtime from pathlib import Path @@ -148,7 +149,7 @@ TARGET_ROW_IDS = {"protein_g": 203, "fat_g": 204, "net_carbs_g": -1205} SODIUM_ID = 307 -# Cronometer's defaults when DGnn names or DGnnON visibility prefs are unset. +# Compatibility defaults for missing DGnn names or DGnnON visibility prefs. _DIARY_GROUP_DEFAULTS = ( ("Uncategorized", True), ("Breakfast", True), @@ -1609,7 +1610,7 @@ def add_serving( grams: float, translation_id: int = 0, day: date | None = None, - diary_group: int = 0, + diary_group: int | None = None, at: dtime | None = None, ) -> dict: """Log a food serving to the diary. @@ -1623,12 +1624,10 @@ def add_serving( grams: Weight in grams. translation_id: Translation ID (from search results, usually 0). day: Date to log to. Defaults to today. - diary_group: Meal group number. 0 = auto: the group is picked by - time of day as 1-4 (see _meal_group_for_hour), which - is Breakfast/Lunch/Dinner/Snacks only on an account - with the default groups. Otherwise the number from - get_diary_groups; resolve_diary_group maps a name to - it. + diary_group: Group number from get_diary_groups, including 0. + None picks by time of day and requires unique enabled + Breakfast/Lunch/Dinner/Snacks names in the account. + resolve_diary_group maps an explicit name to a number. at: Time of day to stamp the entry with, in the account timezone. Defaults to now. Also drives the auto meal group. @@ -1638,8 +1637,8 @@ def add_serving( day_str = self._format_day(day) time_str = f"{when.hour}:{when.minute}:{when.second}" - if diary_group == 0: - diary_group = _meal_group_for_hour(when.hour) + if diary_group is None: + diary_group = self._auto_diary_group_for_hour(when.hour) serving = { "order": (diary_group << 16) | 1, @@ -1679,7 +1678,7 @@ def add_note( self, text: str, day: date | None = None, - diary_group: int = 0, + diary_group: int | None = None, at: dtime | None = None, ) -> dict: """Add a note to a diary day. @@ -1688,7 +1687,7 @@ def add_note( text: The note text. day: Date to add it to. Defaults to today. diary_group: Meal group number the note sits in, as for - add_serving (0 = auto, by time of day). + add_serving (None = auto, by time of day; 0 is a real group). at: Time of day to stamp the note with, in the account timezone. Defaults to now. Also drives the auto meal group. @@ -1696,8 +1695,8 @@ def add_note( """ now = self.now() when = at or now.time() - if diary_group == 0: - diary_group = _meal_group_for_hour(when.hour) + if diary_group is None: + diary_group = self._auto_diary_group_for_hour(when.hour) # The UTC offset in force on the note's own date and time, in the # account's zone (not now's offset: they differ across a DST change). stamped = datetime.combine(day or now.date(), when, tzinfo=self._tzinfo()) @@ -2482,11 +2481,11 @@ def get_diary_groups(self) -> list[dict]: Group names are account settings stored as DG01..DG08 profile prefs (name) with a DGnnON twin (visibility). A diary entry's `order` carries its group in the bits above 16 (`order >> 16`), and that index is the - pref number minus one: DG01 is group 0 (where exercise and biometrics - sit), DG02 is group 1, and so on. The names and count are customizable, + pref number minus one: DG01 is group 0, DG02 is group 1, and so on. + The names and count are customizable, so "lunch" is not always group 2 -- resolve names through this list instead of assuming the default Breakfast/Lunch/Dinner/Snacks layout. - Unset names and visibility flags use Cronometer's defaults: groups + Unset names and visibility flags use compatibility defaults: groups 0-4 are enabled and groups 5-7 are hidden. Returns [{"group": int, "pref": "DG04", "name": str, "enabled": bool}]. @@ -2526,28 +2525,27 @@ def _diary_groups_for_lookup(self) -> tuple[list[dict], bool]: def resolve_diary_group(self, diary_group: str) -> dict: """Turn a diary group name into the group number the write calls take. - "auto" (any case) resolves to 0, which add_serving, add_note and + "auto" (any case) resolves to None, which add_serving, add_note and add_exercise treat as "pick by time of day". Any other value is - matched, case-insensitively, against the names of the account's + matched, ignoring case and whitespace, against the names of the account's enabled groups (see get_diary_groups), so "dinner" is group 4 on an account with a "Post-workout" slot and 3 on one without. A name that isn't in the cached list is looked up again once before failing, so groups renamed or added in the app work without a restart. - Raises ValueError for an unknown, disabled or ambiguous name, and for - the group numbered 0 (Uncategorized by default): 0 is the "auto" - sentinel everywhere below, so it cannot be addressed by name. + Raises ValueError for an unknown, disabled or ambiguous name. + Group 0 is writable like every other enabled group. - Returns {"group": int, "name": str}; "auto" gives {"group": 0, "name": + Returns {"group": int, "name": str}; "auto" gives {"group": None, "name": "auto"}. """ - key = diary_group.strip().lower() + key = _diary_group_key(diary_group) if key == "auto": - return {"group": 0, "name": "auto"} + return {"group": None, "name": "auto"} def find(groups: list[dict]) -> list[dict]: - return [g for g in groups if g["name"].strip().lower() == key] + return [g for g in groups if _diary_group_key(g["name"]) == key] groups, fetched = self._diary_groups_for_lookup() matches = find(groups) @@ -2555,7 +2553,7 @@ def find(groups: list[dict]) -> list[dict]: groups = self.get_diary_groups() matches = find(groups) - writable = [g for g in matches if g["enabled"] and g["group"] != 0] + writable = [g for g in matches if g["enabled"]] if len(writable) > 1: numbers = ", ".join(str(g["group"]) for g in writable) raise ValueError( @@ -2566,23 +2564,43 @@ def find(groups: list[dict]) -> list[dict]: match = writable[0] return {"group": match["group"], "name": match["name"]} if not matches: - names = ["auto"] + [ - g["name"] for g in groups if g["enabled"] and g["group"] != 0 - ] + names = ["auto"] + [g["name"] for g in groups if g["enabled"]] raise ValueError( f"Invalid diary_group '{diary_group}'. " f"Must be one of: {', '.join(names)}." ) - match = matches[0] - if not match["enabled"]: - raise ValueError( - f"Diary group '{match['name']}' is disabled in the account." - ) raise ValueError( - f"Diary group '{match['name']}' is group 0, which means " - '"auto" here and cannot be chosen by name.' + f"Diary group '{matches[0]['name']}' is disabled in the account." ) + def _auto_diary_group_for_hour(self, hour: int) -> int: + """Resolve all four meal names from one account layout before picking.""" + + def find(groups: list[dict]) -> dict[str, list[int]]: + meals: dict[str, list[int]] = { + name: [] for name in ("breakfast", "lunch", "dinner", "snacks") + } + for group in groups: + key = _diary_group_key(group["name"]) + if group["enabled"] and key in meals: + meals[key].append(group["group"]) + return meals + + groups, fetched = self._diary_groups_for_lookup() + meals = find(groups) + if any(len(matches) != 1 for matches in meals.values()) and not fetched: + groups = self.get_diary_groups() + meals = find(groups) + if any(len(matches) != 1 for matches in meals.values()): + names = ", ".join(g["name"] for g in groups if g["enabled"]) or "(none)" + raise ValueError( + "Cannot resolve diary_group 'auto': requires unique enabled " + "Breakfast, Lunch, Dinner and Snacks groups. " + f"Available groups: {names}. " + "Choose an explicit diary_group from get_diary_groups." + ) + return meals[_meal_name_for_hour(hour)][0] + def get_macro_split(self) -> dict: """Saved macro ratios as percentages of energy. @@ -2856,7 +2874,7 @@ def add_exercise( minutes: float, calories: float, day: date | None = None, - diary_group: int = 0, + diary_group: int | None = None, ) -> dict: """Log an exercise with a given calorie burn. @@ -2871,7 +2889,7 @@ def add_exercise( minutes: Duration in minutes. calories: Calories burned (a positive number). day: Date to log to. Defaults to today. - diary_group: Meal group, as for add_serving (0 = auto). + diary_group: Meal group, as for add_serving (None = auto). Uses: POST /api/v2/add_exercise @@ -2881,8 +2899,8 @@ def add_exercise( raise ValueError(f"minutes must be positive, got {minutes}") if not math.isfinite(calories) or calories < 0: raise ValueError(f"calories must be zero or positive, got {calories}") - if diary_group == 0: - diary_group = _meal_group_for_hour(self.now().hour) + if diary_group is None: + diary_group = self._auto_diary_group_for_hour(self.now().hour) exercise = { "exerciseId": None, @@ -2997,18 +3015,18 @@ def _v3_diary_entry(entry: dict) -> dict: return out -def _meal_group_for_hour(hour: int) -> int: - """Map hour of day to a Cronometer diary meal group number. +def _diary_group_key(name: str) -> str: + """Match account names without translating them or discarding accents.""" + return "".join(unicodedata.normalize("NFC", name).casefold().split()) - Returns 1-4, which are Breakfast, Lunch, Dinner and Snacks only on an - account with the default groups; it does not consult the account's own - group names. This is what "auto" uses. - """ + +def _meal_name_for_hour(hour: int) -> str: + """Pick a meal name; its group number comes from the account's prefs.""" if 4 <= hour < 10: - return 1 # Breakfast + return "breakfast" elif 10 <= hour < 14: - return 2 # Lunch + return "lunch" elif 14 <= hour < 21: - return 3 # Dinner + return "dinner" else: - return 4 # Snacks + return "snacks" diff --git a/src/cronometer_api_mcp/server.py b/src/cronometer_api_mcp/server.py index 81b5932..4b3a778 100644 --- a/src/cronometer_api_mcp/server.py +++ b/src/cronometer_api_mcp/server.py @@ -155,7 +155,7 @@ def _group_echo(group: dict) -> dict: Only for an explicitly named group: "auto" is chosen from the time of day inside the client, so there is nothing resolved to report. """ - if group["group"] == 0: + if group["group"] is None: return {} return {"diary_group": group} @@ -273,8 +273,8 @@ def get_diary_groups() -> str: `group` here is that number, so an entry with order 196609 is in group 3. Returns each group as {group, pref, name, enabled}, in diary order. Group 0 - is where exercise and biometrics entries sit. A group with enabled=false is - hidden in the app, so no entries are expected there. + is a regular slot whose name depends on the account. A group with + enabled=false is hidden in the app but may still contain older entries. """ try: client = _get_client() @@ -335,8 +335,9 @@ def add_food_entry( translation_id: Translation ID from search results (usually 0). diary_group: Meal slot: "auto" (default, picks by time of day) or the name of one of the account's diary groups, matched - case-insensitively. Group names are customizable; call - get_diary_groups to see them. + ignoring case and whitespace. "auto" requires unique + enabled Breakfast, Lunch, Dinner and Snacks groups; + otherwise choose an explicit name from get_diary_groups. time: Time of day to log at, 24-hour HH:MM or HH:MM:SS in the account timezone (defaults to now). With diary_group "auto", this also picks the meal slot, so logging lunch late still lands in lunch. @@ -418,7 +419,9 @@ def add_note( date: Date as YYYY-MM-DD (defaults to today). diary_group: Meal slot the note sits in: "auto" (default, picks by time of day) or the name of one of the account's diary groups, - matched case-insensitively (see get_diary_groups). + matched ignoring case and whitespace. "auto" requires unique + enabled Breakfast, Lunch, Dinner and Snacks groups; otherwise + choose an explicit name from get_diary_groups. time: Time of day for the note, 24-hour HH:MM or HH:MM:SS in the account timezone (defaults to now). With diary_group "auto", this also picks the meal slot. @@ -1388,7 +1391,9 @@ def add_exercise( date: Date as YYYY-MM-DD (defaults to today). diary_group: Meal slot: "auto" (default, picks by time of day) or the name of one of the account's diary groups, matched - case-insensitively (see get_diary_groups). + ignoring case and whitespace. "auto" requires unique enabled + Breakfast, Lunch, Dinner and Snacks groups; otherwise choose an + explicit name from get_diary_groups. """ try: client = _get_client() diff --git a/tests/test_client.py b/tests/test_client.py index b940a3f..12a8dae 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -163,11 +163,12 @@ def test_add_serving_cold_start_embeds_real_user_id(tmp_path): """First write on a cold client logs in once and sends the real userId.""" client, state = make_cold_client(tmp_path, [{"result": "SUCCESS", "id": 7}]) - client.add_serving(food_id=1, measure_id=0, grams=100.0) + client.add_serving(food_id=1, measure_id=0, grams=100.0, diary_group=0) assert state["login"] == 1 assert state["post"] == 1 # no stale-payload double failure (#31) assert state["payloads"][0]["serving"]["userId"] == 42 + assert state["payloads"][0]["serving"]["order"] == 1 def test_user_id_property_triggers_login(tmp_path): diff --git a/tests/test_diary_groups.py b/tests/test_diary_groups.py index a83c5c8..ed5d084 100644 --- a/tests/test_diary_groups.py +++ b/tests/test_diary_groups.py @@ -7,6 +7,7 @@ import pytest from test_client import make_cold_client +from test_notes import capture_forms from cronometer_api_mcp import client as client_module @@ -38,6 +39,31 @@ def profile(**prefs) -> dict: "weightUnit": "Pounds", } +BREAKFAST_FIRST = { + "DG01": "Breakfast", + "DG01ON": "true", + "DG02": "Lunch", + "DG02ON": "true", + "DG03": "Dinner", + "DG03ON": "true", + "DG04": "Snacks", + "DG04ON": "true", + "DG05": "Uncategorized", + "DG05ON": "true", + "DG06": "Post workout", + "DG06ON": "false", + "DG07": "Group 7", + "DG07ON": "false", + "DG08": "Group 8", + "DG08ON": "false", +} + +WRITE_TOOLS = [ + ("add_food_entry", {"food_id": 1, "measure_id": 0, "grams": 100}), + ("add_note", {"text": "late snack"}), + ("add_exercise", {"activity_id": 1, "minutes": 30, "calories": 200}), +] + def test_group_index_is_pref_number_minus_one(tmp_path): client, _ = make_cold_client(tmp_path, [profile(**CUSTOM_GROUPS)]) @@ -187,11 +213,11 @@ def test_resolve_names_use_the_accounts_numbers(tmp_path): assert client.resolve_diary_group("Pre-bedtime")["group"] == 5 -def test_resolve_auto_is_zero_without_reading_the_profile(tmp_path): +def test_resolve_auto_defers_selection_until_the_entry_time_is_known(tmp_path): client, state = make_cold_client(tmp_path, [profile(**CUSTOM_GROUPS)]) - assert client.resolve_diary_group("auto") == {"group": 0, "name": "auto"} - assert client.resolve_diary_group(" AUTO ")["group"] == 0 + assert client.resolve_diary_group("auto") == {"group": None, "name": "auto"} + assert client.resolve_diary_group(" AUTO ")["group"] is None assert state["post"] == 0 @@ -250,9 +276,8 @@ def test_resolve_unknown_name_lists_the_valid_ones(tmp_path): assert "Invalid diary_group 'brunch'" in message for name in ("auto", "Breakfast", "Post-workout", "Dinner", "Snacks"): assert name in message - # Hidden and sentinel groups are not offered. assert "Group 8" not in message - assert "Exercise and Biometrics" not in message + assert "Exercise and Biometrics" in message def test_resolve_rejects_a_disabled_group(tmp_path): @@ -262,23 +287,53 @@ def test_resolve_rejects_a_disabled_group(tmp_path): client.resolve_diary_group("group 8") -def test_resolve_rejects_group_zero_by_name(tmp_path): - """0 is the auto sentinel, so group 0 can't be addressed by name.""" +def test_resolve_accepts_group_zero_by_name(tmp_path): client, _ = make_cold_client(tmp_path, [profile(**CUSTOM_GROUPS)]) - with pytest.raises(ValueError, match="auto"): - client.resolve_diary_group("Exercise and Biometrics") + assert client.resolve_diary_group("Exercise and Biometrics") == { + "group": 0, + "name": "Exercise and Biometrics", + } + + +@pytest.mark.parametrize( + "stored,requested", + [ + ("Petit déjeuner", " PETIT\tDÉJEUNER "), + ("Dîner", "DI\u0302NER"), + ("Straße", "STRASSE"), + ("夕食", "夕 食"), + ], +) +def test_resolve_localized_names_ignores_case_and_whitespace( + tmp_path, stored, requested +): + client, _ = make_cold_client( + tmp_path, [profile(**{**BREAKFAST_FIRST, "DG01": stored})] + ) + + assert client.resolve_diary_group(requested) == {"group": 0, "name": stored} + + +def test_resolve_does_not_translate_or_strip_accents(tmp_path): + client, _ = make_cold_client( + tmp_path, [profile(**{**BREAKFAST_FIRST, "DG03": "Dîner"})] + ) + + for name in ("Dinner", "Diner"): + with pytest.raises(ValueError, match="Invalid diary_group"): + client.resolve_diary_group(name) @pytest.mark.parametrize( "overrides", [ {"DG02": " dinner ", "DG02ON": "false"}, - {"DG01": " DINNER "}, + {"DG01": " DINNER ", "DG01ON": "false"}, {"DG02": "Dinner", "DG02ON": "false", "DG08": "dinner"}, ], ) -def test_resolve_ignores_unwritable_groups_with_the_same_name(tmp_path, overrides): +def test_resolve_ignores_disabled_groups_with_the_same_name(tmp_path, overrides): client, _ = make_cold_client(tmp_path, [profile(**{**CUSTOM_GROUPS, **overrides})]) assert client.resolve_diary_group("dinner") == {"group": 4, "name": "Dinner"} @@ -311,28 +366,26 @@ def test_add_food_entry_uses_default_groups_when_prefs_are_unset( assert state["payloads"][-1]["serving"]["order"] == (group << 16) | 1 -@pytest.mark.parametrize( - "tool,kwargs", - [ - ("add_food_entry", {"food_id": 1, "measure_id": 0, "grams": 100}), - ("add_note", {"text": "late snack"}), - ("add_exercise", {"activity_id": 1, "minutes": 30, "calories": 200}), - ], -) -def test_ambiguous_group_names_do_not_write(tmp_path, monkeypatch, tool, kwargs): +@pytest.mark.parametrize("tool,kwargs", WRITE_TOOLS) +@pytest.mark.parametrize("pref,numbers", [("DG01", "0, 4"), ("DG03", "2, 4")]) +def test_ambiguous_group_names_do_not_write( + tmp_path, monkeypatch, tool, kwargs, pref, numbers +): from cronometer_api_mcp import server client, state = make_cold_client( - tmp_path, [profile(**{**CUSTOM_GROUPS, "DG03": " DINNER "})] + tmp_path, [profile(**{**CUSTOM_GROUPS, pref: " DIN NER "})] ) monkeypatch.setattr(server, "_client", client) + forms = capture_forms(client) result = json.loads(getattr(server, tool)(**kwargs, diary_group="dinner")) assert result["status"] == "error" assert "Ambiguous diary_group 'dinner'" in result["message"] - assert "2, 4" in result["message"] + assert numbers in result["message"] assert state["post"] == 1 + assert forms == [] def test_add_food_entry_writes_to_the_named_group_and_echoes_it(tmp_path, monkeypatch): @@ -353,22 +406,177 @@ def test_add_food_entry_writes_to_the_named_group_and_echoes_it(tmp_path, monkey assert serving["order"] == (4 << 16) | 1 -def test_add_food_entry_auto_keeps_the_hour_based_numbers(tmp_path, monkeypatch): - """auto is unchanged: hour -> 1-4, with no profile read and no echo.""" +@pytest.mark.parametrize("tool,kwargs", WRITE_TOOLS) +@pytest.mark.parametrize( + "prefs,name,group", + [ + (BREAKFAST_FIRST, "Breakfast", 0), + (BREAKFAST_FIRST, "Uncategorized", 4), + ({}, "Uncategorized", 0), + (CUSTOM_GROUPS, "Pre-bedtime", 5), + ], +) +def test_named_groups_are_written_and_echoed( + tmp_path, monkeypatch, tool, kwargs, prefs, name, group +): + from cronometer_api_mcp import server + + account = profile(**{**prefs, "weightInKG": 80}) + responses = [account] * (2 if tool == "add_exercise" else 1) + client, state = make_cold_client( + tmp_path, [*responses, {"result": "SUCCESS", "id": 7}] + ) + monkeypatch.setattr(server, "_client", client) + forms = capture_forms(client) + + result = json.loads(getattr(server, tool)(**kwargs, diary_group=name)) + + assert result["status"] == "success" + assert result["diary_group"] == {"group": group, "name": name} + if tool == "add_note": + assert int(forms[0]["order"]) == (group << 16) | 1 + else: + entry = "exercise" if tool == "add_exercise" else "serving" + assert state["payloads"][-1][entry]["order"] == (group << 16) | 1 + + +@pytest.mark.parametrize("tool,kwargs", WRITE_TOOLS) +@pytest.mark.parametrize( + "prefs,groups", + [ + (BREAKFAST_FIRST, (0, 1, 2, 3)), + (CUSTOM_GROUPS, (1, 3, 4, 6)), + ({}, (1, 2, 3, 4)), + ], + ids=["breakfast-first", "custom", "missing-prefs"], +) +@pytest.mark.parametrize( + "hour,meal", [(3, 3), (4, 0), (9, 0), (10, 1), (13, 1), (14, 2), (20, 2), (21, 3)] +) +def test_auto_writes_to_account_groups_using_the_entry_time( + tmp_path, monkeypatch, tool, kwargs, prefs, groups, hour, meal +): from cronometer_api_mcp import server - client, state = make_cold_client(tmp_path, [{"result": "SUCCESS", "id": 7}]) + account = profile(**{**prefs, "weightInKG": 80}) + responses = [account] * (2 if tool == "add_exercise" else 1) + client, state = make_cold_client( + tmp_path, [*responses, {"result": "SUCCESS", "id": 7}] + ) monkeypatch.setattr(server, "_client", client) + forms = capture_forms(client) + clock_hour = hour if tool == "add_exercise" else 0 monkeypatch.setattr( - client, "now", lambda: datetime(2026, 11, 13, 19, 8, tzinfo=UTC) + client, "now", lambda: datetime(2026, 11, 13, clock_hour, 8, tzinfo=UTC) ) + at = {} if tool == "add_exercise" else {"time": f"{hour:02}:30"} - result = json.loads(server.add_food_entry(food_id=1, measure_id=0, grams=100)) + result = json.loads(getattr(server, tool)(**kwargs, **at)) assert result["status"] == "success" assert "diary_group" not in result - assert state["post"] == 1 # just the add_serving call - assert state["payloads"][-1]["serving"]["order"] == (3 << 16) | 1 + if tool == "add_note": + assert int(forms[0]["order"]) == (groups[meal] << 16) | 1 + assert forms[0]["time"] == f"{hour:02}:30:00" + else: + entry = "exercise" if tool == "add_exercise" else "serving" + assert state["payloads"][-1][entry]["order"] == (groups[meal] << 16) | 1 + + +@pytest.mark.parametrize("tool,kwargs", WRITE_TOOLS) +@pytest.mark.parametrize( + "overrides", + [ + {"DG04": "Evening snack"}, + {"DG04ON": "false"}, + {"DG05": " BREAK FAST "}, + { + "DG01": "Petit déjeuner", + "DG02": "Déjeuner", + "DG03": "Dîner", + "DG04": "Collations", + }, + {f"DG{i:02}ON": "false" for i in range(1, 9)}, + ], + ids=["missing", "disabled", "duplicate", "localized", "all-disabled"], +) +def test_auto_requires_all_four_unique_enabled_meals_before_writing( + tmp_path, monkeypatch, tool, kwargs, overrides +): + from cronometer_api_mcp import server + + client, state = make_cold_client( + tmp_path, [profile(**{**BREAKFAST_FIRST, **overrides})] + ) + monkeypatch.setattr(server, "_client", client) + monkeypatch.setattr(client, "now", lambda: datetime(2026, 11, 13, 8, tzinfo=UTC)) + forms = capture_forms(client) + + result = json.loads(getattr(server, tool)(**kwargs)) + + assert result["status"] == "error" + assert "Cannot resolve diary_group 'auto'" in result["message"] + assert "Choose an explicit diary_group" in result["message"] + for group in client._diary_groups: + if group["enabled"]: + assert group["name"] in result["message"] + assert state["post"] == 1 + assert forms == [] + + +def test_auto_reuses_the_group_cache(tmp_path): + client, state = make_cold_client(tmp_path, [profile(**BREAKFAST_FIRST)]) + + client.resolve_diary_group("Breakfast") + assert client._auto_diary_group_for_hour(8) == 0 + assert client._auto_diary_group_for_hour(12) == 1 + assert state["post"] == 1 + + +@pytest.mark.parametrize( + "overrides", [{"DG04": "Other"}, {"DG04ON": "false"}, {"DG05": "Lunch"}] +) +def test_auto_refreshes_an_unusable_cached_layout_once(tmp_path, overrides): + client, state = make_cold_client( + tmp_path, + [profile(**{**BREAKFAST_FIRST, **overrides}), profile(**BREAKFAST_FIRST)], + ) + client.get_diary_groups() + + assert client._auto_diary_group_for_hour(8) == 0 + assert state["post"] == 2 + + +def test_auto_stops_after_one_refresh_of_an_unusable_layout(tmp_path): + client, state = make_cold_client( + tmp_path, [profile(**{**BREAKFAST_FIRST, "DG04": "Other"})] + ) + client.get_diary_groups() + + with pytest.raises(ValueError, match="Choose an explicit diary_group"): + client._auto_diary_group_for_hour(8) + assert state["post"] == 2 + + +@pytest.mark.parametrize("tool,kwargs", WRITE_TOOLS) +def test_auto_profile_failure_does_not_write(tmp_path, monkeypatch, tool, kwargs): + from cronometer_api_mcp import server + + client, state = make_cold_client(tmp_path, [{}]) + monkeypatch.setattr(server, "_client", client) + forms = capture_forms(client) + + def unavailable(): + raise RuntimeError("profile unavailable") + + monkeypatch.setattr(client, "_get_profile_prefs", unavailable) + + result = json.loads(getattr(server, tool)(**kwargs)) + + assert result["status"] == "error" + assert "profile unavailable" in result["message"] + assert state["post"] == 0 + assert forms == [] def test_add_food_entry_unknown_group_returns_an_error(tmp_path, monkeypatch): diff --git a/tests/test_entry_time.py b/tests/test_entry_time.py index bec02e1..1843a43 100644 --- a/tests/test_entry_time.py +++ b/tests/test_entry_time.py @@ -13,7 +13,7 @@ @pytest.fixture def client(monkeypatch): c = Mock(spec=CronometerClient) - c.resolve_diary_group.return_value = {"group": 0, "name": "auto"} + c.resolve_diary_group.return_value = {"group": None, "name": "auto"} c.add_serving.return_value = {"id": 1} c.add_note.return_value = {"noteId": 2} monkeypatch.setattr(server, "_client", c) diff --git a/tests/test_notes.py b/tests/test_notes.py index 9449c75..351c182 100644 --- a/tests/test_notes.py +++ b/tests/test_notes.py @@ -119,7 +119,7 @@ def test_add_note_at_drives_the_auto_group(tmp_path): client.add_note("lunchish", DAY, at=dtime(12, 30)) assert forms[0]["time"] == "12:30:00" - # 12:30 is Lunch, group 2 (see _meal_group_for_hour), not the 23:00 group. + # 12:30 is Lunch in the fallback layout, not the 23:00 Snacks group. assert forms[0]["order"] == str((2 << 16) | 1)