From 6cd3470502977e8eecd51f04286bf2cd9e3f8733 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Tue, 17 Nov 2026 21:05:41 +0100 Subject: [PATCH] Add the Claude meal estimator estimate_meal(text, photo) -> Estimate runs Claude through claude_agent_sdk in an isolated CLAUDE_CONFIG_DIR: a copy of the access token (no refresh token, no MCP tokens) and the diet-food skill, never kuhy's ~/.claude. The skill text is the system prompt; the closest curated and derived food-bank rows ride in the user message; the photo is an image block; the answer is constrained by a JSON schema and validated again. Failure paths, all fail closed (an EstimateError code, nothing logged): - no host login, CLI/API error, bad transport: estimate_failed - more than 45 s: estimate_timeout - no object, missing/mistyped field, NaN/inf/negative/absurd number, grams 0, blank or long desc: estimate_invalid - neither text nor photo: ValueError before any model call - failed token refresh is logged, the call then fails as estimate_failed Live smoke (scratch HOME, nothing logged): "2 jajka sadzone i kromka chleba" -> 315 kcal in 4.3 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC --- app/pubspec.yaml | 2 +- diet_guard/_claude_bank.py | 50 ++++++ diet_guard/_claude_estimate.py | 96 ++++++++++ diet_guard/_claude_schema.py | 136 +++++++++++++++ diet_guard/tests/_claude_fakes.py | 86 +++++++++ diet_guard/tests/test_claude_estimate.py | 128 ++++++++++++++ diet_guard/tests/test_claude_schema.py | 105 +++++++++++ diet_guard/tests/test_claude_sdk.py | 212 +++++++++++++++++++++++ skills/diet-food/SKILL.md | 60 +++++++ 9 files changed, 874 insertions(+), 1 deletion(-) create mode 100644 diet_guard/_claude_bank.py create mode 100644 diet_guard/_claude_estimate.py create mode 100644 diet_guard/_claude_schema.py create mode 100644 diet_guard/tests/_claude_fakes.py create mode 100644 diet_guard/tests/test_claude_estimate.py create mode 100644 diet_guard/tests/test_claude_schema.py create mode 100644 diet_guard/tests/test_claude_sdk.py create mode 100644 skills/diet-food/SKILL.md diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 7675f79..bf8e477 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,7 +2,7 @@ name: diet_guard_app description: "Companion phone app for diet_guard: log meals on the go." publish_to: 'none' -version: 1.0.166+1 +version: 1.0.167+1 environment: sdk: ^3.12.2 diff --git a/diet_guard/_claude_bank.py b/diet_guard/_claude_bank.py new file mode 100644 index 0000000..03881ae --- /dev/null +++ b/diet_guard/_claude_bank.py @@ -0,0 +1,50 @@ +"""The food-bank rows handed to the estimator. + +The skill looks the bank up first (kuhy's own logged numbers beat generic +ones), but the whole bank would bloat every prompt. So the rows are the +closest matches for each part of the typed meal plus the most-logged staples, +deduplicated. Curated and log-derived rows both come through +:func:`diet_guard._foodbank_search.search_foods`. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Final + +from diet_guard._foodbank_search import search_foods + +if TYPE_CHECKING: + from diet_guard._estimator import Nutrition + +#: Splits a meal typed as a list: commas, plus, "i"/"oraz"/"and"/"with". +_PARTS: Final = re.compile( + r"\s*(?:,|;|\+|\bi\b|\boraz\b|\band\b|\bz\b)\s*", re.IGNORECASE +) +PER_QUERY: Final = 4 +STAPLES: Final = 6 +MAX_ROWS: Final = 20 + + +def _row(name: str, nutrition: Nutrition) -> str: + """One bank row as a compact line the model can scale.""" + return ( + f"{name} | {nutrition.grams:g} g | {nutrition.kcal:g} kcal | " + f"P{nutrition.protein_g:g} C{nutrition.carbs_g:g} F{nutrition.fat_g:g}" + ) + + +def bank_rows(text: str | None) -> list[str]: + """Bank rows relevant to ``text``, best first, at most :data:`MAX_ROWS`. + + A photo-only request (``text`` None or blank) gets the staples alone. + """ + queries = [text.strip()] if text and text.strip() else [] + queries += [part for part in _PARTS.split(text or "") if part.strip()] + rows: dict[str, str] = {} + for query in dict.fromkeys(queries): + for name, nutrition in search_foods(query, PER_QUERY): + rows.setdefault(name.casefold(), _row(name, nutrition)) + for name, nutrition in search_foods("", STAPLES): + rows.setdefault(name.casefold(), _row(name, nutrition)) + return list(rows.values())[:MAX_ROWS] diff --git a/diet_guard/_claude_estimate.py b/diet_guard/_claude_estimate.py new file mode 100644 index 0000000..e2ea633 --- /dev/null +++ b/diet_guard/_claude_estimate.py @@ -0,0 +1,96 @@ +"""Estimate one meal with Claude: ``estimate_meal(text, photo) -> Estimate``. + +The pure entry point for the relay worker now and the Tk gate later. It never +logs anything: it returns an :class:`~diet_guard._claude_schema.Estimate` or +raises :class:`EstimateError` with the contract's error code, and the caller +decides. Every failure (no login, CLI or API error, timeout, invalid JSON) +is an error, never a guess (fail closed). + +The model runs through :func:`diet_guard._claude_sdk.run_model` in an +isolated config dir with the ``diet-food`` skill as its system prompt, the +text and photo as one user message, and the closest food-bank rows. +""" + +from __future__ import annotations + +import asyncio +import base64 +from typing import Any, Final + +from diet_guard import _claude_sandbox, _claude_sdk +from diet_guard._claude_bank import bank_rows +from diet_guard._claude_schema import ( + SCHEMA, + Estimate, + InvalidEstimateError, + parse_estimate, +) + +#: Contract error codes (``docs/DOCS-claude-relay.md`` section 3). +TIMEOUT: Final = "estimate_timeout" +FAILED: Final = "estimate_failed" +INVALID: Final = "estimate_invalid" + +#: Wall-clock budget for one model call; the contract's 45 s. +BUDGET_S: Final = 45.0 + + +class EstimateError(Exception): + """The meal could not be estimated; ``code`` is the contract's code.""" + + def __init__(self, code: str, message: str) -> None: + """Carry the contract ``code`` and a log-only ``message``.""" + super().__init__(message) + self.code = code + + +def _content(text: str | None, photo: bytes | None) -> list[dict[str, Any]]: + """The user message: the typed meal, the bank rows, the photo.""" + rows = bank_rows(text) + parts = [f"Meal as typed: {text.strip()}" if text and text.strip() else "No text."] + if rows: + parts.append("Food bank (name | grams | kcal | macros per logged portion):") + parts.extend(rows) + blocks: list[dict[str, Any]] = [{"type": "text", "text": "\n".join(parts)}] + if photo is not None: + data = base64.b64encode(photo).decode("ascii") + source = {"type": "base64", "media_type": "image/jpeg", "data": data} + blocks.append({"type": "image", "source": source}) + return blocks + + +async def estimate_meal_async(text: str | None, photo: bytes | None) -> Estimate: + """Estimate one meal; for callers already inside an event loop. + + Raises: + ValueError: neither ``text`` nor ``photo`` was given. + EstimateError: the model failed, timed out or answered nonsense. + """ + if not (text and text.strip()) and photo is None: + msg = "nothing to estimate: no text and no photo" + raise ValueError(msg) + prompt = await asyncio.to_thread(_claude_sandbox.skill_text) + content = await asyncio.to_thread(_content, text, photo) + try: + answer = await _claude_sdk.run_model(prompt, content, SCHEMA, budget_s=BUDGET_S) + except _claude_sdk.ModelTimeoutError as err: + raise EstimateError(TIMEOUT, str(err)) from err + except _claude_sdk.ModelError as err: + raise EstimateError(FAILED, str(err)) from err + try: + return parse_estimate(answer) + except InvalidEstimateError as err: + raise EstimateError(INVALID, str(err)) from err + + +def estimate_meal(text: str | None, photo: bytes | None) -> Estimate: + """Estimate one meal from a description and/or a JPEG photo (blocking). + + Not callable from inside a running event loop; use + :func:`estimate_meal_async` there. + + Raises: + ValueError: neither ``text`` nor ``photo`` was given. + EstimateError: the model failed, timed out or answered nonsense. + """ + return asyncio.run(estimate_meal_async(text, photo)) diff --git a/diet_guard/_claude_schema.py b/diet_guard/_claude_schema.py new file mode 100644 index 0000000..e22b49f --- /dev/null +++ b/diet_guard/_claude_schema.py @@ -0,0 +1,136 @@ +"""The estimator's strict output: a JSON schema and a validator. + +The schema goes to the model as ``output_format`` (so the CLI constrains the +answer), and :func:`parse_estimate` re-validates what came back: a model +answer that is not a sane, complete object is never logged. Pure stdlib, so +the gate can import it. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Any, Final + +MAX_DESC: Final = 120 +MAX_GRAMS: Final = 5000.0 +MAX_KCAL: Final = 5000.0 + +_NUMBERS: Final = ("grams", "kcal", "protein_g", "carbs_g", "fat_g") +_NUMBER: Final = {"type": "number", "minimum": 0} +_ITEM_PROPS: Final = { + "name": {"type": "string", "minLength": 1, "maxLength": MAX_DESC}, + **dict.fromkeys(_NUMBERS, _NUMBER), +} + +#: The JSON schema the model's answer must satisfy. +SCHEMA: Final[dict[str, Any]] = { + "type": "object", + "additionalProperties": False, + "required": ["desc", *_NUMBERS], + "properties": { + "desc": {"type": "string", "minLength": 1, "maxLength": MAX_DESC}, + **dict.fromkeys(_NUMBERS, _NUMBER), + "components": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": False, + "required": ["name", *_NUMBERS], + "properties": _ITEM_PROPS, + }, + }, + }, +} + + +class InvalidEstimateError(ValueError): + """The model's answer is not a usable estimate.""" + + +@dataclass(frozen=True) +class Estimate: + """One estimated meal: totals for the whole portion. + + Attributes: + desc: Short name for the whole meal. + grams: Total edible weight, greater than 0. + kcal: Energy for the portion. + protein_g: Protein for the portion. + carbs_g: Carbohydrate for the portion. + fat_g: Fat for the portion. + components: Per-item breakdown, or None for a single item. + """ + + desc: str + grams: float + kcal: float + protein_g: float + carbs_g: float + fat_g: float + components: tuple[dict[str, object], ...] | None = None + + +def _number(data: dict[str, Any], key: str, ceiling: float) -> float: + """``data[key]`` as a finite float in ``[0, ceiling]`` (bool is refused).""" + value = data.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)): + msg = f"{key} is not a number" + raise InvalidEstimateError(msg) + number = float(value) + if not math.isfinite(number) or not 0 <= number <= ceiling: + msg = f"{key}={value!r} is out of range" + raise InvalidEstimateError(msg) + return number + + +def _text(data: dict[str, Any], key: str) -> str: + """``data[key]`` as a non-blank string of at most :data:`MAX_DESC`.""" + value = data.get(key) + if not isinstance(value, str) or not value.strip() or len(value) > MAX_DESC: + msg = f"{key} is not a short non-blank string" + raise InvalidEstimateError(msg) + return value.strip() + + +def _macros(data: dict[str, Any]) -> dict[str, float]: + """The five numbers every meal and every component carries.""" + numbers = { + "grams": _number(data, "grams", MAX_GRAMS), + "kcal": _number(data, "kcal", MAX_KCAL), + } + for key in ("protein_g", "carbs_g", "fat_g"): + numbers[key] = _number(data, key, MAX_GRAMS) + return numbers + + +def _component(item: object) -> dict[str, object]: + """One validated component.""" + if not isinstance(item, dict): + msg = "a component is not an object" + raise InvalidEstimateError(msg) + return {"name": _text(item, "name"), **_macros(item)} + + +def parse_estimate(data: object) -> Estimate: + """Validate the model's answer. + + Raises: + InvalidEstimateError: not an object, a field is missing or mistyped, + a number is non-finite, negative or absurd, or ``grams`` is 0. + """ + if not isinstance(data, dict): + msg = "the answer is not an object" + raise InvalidEstimateError(msg) + numbers = _macros(data) + if numbers["grams"] <= 0: + msg = "grams must be greater than 0" + raise InvalidEstimateError(msg) + raw = data.get("components") + components: tuple[dict[str, object], ...] | None = None + if raw is not None: + if not isinstance(raw, list): + msg = "components is not a list" + raise InvalidEstimateError(msg) + components = tuple(_component(item) for item in raw) + return Estimate(desc=_text(data, "desc"), components=components, **numbers) diff --git a/diet_guard/tests/_claude_fakes.py b/diet_guard/tests/_claude_fakes.py new file mode 100644 index 0000000..86a0a71 --- /dev/null +++ b/diet_guard/tests/_claude_fakes.py @@ -0,0 +1,86 @@ +"""Fakes for the relay and estimator tests: a fake SDK, a fake RTDB, fresh modules. + +The conftest redirects replace the relay's entry points (``connect_sealed``, +``run_model``, the sync touch points) with blockers. A test of the *real* +function loads a pristine copy of its module with :func:`fresh` instead of +fighting the patch. +""" + +from __future__ import annotations + +import asyncio +import importlib.util +import json +import sys +from types import ModuleType, SimpleNamespace +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + from pathlib import Path + + +def fresh(module: ModuleType) -> ModuleType: + """A pristine second copy of ``module``, untouched by any redirect.""" + name = f"{module.__name__}__fresh" + spec = importlib.util.spec_from_file_location(name, module.__file__) + assert spec is not None + assert spec.loader is not None + copy = importlib.util.module_from_spec(spec) + sys.modules[name] = copy + spec.loader.exec_module(copy) + return copy + + +class FakeResult: + """A stand-in ``ResultMessage``.""" + + def __init__(self, structured: object, *, is_error: bool = False) -> None: + """Carry the structured answer and the error flag.""" + self.structured_output = structured + self.is_error = is_error + self.subtype = "error_during_execution" if is_error else "success" + self.errors = ["boom"] if is_error else None + self.result = "text" + + +class FakeSdk(SimpleNamespace): + """A stand-in ``claude_agent_sdk`` that records what it was asked.""" + + def __init__(self, messages: list[object], *, hang: bool = False) -> None: + """Replay ``messages``; with ``hang`` the query never finishes.""" + self.calls: list[dict[str, Any]] = [] + self._messages = messages + self._hang = hang + super().__init__( + ClaudeAgentOptions=SimpleNamespace, + ResultMessage=FakeResult, + query=self._query, + ) + + async def _query( + self, *, prompt: AsyncIterator[dict[str, Any]], options: object + ) -> AsyncIterator[object]: + sent = [item async for item in prompt] + self.calls.append({"sent": sent, "options": options}) + if self._hang: + await asyncio.sleep(60) + for message in self._messages: + yield message + + +def write_host_login(path: Path, expires_ms: int) -> None: + """kuhy's CLI login as it looks on disk, refresh token included.""" + path.write_text( + json.dumps( + { + "claudeAiOauth": { + "accessToken": "tok", + "refreshToken": "SECRET-REFRESH", + "expiresAt": expires_ms, + }, + "mcpOAuth": {"server": {"token": "SECRET-MCP"}}, + } + ), + encoding="utf-8", + ) diff --git a/diet_guard/tests/test_claude_estimate.py b/diet_guard/tests/test_claude_estimate.py new file mode 100644 index 0000000..9524887 --- /dev/null +++ b/diet_guard/tests/test_claude_estimate.py @@ -0,0 +1,128 @@ +"""``estimate_meal``: the prompt it builds and how every failure maps.""" + +from __future__ import annotations + +import asyncio +import base64 +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest + +from diet_guard import _claude_sdk +from diet_guard._claude_bank import bank_rows +from diet_guard._claude_estimate import ( + FAILED, + INVALID, + TIMEOUT, + EstimateError, + estimate_meal, + estimate_meal_async, +) +from diet_guard._estimator import Nutrition +from diet_guard._foodbank import remember_food + +GOOD: dict[str, Any] = { + "desc": "2 jajka sadzone i kromka chleba", + "grams": 190, + "kcal": 410, + "protein_g": 17.5, + "carbs_g": 22, + "fat_g": 26, +} + + +def _fake(result: object = GOOD) -> AsyncMock: + return AsyncMock(return_value=result) + + +def test_text_only_builds_one_text_block_and_returns_the_estimate() -> None: + """The typed meal is sent as text; no image block; the skill is the prompt.""" + model = _fake() + with patch("diet_guard._claude_sdk.run_model", model): + est = estimate_meal("2 jajka sadzone i kromka chleba", None) + assert est.kcal == 410.0 + prompt, content, schema = model.await_args.args + assert not prompt.startswith("---") # the front matter is stripped + assert "How to estimate" in prompt + assert [block["type"] for block in content] == ["text"] + assert "2 jajka sadzone i kromka chleba" in content[0]["text"] + assert schema["required"] + assert model.await_args.kwargs == {"budget_s": 45.0} + + +def test_photo_is_sent_as_a_base64_jpeg_block() -> None: + """A photo rides as an image content block, the way the tutor sends one.""" + model = _fake() + with patch("diet_guard._claude_sdk.run_model", model): + estimate_meal(None, b"\xff\xd8photo") + content = model.await_args.args[1] + assert content[0]["text"].startswith("No text.") + image = content[1] + assert image["type"] == "image" + assert image["source"]["media_type"] == "image/jpeg" + assert base64.b64decode(image["source"]["data"]) == b"\xff\xd8photo" + + +@pytest.mark.parametrize("text", [None, "", " "]) +def test_nothing_to_estimate_is_a_value_error(text: str | None) -> None: + """No text and no photo never reaches the model.""" + model = _fake() + with ( + patch("diet_guard._claude_sdk.run_model", model), + pytest.raises(ValueError, match="nothing to estimate"), + ): + asyncio.run(estimate_meal_async(text, None)) + model.assert_not_awaited() + + +@pytest.mark.parametrize( + ("raised", "code"), + [ + (_claude_sdk.ModelTimeoutError("slow"), TIMEOUT), + (_claude_sdk.ModelError("no login"), FAILED), + ], +) +def test_model_errors_map_to_contract_codes(raised: Exception, code: str) -> None: + """A timeout and any other model failure are distinct error codes.""" + model = AsyncMock(side_effect=raised) + with ( + patch("diet_guard._claude_sdk.run_model", model), + pytest.raises(EstimateError) as caught, + ): + estimate_meal("banan", None) + assert caught.value.code == code + + +def test_invalid_answer_is_estimate_invalid() -> None: + """A schema-breaking answer is an error, never a logged guess.""" + with ( + patch("diet_guard._claude_sdk.run_model", _fake({"desc": "x"})), + pytest.raises(EstimateError) as caught, + ): + estimate_meal("banan", None) + assert caught.value.code == INVALID + + +def test_bank_rows_find_each_part_and_the_staples() -> None: + """Each part of "a i b" finds its own row; staples ride along; no dupes.""" + jajko = Nutrition(kcal=90, protein_g=6, carbs_g=0.5, fat_g=7, grams=60, source="m") + chleb = Nutrition( + kcal=160, protein_g=4.5, carbs_g=21, fat_g=6, grams=70, source="m" + ) + remember_food("jajko sadzone", jajko) + remember_food("kromka chleba", chleb) + rows = bank_rows("jajko sadzone i kromka chleba") + assert any(row.startswith("jajko sadzone | 60 g | 90 kcal") for row in rows) + assert any(row.startswith("kromka chleba | 70 g") for row in rows) + assert len(rows) == len(set(rows)) + assert bank_rows(None) # photo-only: the staples alone + + +def test_bank_rows_empty_bank_is_empty() -> None: + """A fresh install has no rows, and the prompt simply omits the table.""" + assert bank_rows("coś") == [] + model = _fake() + with patch("diet_guard._claude_sdk.run_model", model): + estimate_meal("coś", None) + assert "Food bank" not in model.await_args.args[1][0]["text"] diff --git a/diet_guard/tests/test_claude_schema.py b/diet_guard/tests/test_claude_schema.py new file mode 100644 index 0000000..3bcf6e2 --- /dev/null +++ b/diet_guard/tests/test_claude_schema.py @@ -0,0 +1,105 @@ +"""The estimator's output schema: only a sane, complete JSON object passes.""" + +from __future__ import annotations + +import math +from typing import Any + +import pytest + +from diet_guard._claude_schema import ( + SCHEMA, + Estimate, + InvalidEstimateError, + parse_estimate, +) + +GOOD: dict[str, Any] = { + "desc": "2 jajka sadzone, kromka chleba", + "grams": 190, + "kcal": 410, + "protein_g": 17.5, + "carbs_g": 22, + "fat_g": 26, +} + + +def test_valid_object_becomes_an_estimate() -> None: + """Every required number is carried over, no components by default.""" + est = parse_estimate(GOOD) + assert est == Estimate( + desc="2 jajka sadzone, kromka chleba", + grams=190.0, + kcal=410.0, + protein_g=17.5, + carbs_g=22.0, + fat_g=26.0, + components=None, + ) + + +def test_components_are_validated_and_kept() -> None: + """A component carries the same five numbers plus its name.""" + item = {"name": "jajko", "grams": 60, "kcal": 90, "protein_g": 6, "carbs_g": 0.5} + est = parse_estimate({**GOOD, "components": [{**item, "fat_g": 7}]}) + assert est.components is not None + assert est.components[0]["name"] == "jajko" + assert est.components[0]["fat_g"] == 7.0 + + +@pytest.mark.parametrize( + "bad", + [ + {k: v for k, v in GOOD.items() if k != "kcal"}, + {**GOOD, "desc": " "}, + {**GOOD, "desc": "x" * 121}, + {**GOOD, "desc": 5}, + {**GOOD, "grams": 0}, + {**GOOD, "grams": 6000}, + {**GOOD, "kcal": -1}, + {**GOOD, "kcal": 5001}, + {**GOOD, "protein_g": math.nan}, + {**GOOD, "fat_g": math.inf}, + {**GOOD, "carbs_g": "22"}, + {**GOOD, "kcal": True}, + {**GOOD, "components": "none"}, + {**GOOD, "components": [{"name": "x"}]}, + { + **GOOD, + "components": [ + { + "name": "", + "grams": 1, + "kcal": 1, + "protein_g": 0, + "carbs_g": 0, + "fat_g": 0, + } + ], + }, + {**GOOD, "components": ["x"]}, + ], +) +def test_invalid_object_is_refused(bad: dict[str, Any]) -> None: + """Missing, mistyped, non-finite or absurd values are never logged.""" + with pytest.raises(InvalidEstimateError): + parse_estimate(bad) + + +def test_non_object_is_refused() -> None: + """A list or string is not an estimate.""" + with pytest.raises(InvalidEstimateError): + parse_estimate([GOOD]) + + +def test_schema_requires_exactly_the_contract_fields() -> None: + """The JSON schema handed to the model names every required field.""" + assert set(SCHEMA["required"]) == { + "desc", + "grams", + "kcal", + "protein_g", + "carbs_g", + "fat_g", + } + assert SCHEMA["additionalProperties"] is False diff --git a/diet_guard/tests/test_claude_sdk.py b/diet_guard/tests/test_claude_sdk.py new file mode 100644 index 0000000..0e762a1 --- /dev/null +++ b/diet_guard/tests/test_claude_sdk.py @@ -0,0 +1,212 @@ +"""The model call and its sandbox, against a fake ``claude_agent_sdk``.""" + +from __future__ import annotations + +import asyncio +import json +import subprocess +from typing import TYPE_CHECKING, Any +from unittest.mock import AsyncMock, Mock, patch + +import pytest + +from diet_guard import _claude_sandbox as sandbox +from diet_guard import _claude_sdk as sdk +from diet_guard.tests._claude_fakes import ( + FakeResult, + FakeSdk, + fresh, + write_host_login, +) + +if TYPE_CHECKING: + from pathlib import Path + +FAR = 4_000_000_000_000 # an expiry far in the future, in ms + + +@pytest.fixture +def login() -> None: + """A readable host login that is not about to expire.""" + write_host_login(sandbox.HOST_LOGIN_FILE, FAR) + + +def _ask(fake: FakeSdk, budget_s: float = 5) -> dict[str, Any]: + content = [{"type": "text", "text": "banan"}] + with patch("diet_guard._claude_sdk.import_module", return_value=fake): + return asyncio.run( + sdk.bounded_ask("PROMPT", content, {"s": 1}, budget_s=budget_s) + ) + + +@pytest.mark.usefixtures("login") +def test_answer_and_isolation_options() -> None: + """The structured answer returns; the call is tool-less and sandboxed.""" + fake = FakeSdk([FakeResult({"kcal": 1})]) + assert _ask(fake) == {"kcal": 1} + options = fake.calls[0]["options"] + assert options.tools == [] + assert options.mcp_servers == {} + assert options.setting_sources == [] + assert options.system_prompt == "PROMPT" + assert options.output_format == {"type": "json_schema", "schema": {"s": 1}} + assert options.env["CLAUDE_CONFIG_DIR"] == str(sandbox.SANDBOX_DIR) + assert options.cwd == sandbox.SANDBOX_DIR / "work" + message = fake.calls[0]["sent"][0]["message"] + assert message["content"] == [{"type": "text", "text": "banan"}] + + +@pytest.mark.usefixtures("login") +@pytest.mark.parametrize( + "messages", + [ + [FakeResult(None, is_error=True)], + [FakeResult(None)], + [FakeResult(["not", "an", "object"])], + [], + ], +) +def test_no_usable_answer_is_a_model_error(messages: list[object]) -> None: + """An API error or an answer that is not an object fails closed.""" + with pytest.raises(sdk.ModelError): + _ask(FakeSdk(messages)) + + +def test_missing_login_is_a_model_error() -> None: + """No host login: nothing is sent to the model at all.""" + fake = FakeSdk([FakeResult({"kcal": 1})]) + with pytest.raises(sdk.ModelError, match="no Claude login"): + _ask(fake) + assert fake.calls == [] + + +@pytest.mark.usefixtures("login") +def test_a_hung_model_times_out() -> None: + """A call past its budget is a ModelTimeoutError.""" + with pytest.raises(sdk.ModelTimeoutError): + _ask(FakeSdk([], hang=True), budget_s=0.05) + + +@pytest.mark.usefixtures("login") +def test_any_other_failure_is_wrapped() -> None: + """A CLI/transport exception becomes a ModelError naming only its type.""" + fake = FakeSdk([]) + fake.query = Mock(side_effect=OSError("secret path")) + with pytest.raises(sdk.ModelError, match="OSError") as caught: + _ask(fake) + assert "secret path" not in str(caught.value) + + +def test_run_model_delegates_to_bounded_ask() -> None: + """The seam is a thin wrapper: same arguments, same result.""" + real = fresh(sdk) + with patch.object(real, "bounded_ask", AsyncMock(return_value={"ok": 1})) as ask: + out = asyncio.run(real.run_model("p", [], {}, budget_s=3)) + assert out == {"ok": 1} + ask.assert_awaited_once_with("p", [], {}, budget_s=3) + + +# -- the sandbox --------------------------------------------------------------- +def test_login_copy_drops_the_refresh_token_and_mcp_tokens(login: None) -> None: + """Only claudeAiOauth minus refreshToken reaches the sandbox, mode 0600.""" + assert sandbox.copy_login() == FAR + target = sandbox.SANDBOX_DIR / ".credentials.json" + text = target.read_text(encoding="utf-8") + assert "SECRET" not in text + assert json.loads(text) == { + "claudeAiOauth": {"accessToken": "tok", "expiresAt": FAR} + } + assert target.stat().st_mode & 0o777 == 0o600 + + +@pytest.mark.parametrize("raw", [None, "not json", "{}", '{"claudeAiOauth": 3}']) +def test_unreadable_host_login_copies_nothing(raw: str | None) -> None: + """A missing, broken or empty login writes nothing and reports None.""" + if raw is not None: + sandbox.HOST_LOGIN_FILE.write_text(raw, encoding="utf-8") + assert sandbox.copy_login() is None + assert not sandbox.SANDBOX_DIR.exists() + + +def test_expiry_missing_is_none_but_copied() -> None: + """A login without expiresAt is copied; its expiry is unknown.""" + sandbox.HOST_LOGIN_FILE.write_text( + json.dumps({"claudeAiOauth": {"accessToken": "t"}}), encoding="utf-8" + ) + assert sandbox.copy_login() is None + assert (sandbox.SANDBOX_DIR / ".credentials.json").is_file() + + +def test_prepare_installs_the_skill_and_work_dir(login: None) -> None: + """A fresh login: no refresh, skill copied, work dir ready.""" + refresh = Mock() + assert sandbox.prepare(refresh=refresh) == sandbox.SANDBOX_DIR + refresh.assert_not_called() + skill = sandbox.SANDBOX_DIR / "skills" / "diet-food" / "SKILL.md" + assert skill.read_text(encoding="utf-8").startswith("---\nname: diet-food") + assert (sandbox.SANDBOX_DIR / "work").is_dir() + + +def test_prepare_without_login_is_none() -> None: + """No host login: no sandbox.""" + assert sandbox.prepare() is None + + +def test_prepare_refreshes_an_expiring_login_then_recopies() -> None: + """Within the margin the host CLI refreshes first; the new token is copied.""" + write_host_login(sandbox.HOST_LOGIN_FILE, 1_000) + refresh = Mock(side_effect=lambda: write_host_login(sandbox.HOST_LOGIN_FILE, FAR)) + assert sandbox.prepare(now=lambda: 1.0, refresh=refresh) == sandbox.SANDBOX_DIR + refresh.assert_called_once_with() + fresh_login = json.loads((sandbox.SANDBOX_DIR / ".credentials.json").read_text()) + assert fresh_login["claudeAiOauth"]["expiresAt"] == FAR + + +def test_failed_refresh_is_logged_and_the_old_copy_stays() -> None: + """A refresh that fails does not raise; the call then fails in the CLI.""" + write_host_login(sandbox.HOST_LOGIN_FILE, 1_000) + refresh = Mock(side_effect=subprocess.SubprocessError("nope")) + assert sandbox.prepare(now=lambda: 1.0, refresh=refresh) == sandbox.SANDBOX_DIR + + +def test_refresh_host_login_runs_the_host_cli_with_nothing_loaded() -> None: + """The refresh is one tiny, tool-less, settings-less CLI call.""" + with ( + patch( + "diet_guard._claude_sandbox.host_cli", + return_value=sandbox.Path("/x/claude"), + ), + patch("diet_guard._claude_sandbox.subprocess.run") as run, + ): + sandbox.refresh_host_login() + cmd = run.call_args.args[0] + assert cmd[0] == "/x/claude" + assert "--setting-sources=" in cmd + assert "--tools=" in cmd + assert run.call_args.kwargs["cwd"] == sandbox.SANDBOX_DIR / "refresh" + + +def test_refresh_without_a_host_cli_is_a_noop() -> None: + """No claude binary on PATH: nothing to refresh with, nothing raised.""" + with ( + patch("diet_guard._claude_sandbox.host_cli", return_value=None), + patch("diet_guard._claude_sandbox.subprocess.run") as run, + ): + sandbox.refresh_host_login() + run.assert_not_called() + + +def test_host_cli_follows_path() -> None: + """host_cli is whatever ``claude`` resolves to, or None.""" + with patch("diet_guard._claude_sandbox.shutil.which", return_value="/bin/claude"): + assert str(sandbox.host_cli()) == "/bin/claude" + with patch("diet_guard._claude_sandbox.shutil.which", return_value=None): + assert sandbox.host_cli() is None + + +def test_skill_text_without_front_matter(tmp_path: Path) -> None: + """A skill file with no front matter is returned whole.""" + skill = tmp_path / "SKILL.md" + skill.write_text("body only\n", encoding="utf-8") + with patch("diet_guard._claude_sandbox.SKILL_DIR", tmp_path): + assert sandbox.skill_text() == "body only" diff --git a/skills/diet-food/SKILL.md b/skills/diet-food/SKILL.md new file mode 100644 index 0000000..7ea54b5 --- /dev/null +++ b/skills/diet-food/SKILL.md @@ -0,0 +1,60 @@ +--- +name: diet-food +description: Estimate what one meal weighed and how many kcal and macros it had, from a photo and/or a short description, and answer with one strict JSON object. Used by diet_guard's "send to Claude" worker. +--- + +# diet-food + +You are the estimator inside kuhy's calorie log. One request, one meal, one +JSON object back. Nothing else: no greeting, no questions, no markdown. + +## Input + +The user message holds any of: + +- the meal as typed (often Polish, often terse: "2 jajka sadzone i kromka + chleba"); +- a photo of the plate or the package; +- a table of foods kuhy logged before (name, grams, kcal, protein, carbs, + fat per logged portion). + +## How to estimate + +1. Name every distinct item you can see or read, and the portion of each. + Count units when the text does (2 eggs, 3 slices). Judge size from the + plate, the cutlery or the package when there is a photo. +2. **Look the food bank up first.** If an item matches a table row (same food, + close name, Polish or English), scale that row to the portion eaten + (kcal and macros are linear in grams) instead of guessing. kuhy's own + numbers beat generic ones. +3. Estimate the rest from typical values for the food as prepared (frying + oil, sauces and dressings included: they are most of the hidden kcal). +4. Package or label visible: read the per-100 g values and use them. +5. Sum the items. Round grams to 5, kcal to 5, macros to 0.5. +6. Never refuse and never ask a question. A vague meal still gets the best + single estimate; a photo with no food in it gets a small guess from the + text, or `grams` 100 and `kcal` 100 only if there is no text at all. + +## Output + +Exactly one JSON object, matching the schema the caller enforces: + +``` +{"desc": "owsianka z bananem i orzechami", + "grams": 330, "kcal": 520, "protein_g": 16, "carbs_g": 72, "fat_g": 18, + "components": [ + {"name": "owsianka na mleku", "grams": 250, "kcal": 290, "protein_g": 10, + "carbs_g": 40, "fat_g": 9}, + {"name": "banan", "grams": 60, "kcal": 55, "protein_g": 1, + "carbs_g": 14, "fat_g": 0.5}, + {"name": "orzechy wloskie", "grams": 20, "kcal": 130, "protein_g": 3, + "carbs_g": 3, "fat_g": 13}]} +``` + +- `desc`: a short name for the whole meal in the language kuhy wrote in + (Polish by default), at most 120 characters. +- `grams`: the total edible weight, greater than 0. +- `kcal`, `protein_g`, `carbs_g`, `fat_g`: totals for the whole portion, never + negative. kcal should be close to 4 x protein + 4 x carbs + 9 x fat. +- `components`: optional, one entry per item with the same five numbers; they + must add up to the totals. Leave it out for a single-item meal.