Add the Claude relay worker

python -m diet_guard claude-worker serves the phone's meal requests from
RTDB (rtdb_relay RequestServer, one SSE stream, reconnects with backoff):
validate, estimate with Claude, log through the signed log with
source=claude under the oldest due slot (normal mode: nearest slot of the
phone's hint), write the sealed result, delete only the request payload,
then publish in the background. diet-guard-claude.service (Restart=on-failure,
WantedBy=default.target) is installed by install.sh and started once the
worker's own Firebase session exists. Nothing is deployed by this commit.

Failure paths:
- narrow peer pull fails (sync locked/unreachable): fail closed, no claim, no
  answer, no model call; the request stays pending, retried every 30 s
- e2e key locked, no passphrase, no session: fail closed, nothing read or
  written; the worker waits and retries every 60 s
- bad body, request older than 24 h (or no created): fail closed, an error
  result, nothing logged
- Claude failure/timeout/invalid JSON: fail closed, an error result with
  retry, nothing logged
- crash between log and result, or a duplicate event: idempotent, the entry
  id is uuid5 of the rid and is looked up (tombstones included) before the
  model call
- request payload delete, old-answer cleanup and the post-answer publish
  failing: fail open on purpose (logged only); the answer and the local
  entry are already durable
- due mode with nothing due: falls back to slot_for_log, not an error

New log helpers log_meal_as / find_entry; log_meal's body is split into
_entry_fields / _store_entry with the same output. The gate and CLI import
none of the worker's dependencies at load time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:15:08 +01:00
parent 6cd3470502
commit 642467dc1d
26 changed files with 1559 additions and 23 deletions

View File

@ -29,7 +29,7 @@ repos:
args: [--pytest-test-first]
# Shared fakes and fixtures, not test modules. Split out of conftest.py
# and test_sync.py only because those files passed the 250-line cap.
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes)\.py$
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]

View File

@ -15,6 +15,7 @@ show adherence, streaks, a YTD tally and weekly/monthly averages, all derived fr
- One sync tick: `python -m diet_guard sync`
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
- Phone's "send to Claude" worker: `python -m diet_guard claude-worker`, [docs/DOCS-claude-relay.md](docs/DOCS-claude-relay.md)
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
- run: `python -m diet_guard gate --demo`
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`

View File

@ -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.167+1
version: 1.0.168+1
environment:
sdk: ^3.12.2

20
diet-guard-claude.service Normal file
View File

@ -0,0 +1,20 @@
[Unit]
Description=Diet Guard "send to Claude" relay worker (phone meal requests)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# Event-driven: one RTDB stream does the waiting, so a PC that was off simply
# serves the queued requests when this starts. Headless: no DISPLAY, unlike
# the gate. No PYTHONPATH: diet_guard (and claude_agent_sdk, rtdb_relay,
# httpx) are pip-installed into system Python's user site-packages by
# install.sh, which is what /usr/bin/python resolves.
ExecStart=/usr/bin/python -m diet_guard claude-worker
# A cancelled stream (the rules refuse the path) exits 1; an unconfigured or
# locked relay does not exit at all, it waits and retries (docs/DOCS-claude-relay.md).
Restart=on-failure
RestartSec=10
[Install]
WantedBy=default.target

View File

@ -0,0 +1,123 @@
"""The relay contract's pure parts: body validation, ids, result shapes.
Stdlib only. ``docs/DOCS-claude-relay.md`` is the prose; the shared fixture
``tests/fixtures/claude_relay_contract.json`` drives both this validator and
the phone's, so they cannot drift.
"""
from __future__ import annotations
import base64
import binascii
from dataclasses import dataclass
from typing import Final, Literal
import uuid
TEXT_MAX: Final = 2000
PHOTO_B64_MAX: Final = 600_000
SLOT_MAX: Final = 1439
EXPIRY_MS: Final = 24 * 60 * 60 * 1000
#: Codes the handler raises (``docs/DOCS-claude-relay.md`` section 3).
BAD_REQUEST: Final = "bad_request"
EXPIRED: Final = "expired"
#: A fixed namespace: the same rid always maps to the same entry id.
_ENTRY_NAMESPACE: Final = uuid.UUID("5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4")
_JPEG_MAGIC: Final = b"\xff\xd8"
Mode = Literal["due", "normal"]
class BadRequestError(ValueError):
"""The request body breaks the contract."""
@dataclass(frozen=True)
class MealRequest:
"""A validated request body.
Attributes:
text: The typed meal, trimmed, or None.
photo: The decoded JPEG bytes, or None.
client_slot_min: The slot the phone would use; a hint in due mode.
mode: ``"due"`` (oldest due slot) or ``"normal"`` (nearest slot).
"""
text: str | None
photo: bytes | None
client_slot_min: int
mode: Mode
def entry_id_for(rid: str) -> str:
"""The log entry id of request ``rid``: a uuid5, so replays find it."""
return str(uuid.uuid5(_ENTRY_NAMESPACE, rid))
def _photo(value: object) -> bytes | None:
"""The decoded JPEG, None when absent."""
if value is None:
return None
if not isinstance(value, str) or len(value) > PHOTO_B64_MAX:
msg = "photo_jpeg_b64 is not a base64 string within the size cap"
raise BadRequestError(msg)
try:
data = base64.b64decode(value, validate=True)
except binascii.Error as err:
msg = "photo_jpeg_b64 is not valid base64"
raise BadRequestError(msg) from err
if not data.startswith(_JPEG_MAGIC):
msg = "photo_jpeg_b64 is not a JPEG"
raise BadRequestError(msg)
return data
def _text(value: object) -> str | None:
"""The trimmed text, None when absent."""
if value is None:
return None
if not isinstance(value, str):
msg = "text is not a string"
raise BadRequestError(msg)
trimmed = value.strip()
if not trimmed or len(trimmed) > TEXT_MAX:
msg = f"text must be 1..{TEXT_MAX} characters"
raise BadRequestError(msg)
return trimmed
def parse_body(body: dict[str, object]) -> MealRequest:
"""Validate a request body.
Raises:
BadRequestError: any field breaks the contract, or there is neither
text nor photo to estimate.
"""
text = _text(body.get("text"))
photo = _photo(body.get("photo_jpeg_b64"))
if text is None and photo is None:
msg = "neither text nor photo"
raise BadRequestError(msg)
slot = body.get("client_slot_min")
if isinstance(slot, bool) or not isinstance(slot, int) or not 0 <= slot <= SLOT_MAX:
msg = f"client_slot_min must be an int in 0..{SLOT_MAX}"
raise BadRequestError(msg)
mode = body.get("mode")
if mode == "due":
return MealRequest(text, photo, slot, "due")
if mode == "normal":
return MealRequest(text, photo, slot, "normal")
msg = "mode must be 'due' or 'normal'"
raise BadRequestError(msg)
def is_expired(created_ms: object, now_ms: float) -> bool:
"""Whether a request created at ``created_ms`` is older than 24 h.
A missing or non-numeric ``created`` counts as expired: the request has no
server timestamp, so it cannot be trusted to be fresh (fail closed).
"""
if isinstance(created_ms, bool) or not isinstance(created_ms, (int, float)):
return True
return now_ms - created_ms > EXPIRY_MS

90
diet_guard/_claude_log.py Normal file
View File

@ -0,0 +1,90 @@
"""Turning an estimate into one logged entry: slot, write, result data.
The slot rule (``docs/DOCS-claude-relay.md`` section 4) only *calls*
``_slots`` and ``_gate``; no slot arithmetic lives here.
* ``"due"``: the oldest elapsed-but-unlogged slot of today; with nothing due
(already logged elsewhere, free or sick day, hold, outside the enforcement
window) the ordinary ``slot_for_log`` rule, never an error.
* ``"normal"``: ``nearest_slot`` of the phone's ``client_slot_min``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._claude_contract import entry_id_for
from diet_guard._estimator import Nutrition
from diet_guard._gate import due_slots
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slot_wire import entry_slot_minute
from diet_guard._slots import nearest_slot, slot_for_log
from diet_guard._state_sync import find_entry, log_meal_as
if TYPE_CHECKING:
from datetime import datetime
from diet_guard._claude_contract import MealRequest
from diet_guard._claude_schema import Estimate
#: ``Nutrition.source`` and so the entry's ``source`` field.
SOURCE = "claude"
def resolve_slot(request: MealRequest, now: datetime) -> int:
"""The slot minute this request's meal is logged under."""
if request.mode == "due":
due = due_slots(now)
return due[0] if due else slot_for_log(now, current_schedule())
return nearest_slot(request.client_slot_min, current_schedule())
def result_data(entry: dict[str, object]) -> dict[str, object]:
"""The ``logged`` result fields of a stored entry."""
slot = entry_slot_minute(entry)
return {
"entry_id": entry["id"],
"desc": entry["desc"],
"grams": entry["grams"],
"kcal": entry["kcal"],
"protein_g": entry["protein_g"],
"carbs_g": entry["carbs_g"],
"fat_g": entry["fat_g"],
"slot_min": slot,
"time": entry["time"],
}
def already_logged(rid: str) -> dict[str, object] | None:
"""The result data of ``rid``'s entry if it was logged before, else None."""
entry = find_entry(entry_id_for(rid))
return result_data(entry) if entry is not None else None
def log_estimate(
rid: str, estimate: Estimate, request: MealRequest, now: datetime
) -> dict[str, object]:
"""Log ``estimate`` for request ``rid`` and return its result data.
Idempotent: the entry id is derived from ``rid``, and an entry that
already carries it is returned untouched instead of logged again.
"""
if (existing := already_logged(rid)) is not None:
return existing
nutrition = Nutrition(
kcal=estimate.kcal,
protein_g=estimate.protein_g,
carbs_g=estimate.carbs_g,
fat_g=estimate.fat_g,
grams=estimate.grams,
source=SOURCE,
)
components = [dict(item) for item in estimate.components or ()] or None
entry = log_meal_as(
entry_id_for(rid),
estimate.desc,
nutrition,
resolve_slot(request, now),
components=components,
)
return result_data(entry)

View File

@ -0,0 +1,57 @@
"""``python -m diet_guard claude-worker``: connect, serve, never idle-poll.
One SSE stream on ``requests`` does the waiting (``rtdb_relay.sse`` reconnects
forever with backoff). The only timers are fault retries: an unconfigured or
locked relay (no session, no passphrase, wrong key) writes nothing and is
tried again every :data:`RETRY_S`.
"""
from __future__ import annotations
import asyncio
import logging
from typing import TYPE_CHECKING, Final
from rtdb_relay.sse import StreamCancelledError
from diet_guard import _claude_connect, _device
from diet_guard._claude_worker import MealHandler, MealServer
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
RETRY_S: Final = 60.0
_logger = logging.getLogger(__name__)
async def serve(
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
) -> None:
"""Connect and serve until cancelled; a setup failure waits and retries."""
worker = f"claude-{_device.device_id()}"
while True:
try:
rtdb = await _claude_connect.connect_sealed()
except _claude_connect.RelaySetupError as err:
_logger.warning("relay not started, nothing written: %s", err)
await sleep(RETRY_S)
continue
try:
await MealServer(rtdb, worker, MealHandler()).run()
finally:
await rtdb.aclose()
def main() -> int:
"""Run the worker; 0 on Ctrl-C, 1 when RTDB cancelled the stream."""
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
try:
asyncio.run(serve())
except KeyboardInterrupt:
return 0
except StreamCancelledError:
_logger.exception("the rules refuse the relay path")
return 1
return 0

View File

@ -0,0 +1,208 @@
"""Serving meal requests: validate, estimate, log, answer, then publish.
``MealServer`` is ``rtdb_relay``'s ``RequestServer`` with the four things this
relay adds on top (``docs/DOCS-claude-relay.md`` section 5):
* a narrow peer pull before a request is claimed; a failed pull leaves the
request pending (no claim, no answer, no model cost) and retries later;
* the request's id and server ``created`` time reach the handler;
* ``req`` (the photo) is deleted once the result is written; the node keeps
``claim`` and ``result`` until the phone deletes it or 24 h pass;
* the full sync tick runs *after* the answer, in the background.
``MealHandler`` is the handler for kind ``meal``.
"""
from __future__ import annotations
import asyncio
import logging
import time
from typing import TYPE_CHECKING, Any, Final
from rtdb_relay import mirror, sse
from rtdb_relay.lease import ms, valid_rid
from rtdb_relay.rtdb import RtdbError
from rtdb_relay.server import RequestError, RequestServer
from diet_guard import _claude_sync
from diet_guard._claude_contract import (
BAD_REQUEST,
EXPIRED,
EXPIRY_MS,
BadRequestError,
is_expired,
parse_body,
)
from diet_guard._claude_estimate import EstimateError, estimate_meal_async
from diet_guard._claude_layout import KIND
from diet_guard._claude_log import already_logged, log_estimate
from diet_guard._state import now_local
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
from datetime import datetime
from rtdb_relay.lease import Lease
from rtdb_relay.rtdb import Rtdb
from diet_guard._claude_schema import Estimate
type Estimator = Callable[[str | None, bytes | None], Awaitable[Estimate]]
#: Seconds before a request left pending by a failed pull is tried again.
RETRY_S: Final = 30.0
_logger = logging.getLogger(__name__)
class MealHandler:
"""The handler of kind ``meal``: body in, ``logged`` result data out."""
def __init__(
self,
estimate: Estimator = estimate_meal_async,
now: Callable[[], datetime] = now_local,
clock: Callable[[], float] = time.time,
) -> None:
"""Estimate with ``estimate``; ``now`` stamps the entry, ``clock`` ages it."""
self._estimate = estimate
self._now = now
self._clock = clock
# Two requests must not take the same due slot.
self._log_lock = asyncio.Lock()
async def handle(self, body: dict[str, Any]) -> dict[str, Any]:
"""Serve one request body (``rid`` and ``created`` injected by the server)."""
rid = str(body.get("rid"))
if (done := await asyncio.to_thread(already_logged, rid)) is not None:
_logger.info("request %s was logged before: answering from the log", rid)
return done
if is_expired(body.get("created"), self._clock() * 1000):
raise RequestError(EXPIRED, "request older than 24 h")
try:
request = parse_body(body)
except BadRequestError as err:
raise RequestError(BAD_REQUEST, str(err)) from err
try:
estimate = await self._estimate(request.text, request.photo)
except EstimateError as err:
raise RequestError(err.code, str(err), retry=True) from err
async with self._log_lock:
return await asyncio.to_thread(
log_estimate, rid, estimate, request, self._now()
)
class MealServer(RequestServer):
"""``RequestServer`` plus the pull, the cleanup and the late publish."""
def __init__(
self,
rtdb: Rtdb,
worker: str,
handler: MealHandler,
now: Callable[[], float] = time.time,
) -> None:
"""Serve kind ``meal`` with ``handler`` as ``worker``."""
super().__init__(rtdb, worker, {KIND: handler.handle}, now)
# Replaceable (tests): the pause before a pending request is retried.
self._sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
self.tree: dict[str, Any] = {}
self._retry: asyncio.Task[None] | None = None
self._collecting: set[str] = set()
self._publish_lock = asyncio.Lock()
async def answer(self, rid: str, node: dict[str, Any]) -> dict[str, Any] | None:
"""Pull, serve, then clean up and publish; None when not ours to answer."""
if not valid_rid(rid) or "result" in node or "req" not in node:
return None
if (reason := await asyncio.to_thread(_claude_sync.pull_peers)) is not None:
_logger.warning("not serving %s, request stays pending: %s", rid, reason)
self._retry_later()
return None
result = await super().answer(rid, node)
if result is not None:
await self._drop_request(rid)
self._start(self._publish())
return result
async def _run(
self, lease: Lease, kind: str, req: dict[str, Any]
) -> dict[str, Any]:
"""Hand the handler the rid and the server's ``created``; add ``status``."""
body = req.get("body")
body = body if isinstance(body, dict) else {}
enriched = {
**req,
"body": {**body, "rid": lease.rid, "created": req.get("created")},
}
result = await super()._run(lease, kind, enriched)
if result.get("ok"):
return {**result, "status": "logged", "id": lease.rid}
return {
**result,
"status": "error",
"id": lease.rid,
"error_code": result.get("code"),
}
async def _drop_request(self, rid: str) -> None:
"""Delete ``req`` (the photo): useless once the result is out."""
try:
await self.rtdb.delete(f"requests/{rid}/req")
except RtdbError as err:
_logger.warning("could not delete the request payload of %s: %s", rid, err)
async def _publish(self) -> None:
"""The full sync tick, after the answer; an outage is only logged."""
async with self._publish_lock:
reason = await asyncio.to_thread(_claude_sync.publish)
if reason is not None:
_logger.warning("post-answer sync skipped: %s", reason)
def _start(self, work: Awaitable[None]) -> None:
"""Run ``work`` in the background, remembered so it is not collected."""
task = asyncio.ensure_future(work)
self.tasks.add(task)
task.add_done_callback(self.tasks.discard)
def _retry_later(self) -> None:
"""Try the pending requests again in :data:`RETRY_S` (one timer at most)."""
if self._retry is None or self._retry.done():
self._retry = asyncio.ensure_future(self._retry_after())
async def _retry_after(self) -> None:
await self._sleep(RETRY_S)
self.dispatch(self.tree)
def dispatch(self, tree: dict[str, Any]) -> None:
"""Serve what is pending, and drop answers older than 24 h."""
super().dispatch(tree)
cutoff = ms(self._now()) - EXPIRY_MS
for rid, node in tree.items():
result = node.get("result") if isinstance(node, dict) else None
at = result.get("at") if isinstance(result, dict) else None
old = (
isinstance(at, (int, float))
and not isinstance(at, bool)
and at < cutoff
)
if old and valid_rid(rid) and rid not in self._collecting:
self._collecting.add(rid)
self._start(self._collect(rid))
async def _collect(self, rid: str) -> None:
"""Delete one answered request node (a failure is retried next event)."""
try:
await self.rtdb.delete(f"requests/{rid}")
except RtdbError as err:
_logger.warning("could not delete the old request %s: %s", rid, err)
finally:
self._collecting.discard(rid)
async def run(self) -> None:
"""Watch ``requests`` (raw, so sealing is checked) until cancelled."""
self.tree = {}
async for event in sse.listen(self._raw, "requests"):
self.tree = mirror.apply(self.tree, event)
self.dispatch(self.tree)

View File

@ -34,6 +34,7 @@ from diet_guard._cli_body import (
cmd_profile,
cmd_weight,
)
from diet_guard._cli_claude import cmd_claude_worker
from diet_guard._cli_gate import cmd_gate
from diet_guard._cli_init import cmd_init
from diet_guard._cli_kuchnia import cmd_kuchnia
@ -225,6 +226,7 @@ _COMMANDS: dict[str, Callable[[argparse.Namespace], int]] = {
"sync": lambda _args: cmd_sync(_emit),
"kuchnia": _dispatch_kuchnia,
"prune-peers": _dispatch_prune,
"claude-worker": lambda _args: cmd_claude_worker(),
"gate": _dispatch_gate,
"undo": lambda _args: _cmd_undo(),
"body": lambda args: cmd_body(_emit, args),

View File

@ -16,6 +16,7 @@ import argparse
from diet_guard._cli_averages import register_averages_subparser
from diet_guard._cli_body import register_body_subparsers
from diet_guard._cli_claude import register_claude_subparser
from diet_guard._cli_kuchnia import register_kuchnia_subparser
from diet_guard._cli_prune import register_prune_subparser
from diet_guard._cli_sync import register_sync_subparser
@ -98,6 +99,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
register_averages_subparser(sub)
register_kuchnia_subparser(sub)
register_prune_subparser(sub)
register_claude_subparser(sub)
register_sync_subparser(sub)
register_body_subparsers(sub)

29
diet_guard/_cli_claude.py Normal file
View File

@ -0,0 +1,29 @@
"""CLI handler for the ``claude-worker`` subcommand.
The relay worker needs ``claude_agent_sdk``, ``rtdb_relay`` and ``httpx``,
which system Python only gains after the install step. Importing the worker
here would make every command (the gate included) fail at load time on a
machine that has not run it -- the 2026-06-19 outage shape -- so the worker
module is imported only when this subcommand actually runs.
"""
from __future__ import annotations
from importlib import import_module
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import argparse
def register_claude_subparser(sub: argparse._SubParsersAction) -> None:
"""Register the ``claude-worker`` subcommand on ``sub``."""
sub.add_parser(
"claude-worker",
help="Serve the phone's 'send to Claude' meal requests (long-running).",
)
def cmd_claude_worker() -> int:
"""Run the relay worker until it is stopped; its exit code."""
return import_module("diet_guard._claude_relay").main()

View File

@ -166,10 +166,18 @@ def log_meal(
if when is not None and when < now_local():
msg = "cannot log a meal in the past"
raise ValueError(msg)
effective = when or now_local()
entry: dict[str, object] = {
"id": str(uuid.uuid4()),
"time": effective.isoformat(timespec="seconds"),
fields = _entry_fields(description, nutrition, slot, components)
return _store_entry(str(uuid.uuid4()), when or now_local(), fields)
def _entry_fields(
description: str,
nutrition: Nutrition,
slot: int | None,
components: list[dict[str, object]] | None,
) -> dict[str, object]:
"""The entry's content fields: everything except its id and time."""
fields: dict[str, object] = {
"desc": description,
"grams": nutrition.grams,
"kcal": nutrition.kcal,
@ -181,9 +189,21 @@ def log_meal(
if slot is not None:
# Before signing: the HMAC covers the whole dict, so a ``slot_min``
# added afterwards would make the entry fail verification and vanish.
entry.update(slot_fields(slot))
fields.update(slot_fields(slot))
if components is not None:
entry["components"] = list(components)
fields["components"] = list(components)
return fields
def _store_entry(
entry_id: str, effective: datetime, fields: dict[str, object]
) -> dict[str, object]:
"""Sign and append one entry under ``effective``'s day; return it."""
entry: dict[str, object] = {
"id": entry_id,
"time": effective.isoformat(timespec="seconds"),
**fields,
}
signature = compute_entry_hmac(entry)
if signature is not None:
entry["hmac"] = signature

View File

@ -19,12 +19,22 @@ from typing import TYPE_CHECKING
from gatelock.log_integrity import compute_entry_hmac
from diet_guard._state import _read_raw_log, _today, _write_log
from diet_guard._state import (
_entry_fields,
_read_raw_log,
_store_entry,
_today,
_write_log,
now_local,
)
if TYPE_CHECKING:
from diet_guard._estimator import Nutrition
from diet_guard._state import DayLog
__all__ = [
"find_entry",
"log_meal_as",
"read_raw_log",
"resign_entry",
"undo_last_today",
@ -109,3 +119,34 @@ def undo_last_today() -> dict[str, object] | None:
_write_log(log)
return entry
return None
def find_entry(entry_id: str) -> dict[str, object] | None:
"""The stored entry with ``entry_id``, tombstones and unverified included.
A deleted entry still counts as logged: a replayed request must not log
its meal a second time because the user undid the first.
"""
for entries in _read_raw_log().values():
for entry in entries:
if entry.get("id") == entry_id:
return entry
return None
def log_meal_as(
entry_id: str,
description: str,
nutrition: Nutrition,
slot: int | None,
*,
components: list[dict[str, object]] | None = None,
) -> dict[str, object]:
""":func:`~diet_guard._state.log_meal` for now, under a caller-chosen id.
The Claude relay derives the id from the request id, so a replayed
request finds its own entry with :func:`find_entry` instead of logging
twice.
"""
fields = _entry_fields(description, nutrition, slot, components)
return _store_entry(entry_id, now_local(), fields)

View File

@ -0,0 +1,97 @@
"""Shared setup for the meal-server tests: one request, one in-memory RTDB.
The RTDB is ``rtdb_relay``'s own fake. It is rooted at the tutor's layout,
which has the same ``requests/*/req | claim | result`` rules as this relay's,
so the server logic runs against realistic sealing, ETags and SSE; the real
layout is pinned separately by ``test_claude_relay_contract.py``.
"""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from unittest.mock import AsyncMock
from rtdb_relay.tests._fake_rtdb import ROOT, FakeRtdb
from diet_guard._claude_schema import Estimate
from diet_guard._claude_worker import MealHandler, MealServer
from diet_guard._state import load_log
if TYPE_CHECKING:
from rtdb_relay.rtdb import Rtdb
__all__ = ["ROOT", "FakeRtdb"]
RID = "01J0000000000000000000000R"
RID2 = "01J0000000000000000000000S"
NOW_S = 1_800_000_000.0
NOW_MS = int(NOW_S * 1000)
DAY_MS = 24 * 3600 * 1000
NOON = datetime(2026, 11, 17, 12, 30, tzinfo=UTC)
EST = Estimate("2 jajka", 190.0, 410.0, 17.5, 22.0, 26.0, None)
BODY: dict[str, Any] = {"text": "2 jajka", "client_slot_min": 720, "mode": "normal"}
def put(fake: FakeRtdb, rid: str, body: dict[str, Any], age_ms: int = 0) -> None:
"""A phone writes one request."""
req = {
"kind": "meal",
"dev": "d",
"created": NOW_MS - age_ms,
"sent_at": 1,
"body": body,
}
fake.set(f"{ROOT}/requests/{rid}/req", req)
def request_fake(
body: dict[str, Any] | None = None, rid: str = RID, age_ms: int = 0
) -> FakeRtdb:
"""A database holding one pending request."""
fake = FakeRtdb(now_ms=NOW_MS)
put(fake, rid, BODY if body is None else body, age_ms)
return fake
def estimator(result: object = EST) -> AsyncMock:
"""A fake model: returns ``result``, or raises it when it is an exception."""
if isinstance(result, Exception):
return AsyncMock(side_effect=result)
return AsyncMock(return_value=result)
def new_server(db: Rtdb, estimate: AsyncMock | None = None) -> MealServer:
"""A server on ``db`` with a fixed clock and an instant retry pause."""
handler = MealHandler(
estimate or estimator(), now=lambda: NOON, clock=lambda: NOW_S
)
server = MealServer(db, "pc", handler, now=lambda: NOW_S)
server._sleep = AsyncMock()
return server
def serve_once(
fake: FakeRtdb, estimate: AsyncMock, rid: str = RID
) -> tuple[MealServer, dict[str, Any] | None]:
"""Answer ``rid`` once and let its background work finish."""
box: list[MealServer] = []
async def go() -> dict[str, Any] | None:
db = fake.rtdb()
server = new_server(db, estimate)
box.append(server)
node = await server._raw.get(f"requests/{rid}")
out = await server.answer(rid, node if isinstance(node, dict) else {})
await asyncio.gather(*server.tasks)
await db.aclose()
return out
result = asyncio.run(go())
return box[0], result
def entries() -> list[dict[str, Any]]:
"""Every live entry of the (redirected) food log."""
return [e for day in load_log().values() for e in day]

View File

@ -126,3 +126,17 @@ def test_bank_rows_empty_bank_is_empty() -> None:
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"]
def test_bank_rows_reach_the_prompt() -> None:
"""A banked food is offered to the model as a row it can scale."""
banana = Nutrition(
kcal=105, protein_g=1.3, carbs_g=27, fat_g=0.4, grams=118, source="m"
)
remember_food("banan", banana)
model = _fake()
with patch("diet_guard._claude_sdk.run_model", model):
estimate_meal("banan", None)
text = model.await_args.args[1][0]["text"]
assert "Food bank" in text
assert "banan | 118 g | 105 kcal" in text

View File

@ -0,0 +1,98 @@
"""Slot choice and the idempotent write of one Claude meal."""
from __future__ import annotations
from datetime import UTC, datetime
from unittest.mock import patch
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from diet_guard._claude_contract import MealRequest, Mode, entry_id_for
from diet_guard._claude_log import already_logged, log_estimate, resolve_slot
from diet_guard._claude_schema import Estimate
from diet_guard._slot_wire import entry_slot_minute
from diet_guard._state import load_log
EST = Estimate("2 jajka", 190.0, 410.0, 17.5, 22.0, 26.0, None)
NOON = datetime(2026, 11, 17, 12, 30, tzinfo=UTC)
def _request(mode: Mode = "due", slot: int = 480, text: str = "x") -> MealRequest:
return MealRequest(text, None, slot, mode)
def test_due_mode_takes_the_oldest_due_slot_and_ignores_the_hint() -> None:
"""Two slots due: the older one, whatever the phone says."""
with patch("diet_guard._claude_log.due_slots", return_value=(480, 720)):
assert resolve_slot(_request("due", slot=1200), NOON) == 480
def test_due_mode_with_nothing_due_falls_back_to_slot_for_log() -> None:
"""Nothing due is not an error: the ordinary now-rule decides."""
with patch("diet_guard._claude_log.due_slots", return_value=()):
assert resolve_slot(_request("due", slot=1200), NOON) == 720
def test_normal_mode_snaps_the_hint_to_the_nearest_slot() -> None:
"""A hint of 11:50 lands on the 12:00 slot, ignoring the due list."""
with patch("diet_guard._claude_log.due_slots", return_value=(480,)) as due:
assert resolve_slot(_request("normal", slot=710), NOON) == 720
due.assert_not_called()
def test_log_estimate_writes_one_signed_claude_entry() -> None:
"""The entry carries the derived id, the estimate, the slot and the source."""
with patch("diet_guard._claude_log.due_slots", return_value=(720,)):
data = log_estimate("RID1", EST, _request(), NOON)
assert data["entry_id"] == entry_id_for("RID1")
assert (data["kcal"], data["slot_min"], data["desc"]) == (410.0, 720, "2 jajka")
(entry,) = next(iter(load_log().values()))
assert entry["source"] == "claude"
assert entry_slot_minute(entry) == 720
assert "components" not in entry
def test_components_are_carried_onto_the_entry() -> None:
"""A composite estimate keeps its per-item numbers on the entry."""
part = {"name": "jajko", "grams": 60.0, "kcal": 90.0, "protein_g": 6.0}
est = Estimate(
"x", 60.0, 90.0, 6.0, 0.5, 7.0, ({**part, "carbs_g": 0.5, "fat_g": 7.0},)
)
log_estimate("RID2", est, _request("normal"), NOON)
(entry,) = next(iter(load_log().values()))
assert [c["name"] for c in entry["components"]] == ["jajko"]
def test_replay_returns_the_existing_entry_without_logging_again() -> None:
"""The same rid twice: one entry, the second call echoes the first."""
first = log_estimate("RID3", EST, _request("normal"), NOON)
second = log_estimate("RID3", EST, _request("normal"), NOON)
assert second == first
assert sum(len(day) for day in load_log().values()) == 1
assert already_logged("RID3") == first
assert already_logged("never") is None
def test_property_each_rid_yields_exactly_one_entry() -> None:
"""Any replay order of any rids: one entry per distinct rid, never more.
The log persists across hypothesis examples (one test, one tmp dir), so
the expectation accumulates the rids seen so far.
"""
seen: set[str] = set()
@settings(
max_examples=40,
deadline=None,
suppress_health_check=[HealthCheck.function_scoped_fixture],
)
@given(rids=st.lists(st.sampled_from("ABCDEF"), min_size=1, max_size=12))
def replay(rids: list[str]) -> None:
for rid in rids:
log_estimate(rid, EST, _request("normal"), NOON)
seen.update(rids)
ids = {str(e["id"]) for day in load_log().values() for e in day}
assert ids == {entry_id_for(rid) for rid in seen}
replay()

View File

@ -0,0 +1,204 @@
"""Connecting, unlocking, the serve loop and the CLI entry of the relay worker."""
from __future__ import annotations
import asyncio
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, Mock, patch
from crdt_sync import ConfigError, FirebaseAuthError
import pytest
from rtdb_relay.rtdb import RtdbError
from rtdb_relay.sse import StreamCancelledError
from rtdb_relay.tests._fake_rtdb import FakeRtdb
from diet_guard import _claude_connect as connect_mod
from diet_guard import _claude_relay as relay
from diet_guard import _claude_sync, _sync_e2e
from diet_guard._claude_layout import LAYOUT, ROOT
from diet_guard._cli import main as cli_main
from diet_guard.tests._claude_fakes import fresh
if TYPE_CHECKING:
from pathlib import Path
CONFIG = SimpleNamespace(api_key="key", database_url="https://db.test")
def _provider(*, session: bool = True, token: str | Exception = "tok") -> Mock:
provider = Mock()
provider.has_session.return_value = session
if isinstance(token, Exception):
provider.id_token.side_effect = token
else:
provider.id_token.return_value = token
return provider
# -- connect --------------------------------------------------------------------
def test_connect_builds_a_client_rooted_at_the_relay() -> None:
"""Config and the worker's own session give an Rtdb on the relay root."""
provider = _provider()
with (
patch.object(connect_mod.FirebaseConfig, "load", return_value=CONFIG),
patch.object(connect_mod, "FirebaseTokenProvider", return_value=provider),
patch.object(connect_mod, "credential_store_for") as store,
):
rtdb = connect_mod.connect()
store.assert_called_once_with("diet_guard_claude")
assert rtdb.root == ROOT
assert rtdb.sealer is None
def test_connect_without_firebase_config_is_a_setup_error() -> None:
"""No crdt-sync config: nothing to connect to."""
with (
patch.object(connect_mod.FirebaseConfig, "load", side_effect=ConfigError("x")),
pytest.raises(
connect_mod.RelaySetupError, match="no crdt-sync firebase config"
),
):
connect_mod.connect()
def test_connect_without_a_session_names_the_seed_command() -> None:
"""No signed-in session: the error says how to seed one for this app."""
with (
patch.object(connect_mod.FirebaseConfig, "load", return_value=CONFIG),
patch.object(connect_mod, "credential_store_for"),
patch.object(
connect_mod, "FirebaseTokenProvider", return_value=_provider(session=False)
),
pytest.raises(
connect_mod.RelaySetupError,
match=r"seed_session .* --app diet_guard_claude",
),
):
connect_mod.connect()
def test_token_source_wraps_auth_errors_without_the_secret() -> None:
"""An auth failure becomes an RtdbError; a good token passes through."""
async def go() -> str:
good = connect_mod.token_source(_provider())
bad = connect_mod.token_source(_provider(token=FirebaseAuthError("secret")))
with pytest.raises(RtdbError, match="firebase auth failed"):
await bad()
return await good()
assert asyncio.run(go()) == "tok"
def test_connect_sealed_is_connect_then_unlock() -> None:
"""The seam is a thin wrapper over the two real steps."""
real = fresh(connect_mod)
rtdb = object()
with (
patch.object(real, "connect", return_value=rtdb),
patch.object(real, "unlock_sealed", AsyncMock(return_value="sealed")) as unlock,
):
assert asyncio.run(real.connect_sealed()) == "sealed"
unlock.assert_awaited_once_with(rtdb)
# -- unlock ---------------------------------------------------------------------
def test_unlock_seals_with_the_existing_header_key() -> None:
"""The header is diet_guard's own (made once); a second unlock gets the same key."""
fake = FakeRtdb(sealed=False)
first = asyncio.run(connect_mod.unlock_sealed(fake.rtdb()))
assert fake.raw_get("diet-guard-sync/e2e") is not None
second = asyncio.run(connect_mod.unlock_sealed(fake.rtdb()))
assert first.sealer is not None
assert second.sealer is not None
first.sealer.root = second.sealer.root = ROOT
sealed = first.sealer.seal("requests/R/req", {"a": 1})
assert second.sealer.open("requests/R/req", sealed) == {"a": 1}
assert first.sealer.layout is LAYOUT
@pytest.mark.parametrize("phrase", ["", "the-wrong-phrase"])
def test_unlock_with_no_or_a_wrong_passphrase_fails_closed(
phrase: str, tmp_path: Path
) -> None:
"""A locked key raises RelaySetupError and leaves the client unsealed."""
fake = FakeRtdb(sealed=False)
asyncio.run(
connect_mod.unlock_sealed(fake.rtdb())
) # header made with the test phrase
file = tmp_path / "other-phrase"
file.write_text(phrase, encoding="utf-8")
rtdb = fake.rtdb()
with (
patch.object(_sync_e2e, "PASSWORD_FILE", file),
pytest.raises(connect_mod.RelaySetupError, match="e2e locked"),
):
asyncio.run(connect_mod.unlock_sealed(rtdb))
def test_missing_password_file_reads_as_locked(tmp_path: Path) -> None:
"""No password file: an empty passphrase, which unlock refuses."""
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "absent"):
assert connect_mod.passphrase() == ""
assert connect_mod.passphrase() == "test-passphrase"
# -- sync touch points ----------------------------------------------------------
def test_sync_touch_points_call_the_real_helpers() -> None:
"""pull_peers and publish forward to the narrow pull and the full tick."""
real = fresh(_claude_sync)
with (
patch("diet_guard._sync_refresh.pull_peer_logs", return_value="x") as pull,
patch("diet_guard._sync_events.publish_after_log", return_value=None) as pub,
):
assert real.pull_peers() == "x"
assert real.publish() is None
pull.assert_called_once_with()
pub.assert_called_once_with()
# -- the serve loop and the CLI -------------------------------------------------
class _StopError(Exception):
"""Ends the serve loop in a test."""
def test_serve_waits_and_retries_while_the_relay_cannot_start() -> None:
"""A setup failure writes nothing, sleeps 60 s and tries again."""
rtdb = Mock(aclose=AsyncMock())
waits: list[float] = []
async def sleep(seconds: float) -> None:
waits.append(seconds)
async def go() -> None:
with (
patch.object(
connect_mod,
"connect_sealed",
AsyncMock(side_effect=[connect_mod.RelaySetupError("locked"), rtdb]),
),
patch.object(relay.MealServer, "run", AsyncMock(side_effect=_StopError)),
pytest.raises(_StopError),
):
await relay.serve(sleep)
asyncio.run(go())
assert waits == [relay.RETRY_S]
rtdb.aclose.assert_awaited_once_with()
@pytest.mark.parametrize(
("raised", "code"),
[(None, 0), (KeyboardInterrupt(), 0), (StreamCancelledError("rules"), 1)],
)
def test_main_exit_codes(raised: BaseException | None, code: int) -> None:
"""Clean stop and Ctrl-C exit 0; a cancelled stream exits 1 (systemd restarts)."""
with patch.object(relay, "serve", AsyncMock(side_effect=raised)):
assert relay.main() == code
def test_cli_dispatches_claude_worker_lazily() -> None:
"""The subcommand imports the worker only when it runs, and returns its code."""
with patch.object(relay, "main", return_value=7):
assert cli_main(["claude-worker"]) == 7

View File

@ -0,0 +1,121 @@
"""The shared contract fixture: sealed bytes, layout, ids and body rules."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from crdt_sync import E2eCipher
import pytest
from rtdb_relay.layout import E2eLayoutError, Layout
from rtdb_relay.seal import SEALED, Sealer
from diet_guard._claude_contract import (
BadRequestError,
entry_id_for,
is_expired,
parse_body,
)
from diet_guard._claude_layout import E2E_LAYOUT, KIND, LAYOUT, ROOT
from diet_guard._sync_e2e import DIET_LAYOUT
FIXTURE: dict[str, Any] = json.loads(
(
Path(__file__).resolve().parents[2]
/ "tests/fixtures/claude_relay_contract.json"
).read_text(encoding="utf-8")
)
def _sealer(layout: Layout = LAYOUT) -> Sealer:
return Sealer(E2eCipher(bytes.fromhex(FIXTURE["key_hex"])), layout)
def test_root_and_header_are_the_existing_ones() -> None:
"""The relay shares diet_guard's e2e header: same salt, same key."""
assert FIXTURE["root"] == ROOT
assert E2E_LAYOUT.e2e_path == FIXTURE["header_path"] == DIET_LAYOUT.e2e_path
assert KIND == "meal"
def test_layout_matches_the_fixture() -> None:
"""The sealed units and the one clear node are exactly the contract's."""
assert set(LAYOUT.clear) == set(FIXTURE["layout"]["clear"])
assert {k: sorted(v) for k, v in LAYOUT.units.items()} == FIXTURE["layout"]["units"]
@pytest.mark.parametrize(
"node",
[FIXTURE["request"], *FIXTURE["results"].values()],
ids=["request", "logged", "error", "expired"],
)
def test_sealed_nodes_open_to_the_contract_plaintext(node: dict[str, Any]) -> None:
"""A phone-sealed node opens to its plaintext plus its clear siblings."""
stored = node["node"]
assert SEALED in stored
assert {k: v for k, v in stored.items() if k != SEALED} == node["clear"]
opened = _sealer().open(node["path"], stored)
assert opened == {**node["plain"], **node["clear"]}
def test_a_blob_moved_to_another_path_does_not_open() -> None:
"""The unit path is the AAD: a copied request is read as absent."""
moved = FIXTURE["request"]["node"]
assert _sealer().open("requests/01JD5Z8K3M7Q2W9XH4TBN6VR0F/req", moved) is None
def test_the_sealer_refuses_a_path_outside_the_contract() -> None:
"""Everything else is fail closed: no rule, no write."""
with pytest.raises(E2eLayoutError):
_sealer().seal("presence/workers/pc", {"x": 1})
def test_entry_id_is_the_fixtures_uuid5() -> None:
"""The rid maps to one fixed entry id on both devices."""
assert entry_id_for(FIXTURE["rid"]) == FIXTURE["entry_id"]
assert entry_id_for("a") != entry_id_for("b")
@pytest.mark.parametrize("case", FIXTURE["body_cases"], ids=lambda c: c["name"])
def test_body_cases(case: dict[str, Any]) -> None:
"""The phone's and the PC's validators agree on every shared case."""
if case["valid"]:
assert parse_body(case["body"]).mode == case["body"]["mode"]
else:
with pytest.raises(BadRequestError):
parse_body(case["body"])
def test_parsed_body_carries_text_photo_and_slot() -> None:
"""A valid body is trimmed and its photo decoded."""
body = FIXTURE["request"]["plain"]["body"]
parsed = parse_body({**body, "text": " banan "})
assert parsed.text == "banan"
assert parsed.photo is not None
assert parsed.photo.startswith(b"\xff\xd8")
assert parsed.client_slot_min == 720
def test_expiry_is_24_hours_of_server_time_and_fails_closed() -> None:
"""Older than 24 h, or no usable ``created``, is expired."""
day = 24 * 3600 * 1000
assert not is_expired(1_000, 1_000 + day)
assert is_expired(1_000, 1_001 + day)
for bad in (None, "x", True):
assert is_expired(bad, 5)
@pytest.mark.parametrize(
"body",
[
{"text": 5, "client_slot_min": 1, "mode": "due"},
{"photo_jpeg_b64": 5, "client_slot_min": 1, "mode": "due"},
{"photo_jpeg_b64": "A" * 600_001, "client_slot_min": 1, "mode": "due"},
{"text": "a", "client_slot_min": True, "mode": "due"},
],
)
def test_wrongly_typed_or_oversize_fields_are_refused(body: dict[str, Any]) -> None:
"""Types and size caps beyond the shared cases."""
with pytest.raises(BadRequestError):
parse_body(body)

View File

@ -56,6 +56,13 @@ def test_answer_and_isolation_options() -> None:
assert message["content"] == [{"type": "text", "text": "banan"}]
@pytest.mark.usefixtures("login")
def test_other_stream_messages_are_skipped() -> None:
"""Assistant/system chatter before the result does not matter."""
fake = FakeSdk([object(), FakeResult({"kcal": 2}), object()])
assert _ask(fake) == {"kcal": 2}
@pytest.mark.usefixtures("login")
@pytest.mark.parametrize(
"messages",

View File

@ -0,0 +1,195 @@
"""The meal server end to end: one request in, one answer and one entry out."""
from __future__ import annotations
import asyncio
from typing import Any
from unittest.mock import patch
import pytest
from diet_guard import _claude_sync, _claude_worker
from diet_guard._claude_contract import entry_id_for, parse_body
from diet_guard._claude_estimate import EstimateError
from diet_guard._claude_log import log_estimate
from diet_guard._slot_wire import entry_slot_minute
from diet_guard.tests._claude_worker_fakes import (
BODY,
DAY_MS,
EST,
NOON,
NOW_MS,
RID,
RID2,
ROOT,
entries,
estimator,
new_server,
put,
request_fake,
serve_once,
)
def test_a_request_is_logged_answered_trimmed_and_published() -> None:
"""Result first, then req is deleted, claim and result stay, publish ran."""
fake = request_fake()
_, out = serve_once(fake, estimator())
assert out is not None
result = fake.get(f"{ROOT}/requests/{RID}/result")
assert result["ok"] is True
assert result["status"] == "logged"
assert result["id"] == RID
assert result["entry_id"] == entry_id_for(RID)
assert result["kcal"] == 410.0
assert result["at"] == NOW_MS
assert fake.get(f"{ROOT}/requests/{RID}/req") is None
assert fake.get(f"{ROOT}/requests/{RID}/claim")["by"] == "pc"
(entry,) = entries()
assert entry["source"] == "claude"
_claude_sync.pull_peers.assert_called_once_with()
_claude_sync.publish.assert_called_once_with()
def test_a_failed_pull_leaves_the_request_pending_and_retries() -> None:
"""No claim, no result, req kept; the retry timer serves it once sync is back."""
fake = request_fake()
estimate = estimator()
_claude_sync.pull_peers.return_value = "sync unavailable (locked)"
async def go() -> list[float]:
db = fake.rtdb()
server = new_server(db, estimate)
sleeps: list[float] = []
gate = asyncio.Event()
async def sleep(seconds: float) -> None:
sleeps.append(seconds)
await gate.wait()
server._sleep = sleep
server.tree = await server._raw.get("requests")
node = server.tree[RID]
assert await server.answer(RID, node) is None
assert await server.answer(RID, node) is None # one retry timer at most
assert fake.get(f"{ROOT}/requests/{RID}/claim") is None
assert fake.get(f"{ROOT}/requests/{RID}/result") is None
estimate.assert_not_awaited()
_claude_sync.pull_peers.return_value = None
gate.set()
assert server._retry is not None
await server._retry
await asyncio.gather(*server.tasks)
await db.aclose()
return sleeps
assert asyncio.run(go()) == [_claude_worker.RETRY_S]
assert fake.get(f"{ROOT}/requests/{RID}/result")["status"] == "logged"
@pytest.mark.parametrize(
"code", ["estimate_failed", "estimate_timeout", "estimate_invalid"]
)
def test_an_estimator_failure_is_an_error_result_and_nothing_is_logged(
code: str,
) -> None:
"""Fail closed: error result with retry, no entry, payload still deleted."""
fake = request_fake()
serve_once(fake, estimator(EstimateError(code, "boom")))
result = fake.get(f"{ROOT}/requests/{RID}/result")
assert result["ok"] is False
assert (result["status"], result["error_code"], result["code"]) == (
"error",
code,
code,
)
assert result["retry"] is True
assert entries() == []
assert fake.get(f"{ROOT}/requests/{RID}/req") is None
@pytest.mark.parametrize(
("body", "age_ms", "code"),
[
({"mode": "due", "client_slot_min": 5}, 0, "bad_request"),
(BODY, DAY_MS + 1, "expired"),
],
)
def test_bad_and_expired_requests_are_answered_not_estimated(
body: dict[str, Any], age_ms: int, code: str
) -> None:
"""No model call and no entry for a request that breaks the contract."""
fake = request_fake(body, age_ms=age_ms)
estimate = estimator()
serve_once(fake, estimate)
result = fake.get(f"{ROOT}/requests/{RID}/result")
assert (result["status"], result["error_code"], result["retry"]) == (
"error",
code,
False,
)
estimate.assert_not_awaited()
assert entries() == []
def test_a_crash_between_log_and_result_is_replayed_without_a_second_entry() -> None:
"""The entry exists but no result: the replay answers from the log."""
fake = request_fake()
log_estimate(RID, EST, parse_body(BODY), NOON)
estimate = estimator()
serve_once(fake, estimate)
estimate.assert_not_awaited()
assert fake.get(f"{ROOT}/requests/{RID}/result")["entry_id"] == entry_id_for(RID)
assert len(entries()) == 1
def test_a_duplicate_dispatch_of_one_request_logs_one_entry() -> None:
"""The same stale node served twice (own claim taken over): one entry."""
fake = request_fake()
estimate = estimator()
async def go() -> None:
db = fake.rtdb()
server = new_server(db, estimate)
node = await server._raw.get(f"requests/{RID}")
first = await server.answer(RID, node)
second = await server.answer(RID, node)
assert first is not None
assert second is not None
await asyncio.gather(*server.tasks)
await db.aclose()
asyncio.run(go())
assert len(entries()) == 1
assert estimate.await_count == 1
def test_two_requests_take_two_different_due_slots() -> None:
"""Each due-mode request takes the oldest slot still due when it runs."""
fake = request_fake(rid=RID)
put(fake, RID2, {**BODY, "mode": "due"})
with patch("diet_guard._claude_log.due_slots", side_effect=[(480, 720), (720,)]):
serve_once(fake, estimator(), RID)
serve_once(fake, estimator(), RID2)
slots = sorted(entry_slot_minute(e) or 0 for e in entries())
assert slots == [480, 720]
def test_a_request_claimed_by_another_worker_is_left_alone() -> None:
"""A live lease elsewhere: no estimate, no result, the payload stays."""
fake = request_fake()
lease = {
"by": "other-pc",
"lease_until": NOW_MS + 200_000,
"attempt": 1,
"phase": "x",
"at": 1,
}
fake.set(f"{ROOT}/requests/{RID}/claim", lease)
estimate = estimator()
_, out = serve_once(fake, estimate)
assert out is None
estimate.assert_not_awaited()
assert fake.get(f"{ROOT}/requests/{RID}/result") is None
assert fake.get(f"{ROOT}/requests/{RID}/req") is not None
_claude_sync.publish.assert_not_called()

View File

@ -0,0 +1,134 @@
"""The meal server's housekeeping: old answers, failed cleanups, the stream."""
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import TYPE_CHECKING, Any
from unittest.mock import patch
from rtdb_relay.sse import Event
from diet_guard import _claude_sync, _claude_worker
from diet_guard._claude_worker import MealHandler
from diet_guard.tests._claude_worker_fakes import (
DAY_MS,
NOW_MS,
NOW_S,
RID,
RID2,
ROOT,
FakeRtdb,
estimator,
new_server,
request_fake,
serve_once,
)
if TYPE_CHECKING:
from collections.abc import AsyncIterator
import pytest
def test_old_answers_are_deleted_and_fresh_ones_kept() -> None:
"""Results older than 24 h go; a recent result and its claim stay."""
fake = FakeRtdb(now_ms=NOW_MS)
for rid, at in ((RID, NOW_MS - DAY_MS - 5), (RID2, NOW_MS - 1000)):
fake.raw_set(f"{ROOT}/requests/{rid}/result", {"_e2e": "x", "at": at})
fake.raw_set(f"{ROOT}/requests/{rid}/claim", {"by": "pc"})
async def go() -> None:
db = fake.rtdb()
server = new_server(db)
tree = await server._raw.get("requests")
server.dispatch(tree)
server.dispatch(tree) # a second event does not start a second delete
await asyncio.gather(*server.tasks)
await db.aclose()
asyncio.run(go())
assert fake.raw_get(f"{ROOT}/requests/{RID}") is None
assert fake.raw_get(f"{ROOT}/requests/{RID2}/claim") == {"by": "pc"}
def test_failed_cleanups_are_only_logged(caplog: pytest.LogCaptureFixture) -> None:
"""A failed payload delete or publish does not undo the answer."""
fake = request_fake()
fake.fail[("DELETE", f"/requests/{RID}/req")] = 500
_claude_sync.publish.return_value = "sync unavailable"
with caplog.at_level("WARNING"):
serve_once(fake, estimator())
assert fake.get(f"{ROOT}/requests/{RID}/result")["status"] == "logged"
assert "could not delete the request payload" in caplog.text
assert "post-answer sync skipped" in caplog.text
def test_collect_failure_is_logged_and_the_node_stays(
caplog: pytest.LogCaptureFixture,
) -> None:
"""The node stays when its delete fails, and its marker is released."""
fake = FakeRtdb(now_ms=NOW_MS)
old = NOW_MS - 25 * 3600 * 1000
fake.raw_set(f"{ROOT}/requests/{RID}/result", {"_e2e": "x", "at": old})
fake.fail[("DELETE", f"/requests/{RID}")] = 500
async def go() -> None:
db = fake.rtdb()
server = new_server(db)
server.dispatch(await server._raw.get("requests"))
await asyncio.gather(*server.tasks)
assert RID not in server._collecting
await db.aclose()
with caplog.at_level("WARNING"):
asyncio.run(go())
assert "could not delete the old request" in caplog.text
assert fake.raw_get(f"{ROOT}/requests/{RID}") is not None
def test_answer_ignores_nodes_that_are_not_pending_requests() -> None:
"""A bad rid, an answered node and a node without req are skipped unpulled."""
async def go() -> list[object]:
db = FakeRtdb().rtdb()
server = new_server(db)
out = [
await server.answer("not-a-ulid", {"req": {}}),
await server.answer(RID, {"req": {}, "result": {}}),
await server.answer(RID, {"claim": {}}),
]
await db.aclose()
return out
assert asyncio.run(go()) == [None, None, None]
_claude_sync.pull_peers.assert_not_called()
def test_run_mirrors_the_stream_and_dispatches() -> None:
"""Every stream event updates the local tree and serves what is pending."""
fake = request_fake()
node = {"req": fake.raw_get(f"{ROOT}/requests/{RID}/req")}
async def events(*_args: object, **_kwargs: object) -> AsyncIterator[Event]:
yield Event("put", "/", {RID: node})
async def go() -> dict[str, Any]:
db = fake.rtdb()
server = new_server(db)
with patch.object(_claude_worker.sse, "listen", events):
await server.run()
await asyncio.gather(*server.tasks)
await db.aclose()
return server.tree
assert RID in asyncio.run(go())
assert fake.get(f"{ROOT}/requests/{RID}/result")["status"] == "logged"
def test_handler_defaults_are_the_real_estimator_and_clock() -> None:
"""A bare MealHandler wires the production estimator, clock and now."""
handler = MealHandler()
assert handler._estimate.__name__ == "estimate_meal_async"
assert isinstance(handler._now(), datetime)
assert handler._clock() > NOW_S / 2

View File

@ -0,0 +1,41 @@
"""``log_meal(entry_id=...)`` and ``find_entry``: what makes a replay find itself."""
from __future__ import annotations
from diet_guard._estimator import Nutrition
from diet_guard._state import log_meal
from diet_guard._state_sync import find_entry, log_meal_as
FOOD = Nutrition(kcal=100, protein_g=1, carbs_g=2, fat_g=3, grams=50, source="claude")
def test_given_entry_id_is_used_and_found() -> None:
"""The id the caller picks is the stored id, and find_entry returns it."""
entry = log_meal_as("fixed-id", "owsianka", FOOD, 480)
assert entry["id"] == "fixed-id"
found = find_entry("fixed-id")
assert found is not None
assert found["desc"] == "owsianka"
def test_default_id_is_still_a_fresh_uuid() -> None:
"""Without entry_id nothing changes: two meals, two distinct ids."""
first = log_meal("a", FOOD, 480)
second = log_meal("a", FOOD, 480)
assert first["id"] != second["id"]
def test_find_entry_sees_a_tombstoned_entry() -> None:
"""A deleted entry still counts as logged: a replay must not re-log it."""
log_meal_as("gone", "a", FOOD, 480)
from diet_guard._state_sync import undo_last_today
assert undo_last_today() is not None
found = find_entry("gone")
assert found is not None
assert found["deleted"]
def test_find_entry_unknown_is_none() -> None:
"""No such id: None, no exception."""
assert find_entry("never-logged") is None

View File

@ -10,8 +10,9 @@ This file is the contract both halves build against. The fixture
`tests/fixtures/claude_relay_contract.json` is read by the Python tests and
by the phone's Dart tests, so the two cannot drift. Regenerate it with
`scripts/build_claude_relay_fixture.py` (random nonces: bytes change, the
plaintext does not). The worker lives in `diet_guard/_claude_*.py`; the
estimator and its skill are described at the end.
plaintext does not). The worker lives in `diet_guard/_claude_*.py` (`_claude_worker.py` serves,
`_claude_log.py` picks the slot and writes, `_claude_estimate.py` calls the
model); the estimator and its skill are described at the end.
## 1. Where it lives in RTDB
@ -97,7 +98,7 @@ Error:
| `code` | Meaning | `retry` |
|---|---|---|
| `bad_request` | body fails section 2 | false |
| `expired` | `created` older than 24 h when the PC got to it | false |
| `expired` | `created` older than 24 h (or missing) when the PC got to it | false |
| `estimate_timeout` | Claude exceeded 45 s | true |
| `estimate_failed` | Claude errored or the CLI/login is unusable | true |
| `estimate_invalid` | output not JSON / fails the schema / nonsense values | true |
@ -138,8 +139,9 @@ PC: claim (ETag lease) -> validate -> age check -> already logged? -> │
```
1. **Idempotent by request id, twice over.** The entry id is
`uuid5(NAMESPACE, rid)`. Before spending a Claude call the worker looks
for that id in the raw log (tombstones included). Found: it rebuilds the
`uuid5(NAMESPACE, rid)`, written with `log_meal_as`. Before spending a
Claude call the worker looks for that id with `find_entry` in the raw log
(tombstones included). Found: it rebuilds the
result from the entry and logs nothing. So a duplicate SSE event, a lease
that expired, or a crash between `log_meal` and the result PUT (the
worker takes over its own dead claim on restart) all end in one entry.
@ -166,7 +168,8 @@ PC: claim (ETag lease) -> validate -> age check -> already logged? -> │
## 6. The worker
`python -m diet_guard claude-worker`, run by `diet-guard-claude.service`
(systemd `--user`, `Restart=on-failure`, `WantedBy=default.target`).
(systemd `--user`, `Restart=on-failure`, `WantedBy=default.target`; the
unit lives at the repo root with the other two, `install.sh` installs it).
- Event-driven: one SSE stream on `R/requests`. Reconnects forever with
1/2/5/10/30 s backoff; `auth_revoked` reconnects at once; `cancel` (the

View File

@ -27,6 +27,10 @@ readonly REPO_DIR="$SCRIPT_DIR"
readonly SERVICE_SRC="$SCRIPT_DIR/diet-guard-gate.service"
readonly TIMER_SRC="$SCRIPT_DIR/diet-guard-gate.timer"
readonly SYNC_SERVICE_SRC="$SCRIPT_DIR/diet-guard-sync.service"
readonly CLAUDE_SERVICE_SRC="$SCRIPT_DIR/diet-guard-claude.service"
# The relay worker's own Firebase session (never the gate's: two processes
# refreshing one token file corrupt it). Seeded once, see the step below.
readonly CLAUDE_SESSION_FILE="$HOME/.config/diet_guard_claude/firebase_auth.json"
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
readonly DATA_DIR="$HOME/.local/share/diet_guard"
readonly BUDGET_FILE="$DATA_DIR/.budget"
@ -47,8 +51,8 @@ fi
echo "[2/5] Installing diet_guard + dependencies for /usr/bin/python..."
/usr/bin/python3 -m pip install --user --break-system-packages -e "$REPO_DIR"
echo " Installed. Verifying import..."
/usr/bin/python3 -c "import diet_guard; import gatelock" \
&& echo " diet_guard and gatelock import cleanly from the system interpreter."
/usr/bin/python3 -c "import diet_guard; import gatelock; import claude_agent_sdk, rtdb_relay, httpx" \
&& echo " diet_guard, gatelock and the Claude relay deps import cleanly from the system interpreter."
# 3. systemd user timer + service (gate) -------------------------------------
echo "[3/5] Installing the gate's systemd user timer + service..."
@ -83,6 +87,23 @@ else
echo " mode 600: chmod 600 \"$SYNC_TOKEN_FILE\""
fi
# 4b. The "send to Claude" relay worker ------------------------------------
# Serves the phone's meal requests (docs/DOCS-claude-relay.md). It needs its own
# signed-in Firebase session, which only one Google consent can create, so the
# unit is installed always but started only once the session file exists.
echo "[4b/5] Installing the Claude relay worker unit..."
cp "$CLAUDE_SERVICE_SRC" "$SYSTEMD_USER_DIR/diet-guard-claude.service"
systemctl --user daemon-reload
if [[ -f "$CLAUDE_SESSION_FILE" ]]; then
systemctl --user enable --now diet-guard-claude.service
echo " Relay worker enabled and started."
else
echo " Not started: no session at $CLAUDE_SESSION_FILE. Seed it once (one"
echo " Google consent) in ~/src/utils/crdt-sync:"
echo " python3 -m tool.seed_session --client-id ... --client-secret ... --app diet_guard_claude"
echo " then re-run this installer."
fi
# 5. Set the initial daily budget ---------------------------------------------
echo "[5/5] Setting your initial daily budget..."
if [[ -e "$BUDGET_FILE" ]]; then

View File

@ -20,6 +20,7 @@ from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import uuid
from crdt_sync import E2eCipher, E2eLayout
from rtdb_relay.layout import Layout
@ -30,6 +31,9 @@ OUT_FILE = OUT / "claude_relay_contract.json"
KEY_HEX = bytes(range(32)).hex()
RID = "01JD5Z8K3M7Q2W9XH4TBN6VR0E"
# Namespace of the entry id (uuid5 of the rid), as ``_claude_contract``.
ENTRY_NAMESPACE = "5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4"
ENTRY_ID = str(uuid.uuid5(uuid.UUID(ENTRY_NAMESPACE), RID))
ROOT = E2eLayout.of("diet-guard-sync/claude").prefix
HEADER = E2eLayout.of("diet-guard-sync/devices").e2e_path
CLEAR = ("requests/*/claim",)
@ -56,7 +60,7 @@ LOGGED: dict[str, Any] = {
"kind": "meal",
"status": "logged",
"id": RID,
"entry_id": "7b0c5d52-8a43-5a63-b6f5-7d0f1c0e2a44",
"entry_id": ENTRY_ID,
"desc": "2 jajka sadzone i kromka chleba",
"grams": 190,
"kcal": 410,
@ -145,6 +149,8 @@ def build() -> dict[str, Any]:
"header_path": HEADER,
"key_hex": KEY_HEX,
"rid": RID,
"entry_id_namespace": ENTRY_NAMESPACE,
"entry_id": ENTRY_ID,
"layout": {"clear": list(CLEAR), "units": UNITS},
"limits": {
"text_max": 2000,

View File

@ -4,6 +4,8 @@
"header_path": "diet-guard-sync/e2e",
"key_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"rid": "01JD5Z8K3M7Q2W9XH4TBN6VR0E",
"entry_id_namespace": "5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4",
"entry_id": "90729b3a-5202-5ade-824b-f17949d93890",
"layout": {
"clear": [
"requests/*/claim"
@ -27,7 +29,7 @@
"request": {
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/req",
"node": {
"_e2e": "AYkr3BaGDxFvr9QkhFAb1O/op1RoJGARMjrAnpbcvZ7rFxKVSy0kxKTbUSEqQarex+WBhoshvig8CgZ+X5Zpr6lOw+qoOLTEc+Oc31eUi3vyGipYm1zQDtowCQzTLaNXnWHaVtOqFf7cVZ8vsvSot08c0PI7zHjUbY7uCBQoF6q4sOekDm8k23UQSi9vkyd+EL1hPnjtBPCDCI6QoZq+T09YZxKeXm8oA7hWh0r5ZKMcD2n/2K4MLzyIEhi7kZtPH0Mq8adkSPHtPKkPYdKXhpXNVdChCmBXvzPhWJ6xi66p0FViGIVxhAg4IgCwxhzCyRHAYPjufAheZjbMJt+98aAHEGn2ZEImqIOu+o26GxgmxDXSu/u/IQSb5RJKdMheGFhKCpK6n8/7Qg/Z6keendoVMCwIYbhu0wNDs3qaxd+IaLYc33ABvKssu3kMnrwJ2jR6iDYgSrKe+qGxO4A=",
"_e2e": "ARptgd1om/yDg1f7fxoTEDGTYmtYGbzOLbVOyEBtvqnXA+vzMYiZxfyI5pklwS6zxQfPh//X0Saxx27Ae+/NoFZWY1yE6iR+ok73tvMpXl/n687UM1inV6nJe6+9ItOtlNFP6f55RowkbLMopAGFEyeXr+De4L4yz6iYofOxLGV2kVU62Kj+8apl5qNbxY+IcqR4pt6dOwb1Jdn4s0vuQp6geftXf7Ewv2mML0Ubp1MP24x+BuuS6H+OVb68x0idSWyAwRcmS2uUPd44rmcKqec0cPjbQGP00DIGMghASzyHx23iDDT1W9K9Ca5QR+V4HT88zC7mr0YPRTqYNXyYGkttmaMoADx61Uagtdh2QI/9W1PxUQlWESuIb6/kpzyZ5ecpStp3z/vCdfxYUXG1Cqasrv3d3fJfVhJitXNxVsYRkPghHXKcimU2nkGraCdxHbt3qustc/TLKGRF+nE=",
"created": 1795000000000
},
"plain": {
@ -59,7 +61,7 @@
"logged": {
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/result",
"node": {
"_e2e": "AYLAiRb9+uIpXCSEC8v0bzwxY7kNzlTLgpo+Ys36nAlnFANO1/blHQ1t/hv+MdUNGqyMaPQWwOddC6QClMKcxq0LzG5xV+0DL4Q4XDNGszd+RJgp12iZaRoJMEPLzoDQcnyq0kSjlrZaVIii7fJIFZOTrsS7z22CfCYQNi37uWkmglocNwbOmZiuo7XP4xikJyADhNGJuseo8Hrvrjzm0AVfp2+vuubVpDY7xM7EGhn49yDz+iwFRpvqpmHbVD1mFqEY2l0UhGrWEt+WFW5nD5IOejPiVk9eehXJCEJadU+1t/+ADntYwoxyQjwiicgSAgUK4fU3rxNhUeGPgKLYWYXE8ALywAlf6ieoDlRX8bX+YmHTZDuxhA+vttsxkZhPtC6D2ZcyeokOuHRWTNOZBesAyFiLL+co5/8EqUhUAvRxyGU=",
"_e2e": "AcnCnUL+sLfDhgsuRt2bOTVbrRzZlNtm3FupBPJr8/1kQjIV0xPk3fPgRfL4HIQBR9E1ttO18lwVJEn7b5fTPFcpO+oKfIQUDdRxJl5Lzg86UtTGizhk4UU7Qdhq/g6IXoe8HzapQ+JBW6ivOsd+KFCtUFJ42cQyuol7K33K2j2PnFNHM2ADmGnTz8K5mUoWTrxkdXa/jHnCJaDEoQx8wiYXtffq6shiXNa/47V/oe6uorNzzDS8TpVw6fMhDBsCAG6LFEVSxfpG/yVuRg6BuqI8/yiP6yDyqFMK7EmAvpw22PJa9350+FXcL8fLe7fDyV6idRcmttfFvIeOCP4V614Nrnc9aJz8FIFPtbeBK+JYcxH//qcwbi7aDxGLRV8oKMI8JUUI8PC5mEe6nqPla46KgNSLvVBG1CBamL2KAB7ovCQ=",
"at": 1795000009000
},
"plain": {
@ -67,7 +69,7 @@
"kind": "meal",
"status": "logged",
"id": "01JD5Z8K3M7Q2W9XH4TBN6VR0E",
"entry_id": "7b0c5d52-8a43-5a63-b6f5-7d0f1c0e2a44",
"entry_id": "90729b3a-5202-5ade-824b-f17949d93890",
"desc": "2 jajka sadzone i kromka chleba",
"grams": 190,
"kcal": 410,
@ -84,7 +86,7 @@
"error": {
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/result",
"node": {
"_e2e": "AQdF1d1WVvex3sIwfSAq4df+jWFbJ0/rJAF9FUy85X2pQXa98pAHUJ3CPd9AnGmy3nG+ARBc/IjpJjUi7D07Vg8uZGOy6/FRh91uI9F1LMBPZ/pgO65M5+KC7MGEKszcWzntp8vPkLpHw8ujBtN5mmwPrUkKpL+xH6t0mY6/mdSnEuByiy1OOO0FxH5gbvQ+DAO5JKLRsjNPHHj33NlQpejVUH3OUhlcZTDMIGIV4gY8say9dP5cWL+1ppkBLNxU3dnO/oc0pDM/S4+WqdEmJ1vMQyjkhU2hCTgrGAPNPE0YbQ==",
"_e2e": "AWmFLu+Iov25GLdTDVfnRYwy5g+01YwnhpIa0ThJu+GWHla5swvNo+He9EcH8U2Rft15ZUePS8DrapBih7xD51kCsNYKBl5xXiAQUxgmcCIr45/9maYXFynxoQLOwkzp3tTy6kB4I6MZko3JWyRd+KSa8YEV5Rlt279uOZd1dF9wxc4iN+QO2jVwoWtuYED152vTQAhrPep5DpQ3/nkSto4yGCxWn6N05KpHNSqRx5YUrK12eEWw/wflM8ZA7TXsF291Unnq5FLX0KBsdvOO6Wp770FUvxGhwwwuf9K70bw/Gw==",
"at": 1795000009000
},
"plain": {
@ -104,7 +106,7 @@
"expired": {
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/result",
"node": {
"_e2e": "AQekXG0hCaJd2HLHF4wvRk5PZxqhrM+m+DsjWgdU8mLyay3/DX8T6za37LVF1IpM11hkJ9L6vpdJkH3Rfsfedh5NYssuAV+qF2uHCPeeJ9Iy9Anou9TQ/TkEhOBX6/3+y1AJyvSD/gxACZX32g5tzW+qA4fgbJyPgYIEo2SN5u27M2NrZQzXIpxUYaiqDt2eClAKZH/o6xfMOXVEHCV5QHdbGqxVBIMDZ0D+E8O9zVsNDpHxejaMwUf/vsvjolPhKN4pTqX0ksmW38LgSWU=",
"_e2e": "AdbyPhYZMItxxH+1gHmCfJ6jpWfzhTaSqKA7HE6CceNsyQRR80AREbfMbJcnKj4ExJU28MFP7AjqAGldaqzC8PJTldXOymupascUvVHXIQ8MZJy07Wzb5XxtdkaSL26YWAwIu1Kbz6fyqoI4xBRcTNIz5xAEzW++656co/dETMZe8mfnj1tFuGGjZLGoDm8d3lxbnXWU8Z+uCEHmGjKGYaAwFKEUASzX9tdZgbnnyYhnnbFf3eOqwrjEBdE6dpoj2yow1DnH2h06Fx2VgnM=",
"at": 1795000009000
},
"plain": {