From 2bdb7925a8e938aa276d6df735b67a73972fa578 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 16 Aug 2026 14:28:22 +0200 Subject: [PATCH] Read the meal schedule from a forward-only history (Python) Wires the Python side to the configurable schedule. No edit surface yet, so nothing writes a schedule and current_schedule() returns the default -- the derived hours are still 08/12/16/20 and the cutoff is still 22:00. Verified by running it: before any edit the slots are unchanged, after recording 08-20 x5 they become 08:00, 11:00, 14:00, 17:00, 20:00, and a 2020 day still resolves to the four-meal schedule. _slots.py now takes the schedule as a *required* argument rather than reading module constants. Required, not defaulted, on purpose: a default would let a call site missed in this refactor keep deriving the old fixed hours on one device, and a slot one device offers while the other does not is a checkpoint that can never be satisfied. Making it required let mypy enumerate the nine call sites instead of trusting a grep. The history is forward-only and seeds the default at the epoch *before* recording today's value, so switching to five meals leaves past days judged against the four-meal schedule they actually ran under. Same shape and same reasoning as _budget_history.py; it will ride the same CRDT record. Two details worth naming: - MEAL_SCHEDULE_FILE lands in DATA_DIR, so conftest's _isolate_state redirect is patched in this same commit rather than a later one. Confirmed with a canary that the redirect is live and that ~/.local/share/diet_guard/ has no .meal_schedule after a full run. - _mcp_read imports _budget.current_schedule already, so the meal-schedule lookup is aliased rather than shadowing it. _gatelock._pending_slots is spelled `is None` rather than `or` now. The two are in fact equivalent -- if 0 is a slot it is necessarily the first slot, checked exhaustively -- but the intent should not rest on that coincidence. 761 tests, 100% branch coverage. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM --- app/pubspec.yaml | 2 +- diet_guard/_cli.py | 3 +- diet_guard/_cli_log.py | 3 +- diet_guard/_constants.py | 6 + diet_guard/_gate.py | 3 +- diet_guard/_gatelock.py | 9 +- diet_guard/_mcp.py | 5 +- diet_guard/_mcp_read.py | 8 +- diet_guard/_meal_schedule_store.py | 232 +++++++++++++++++++ diet_guard/_slots.py | 93 ++++---- diet_guard/tests/conftest.py | 4 + diet_guard/tests/test_meal_schedule_store.py | 196 ++++++++++++++++ diet_guard/tests/test_slots.py | 115 +++++++-- 13 files changed, 605 insertions(+), 74 deletions(-) create mode 100644 diet_guard/_meal_schedule_store.py create mode 100644 diet_guard/tests/test_meal_schedule_store.py diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 97cc0d3..8840a8b 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.31+1 +version: 1.0.32+1 environment: sdk: ^3.12.2 diff --git a/diet_guard/_cli.py b/diet_guard/_cli.py index 56e9600..e48d2ca 100644 --- a/diet_guard/_cli.py +++ b/diet_guard/_cli.py @@ -32,6 +32,7 @@ from diet_guard._cli_init import cmd_init from diet_guard._cli_log import ManualMacroArgs, Portion, cmd_ate from diet_guard._cli_sync import cmd_sync from diet_guard._gate import due_slots +from diet_guard._meal_schedule_store import current_schedule from diet_guard._slots import day_slots, slot_label from diet_guard._state import ( entry_kcal, @@ -109,7 +110,7 @@ def _print_slot_status() -> None: logged = logged_slots_today() due = set(due_slots()) parts: list[str] = [] - for slot in day_slots(): + for slot in day_slots(current_schedule()): if slot in logged: mark = "logged" elif slot in due: diff --git a/diet_guard/_cli_log.py b/diet_guard/_cli_log.py index fd54eb2..0aea963 100644 --- a/diet_guard/_cli_log.py +++ b/diet_guard/_cli_log.py @@ -17,6 +17,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING from diet_guard._foodbank import remember_food +from diet_guard._meal_schedule_store import current_schedule from diet_guard._portions import DEFAULT_ITEM_GRAMS, estimate_unit_grams from diet_guard._resolve import ManualMacros, resolve_nutrition from diet_guard._slots import slot_for_log @@ -145,7 +146,7 @@ def cmd_ate( "re-run with --kcal to log it manually.", ) return 1 - log_meal(description, nutrition, slot_for_log(now_local())) + log_meal(description, nutrition, slot_for_log(now_local(), current_schedule())) remember_food(description, nutrition) macro_str = f"P{nutrition.protein_g:g} C{nutrition.carbs_g:g} F{nutrition.fat_g:g}" portion_str = f"{nutrition.grams:g} g" if nutrition.grams else "portion n/a" diff --git a/diet_guard/_constants.py b/diet_guard/_constants.py index 9b5995c..714b06d 100644 --- a/diet_guard/_constants.py +++ b/diet_guard/_constants.py @@ -48,6 +48,12 @@ BUDGET_FILE: Path = DATA_DIR / ".budget" # of it is untouched. Classifying a *past* day reads this; everything about # *today* still reads BUDGET_FILE. Git-ignored, never committed. BUDGET_HISTORY_FILE: Path = DATA_DIR / ".budget_history" +# The effective-from history of the meal schedule (see _meal_schedule_store.py) +# -- when the user eats their first and last meal, and how many meals fall in +# between. Forward-only for the same reason as the budget history: switching +# from four meals to five must not retroactively mark every past day as having +# missed a checkpoint. Git-ignored, never committed. +MEAL_SCHEDULE_FILE: Path = DATA_DIR / ".meal_schedule" # --- Estimator (Open Food Facts) ------------------------------------------- # The default backend is Open Food Facts' "Search-a-licious" full-text search: diff --git a/diet_guard/_gate.py b/diet_guard/_gate.py index 1f415a2..c3d502e 100644 --- a/diet_guard/_gate.py +++ b/diet_guard/_gate.py @@ -17,6 +17,7 @@ from __future__ import annotations from typing import TYPE_CHECKING +from diet_guard._meal_schedule_store import current_schedule from diet_guard._slots import missing_slots, slot_label from diet_guard._state import ( now_local, @@ -39,7 +40,7 @@ def due_slots(now: datetime | None = None) -> tuple[int, ...]: The slot hours that still need a meal logged (empty == nothing due). """ reference = now if now is not None else now_local() - return missing_slots(reference, logged_slots_today()) + return missing_slots(reference, logged_slots_today(), current_schedule()) def gate_is_due(now: datetime | None = None) -> bool: diff --git a/diet_guard/_gatelock.py b/diet_guard/_gatelock.py index b6b7c5e..dc5503a 100644 --- a/diet_guard/_gatelock.py +++ b/diet_guard/_gatelock.py @@ -63,6 +63,7 @@ from diet_guard._gatelock_ui import ( GateCallbacks, make_vars, ) +from diet_guard._meal_schedule_store import current_schedule from diet_guard._slots import current_slot, day_slots from diet_guard._state import now_local @@ -102,7 +103,13 @@ def _pending_slots(*, demo_mode: bool) -> list[int]: if pending: return pending if demo_mode: - return [current_slot(now_local()) or day_slots()[0]] + schedule = current_schedule() + # Spelled `is None` rather than `or` because slot 0 (midnight) is + # falsy. The two happen to be equivalent -- if 0 is a slot it is + # necessarily the *first* slot, so both arms return 0, verified + # exhaustively -- but the intent should not depend on that coincidence. + elapsed = current_slot(now_local(), schedule) + return [elapsed if elapsed is not None else day_slots(schedule)[0]] return [] diff --git a/diet_guard/_mcp.py b/diet_guard/_mcp.py index 989e54f..b9243c9 100644 --- a/diet_guard/_mcp.py +++ b/diet_guard/_mcp.py @@ -44,6 +44,7 @@ from pydantic import BaseModel # the names are genuinely used -- drop this and the server starts write-only. from diet_guard._mcp_read import get_averages, get_slots, get_status, list_today from diet_guard._mcp_server import APPENDS, logger, mcp +from diet_guard._meal_schedule_store import current_schedule from diet_guard._resolve import ManualMacros, resolve_nutrition from diet_guard._slots import slot_for_log from diet_guard._state import ( @@ -131,7 +132,9 @@ def log_meal( "or Open Food Facts. Pass kcal= to log it manually." ), } - target_slot = slot if slot is not None else slot_for_log(now_local()) + target_slot = ( + slot if slot is not None else slot_for_log(now_local(), current_schedule()) + ) resolved = { "kcal": nutrition.kcal, "protein_g": nutrition.protein_g, diff --git a/diet_guard/_mcp_read.py b/diet_guard/_mcp_read.py index 3fe440f..f05539e 100644 --- a/diet_guard/_mcp_read.py +++ b/diet_guard/_mcp_read.py @@ -20,6 +20,7 @@ from diet_guard._averages_report import monthly_average, weekly_average from diet_guard._budget import BudgetError, current_schedule, daily_budget from diet_guard._gate import due_slots from diet_guard._mcp_server import READS_ONLY, mcp +from diet_guard._meal_schedule_store import current_schedule as current_meal_schedule from diet_guard._slots import current_slot, day_slots, slot_label from diet_guard._state import ( load_log, @@ -94,7 +95,7 @@ def get_status() -> dict[str, Any]: "budget_initialized": band is not None, "due_slots": [slot_label(slot) for slot in due_slots()], "logged_slots": sorted(logged_slots_today()), - "current_slot": current_slot(now_local()), + "current_slot": current_slot(now_local(), current_meal_schedule()), } @@ -176,9 +177,10 @@ def get_slots() -> dict[str, Any]: Pure schedule information (08:00 / 12:00 / 16:00 / 20:00 by default) with no budget or intake data attached. """ + schedule = current_meal_schedule() return { "day_slots": [ - {"hour": slot, "label": slot_label(slot)} for slot in day_slots() + {"hour": slot, "label": slot_label(slot)} for slot in day_slots(schedule) ], - "current_slot": current_slot(now_local()), + "current_slot": current_slot(now_local(), schedule), } diff --git a/diet_guard/_meal_schedule_store.py b/diet_guard/_meal_schedule_store.py new file mode 100644 index 0000000..c0e76f3 --- /dev/null +++ b/diet_guard/_meal_schedule_store.py @@ -0,0 +1,232 @@ +"""Forward-only history of the user's meal schedule, and its persistence. + +The schedule is freely editable on either device, but *judging a past day* must +use the schedule that applied on that day. Otherwise switching from four meals +to five would retroactively mark every earlier day as having missed a +checkpoint. + +The shape is deliberately the same as :mod:`diet_guard._budget_history`: a +forward-only list of ``(effective_from, schedule)`` entries, where the schedule +for a day is the newest entry whose ``effective_from`` is on or before it. +Editing appends (or, for a same-day re-edit, replaces) that day's entry, and +every earlier day keeps whatever applied then. + +Storage and sync are split the same way too: + +* the entries live in their own file (``.meal_schedule``); +* they travel as extra ``sched:`` *fields* on the existing + ``budget`` CRDT record (see :mod:`diet_guard.sync_merge`). + +That second point is what makes this shippable without a coordinated release: +``merge_record`` does per-field last-writer-wins over the *union* of field +names, and both devices push the merged record rather than their own, so a +device that knows nothing about meal schedules can neither clobber those fields +nor stop them propagating -- it relays them untouched. + +KEEP IN SYNC WITH ``app/lib/services/meal_schedule_service.dart``. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timezone +import json +import logging + +from diet_guard._constants import MEAL_SCHEDULE_FILE +from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule + +_logger = logging.getLogger(__name__) + +_FILE_VERSION = 1 + +# The effective-from date a seed uses, so the pre-history schedule covers every +# day that was ever logged. Any real date is >= this. +EPOCH_DAY = "1970-01-01" + +_EPOCH_ISO = "1970-01-01T00:00:00+00:00" + + +@dataclass(frozen=True) +class ScheduleEntry: + """One meal schedule and the date it started applying. + + Attributes: + effective_from: ``YYYY-MM-DD``; the first day this schedule applies to. + schedule: The eating window and meal count from that day onward. + edited_at: Local ISO-8601 timestamp of the edit that created it, used + to derive a deterministic Hlc for the sync merge. + """ + + effective_from: str + schedule: MealSchedule + edited_at: str + + +def entry_to_json(entry: ScheduleEntry) -> dict[str, object]: + """Return the wire/disk form of one entry's value.""" + return { + "f": entry.schedule.first, + "l": entry.schedule.last, + "n": entry.schedule.count, + "t": entry.edited_at, + } + + +def entry_from_json(effective_from: str, raw: object) -> ScheduleEntry | None: + """Return an entry parsed from its stored value, or None if unusable. + + Never raises: a malformed entry is skipped so one bad field from a peer + cannot take out the whole history. + """ + if not isinstance(raw, dict): + return None + first, last, count = raw.get("f"), raw.get("l"), raw.get("n") + if not ( + isinstance(first, int) and isinstance(last, int) and isinstance(count, int) + ): + return None + edited_at = raw.get("t") + return ScheduleEntry( + effective_from=effective_from, + # Normalising on the way in means a peer running a future version with + # a wider range cannot hand us a schedule we would derive differently. + schedule=MealSchedule(first, last, count).normalized(), + edited_at=edited_at if isinstance(edited_at, str) else _EPOCH_ISO, + ) + + +def history_from_json(raw: object) -> tuple[ScheduleEntry, ...]: + """Return the entries in a stored document, ascending by date. + + Anything unreadable yields no entries, which callers treat as "fall back + to the default schedule" -- the pre-feature behaviour. + """ + if not isinstance(raw, dict): + return () + entries = raw.get("e") + if not isinstance(entries, dict): + return () + parsed = [ + entry + for day, value in entries.items() + if isinstance(day, str) and (entry := entry_from_json(day, value)) is not None + ] + return tuple(sorted(parsed, key=lambda entry: entry.effective_from)) + + +def history_to_json(entries: tuple[ScheduleEntry, ...]) -> dict[str, object]: + """Return the on-disk document for ``entries``.""" + return { + "v": _FILE_VERSION, + "e": {entry.effective_from: entry_to_json(entry) for entry in entries}, + } + + +def schedule_for_day(entries: tuple[ScheduleEntry, ...], day: str) -> MealSchedule: + """Return the schedule in force on ``day``. + + Args: + entries: The history, ascending by ``effective_from``. + day: ``YYYY-MM-DD``. + + Returns: + The newest entry effective on or before ``day``, or the default when + the history says nothing about that day. + """ + applicable = [entry for entry in entries if entry.effective_from <= day] + return applicable[-1].schedule if applicable else DEFAULT_SCHEDULE + + +def upsert( + entries: tuple[ScheduleEntry, ...], + schedule: MealSchedule, + when: datetime, +) -> tuple[ScheduleEntry, ...]: + """Return ``entries`` with ``schedule`` effective from ``when``'s date. + + Re-editing on the same day replaces that day's entry rather than stacking + a second one, so the history holds at most one entry per date. + """ + day = when.date().isoformat() + kept = tuple(entry for entry in entries if entry.effective_from != day) + fresh = ScheduleEntry( + effective_from=day, + schedule=schedule.normalized(), + edited_at=when.isoformat(), + ) + return tuple(sorted((*kept, fresh), key=lambda entry: entry.effective_from)) + + +def seed_default(entries: tuple[ScheduleEntry, ...]) -> tuple[ScheduleEntry, ...]: + """Return ``entries`` with the default schedule pinned to the epoch. + + Recording today's schedule without this would leave every *earlier* day + with no applicable entry, and those days would then adopt whatever the + user just chose -- exactly the retroactive reclassification the history + exists to prevent. Callers must seed **before** recording today's value. + """ + if any(entry.effective_from == EPOCH_DAY for entry in entries): + return entries + seeded = ScheduleEntry( + effective_from=EPOCH_DAY, + schedule=DEFAULT_SCHEDULE, + edited_at=_EPOCH_ISO, + ) + return tuple(sorted((seeded, *entries), key=lambda entry: entry.effective_from)) + + +def read_raw_history() -> dict[str, object] | None: + """Return the on-disk document verbatim, or None if absent/corrupt. + + Never raises: an unreadable history means "use the default schedule", + which is the pre-feature behaviour. + """ + if not MEAL_SCHEDULE_FILE.exists(): + return None + try: + with MEAL_SCHEDULE_FILE.open() as handle: + document = json.load(handle) + except (OSError, json.JSONDecodeError): + _logger.debug("unreadable meal schedule; using the default") + return None + if not isinstance(document, dict): + return None + return document + + +def write_raw_history(document: dict[str, object]) -> None: + """Persist ``document`` verbatim, overwriting the schedule file.""" + MEAL_SCHEDULE_FILE.parent.mkdir(parents=True, exist_ok=True) + with MEAL_SCHEDULE_FILE.open("w") as handle: + json.dump(document, handle) + + +def load_entries() -> tuple[ScheduleEntry, ...]: + """Return the stored history, or empty if none has been written yet.""" + raw = read_raw_history() + return () if raw is None else history_from_json(raw) + + +def current_schedule() -> MealSchedule: + """Return the schedule in force today. + + This is the impure edge every :mod:`diet_guard._slots` caller resolves + through; the slot arithmetic itself stays a pure function of its + arguments. + """ + today = datetime.now(tz=timezone.utc).astimezone().date().isoformat() + return schedule_for_day(load_entries(), today) + + +def record_schedule_change( + schedule: MealSchedule, *, when: datetime | None = None +) -> None: + """Record a schedule edit, effective from the day it was made. + + Seeds the default at the epoch first, so past days keep the four-meal + schedule they were actually judged against. + """ + moment = when if when is not None else datetime.now(tz=timezone.utc).astimezone() + entries = seed_default(load_entries()) + write_raw_history(history_to_json(upsert(entries, schedule, moment))) diff --git a/diet_guard/_slots.py b/diet_guard/_slots.py index 49ba625..7b4fcd5 100644 --- a/diet_guard/_slots.py +++ b/diet_guard/_slots.py @@ -1,66 +1,68 @@ """Pure meal-slot arithmetic for the diet_guard gate. This module is deliberately I/O-free and clock-free: every function is a total -function of its ``now`` argument and the configured slot constants, so the -fiddly time-of-day edges (07:59 vs 08:00, the 20:00->22:00 tail, the midnight -reset) are exhaustively unit-testable without mocking the filesystem or the -wall clock. The stateful "which slots have I actually logged?" question lives -in :mod:`diet_guard._state`; the two are composed in -:mod:`diet_guard._gate`. +function of its ``now`` and ``schedule`` arguments, so the fiddly time-of-day +edges (07:59 vs 08:00, the 20:00->22:00 tail, the midnight reset) are +exhaustively unit-testable without mocking the filesystem or the wall clock. +The stateful "which slots have I actually logged?" question lives in +:mod:`diet_guard._state`; the two are composed in :mod:`diet_guard._gate`. A "slot" is simply the integer hour at which a meal checkpoint opens (08, 12, -16, 20). A slot is *elapsed* once its hour has arrived and we are still inside -the daily enforcement window; an elapsed slot with no logged meal is what makes -the gate fire. +16, 20 by default). A slot is *elapsed* once its hour has arrived and we are +still inside the daily enforcement window; an elapsed slot with no logged meal +is what makes the gate fire. + +``schedule`` is a required argument on every function here, deliberately: it +used to be read from module constants, and a default would let a call site that +was missed during a refactor keep deriving the old fixed hours on one device +only. That is the split brain this design exists to prevent -- a slot one +device offers and the other does not is a checkpoint that can never be +satisfied. Making it required lets mypy enumerate the call sites instead. +Callers resolve the value at the impure edge, mirroring how +:mod:`diet_guard._daystatus` takes an explicit budget schedule. """ from __future__ import annotations from typing import TYPE_CHECKING -from diet_guard._constants import ( - GATE_DAY_START_HOUR, - GATE_EATING_END_HOUR, - GATE_SLOT_INTERVAL_HOURS, -) - if TYPE_CHECKING: from datetime import datetime + from diet_guard._meal_schedule import MealSchedule + _HOURS_PER_DAY = 24 -def day_slots() -> tuple[int, ...]: - """Return the fixed meal-slot hours for a day, e.g. ``(8, 12, 16, 20)``. +def day_slots(schedule: MealSchedule) -> tuple[int, ...]: + """Return the meal-slot hours for a day, e.g. ``(8, 12, 16, 20)``. - Slots run from the day-start hour, every interval, up to (but not past) the - overnight cutoff. Derived from the constants so changing the cadence in one - place reshapes the whole schedule. + Args: + schedule: The eating window and meal count to derive slots from. Returns: The slot hours in ascending order. """ - return tuple( - range(GATE_DAY_START_HOUR, GATE_EATING_END_HOUR, GATE_SLOT_INTERVAL_HOURS) - ) + return schedule.slots() -def within_enforcement_window(now: datetime) -> bool: +def within_enforcement_window(now: datetime, schedule: MealSchedule) -> bool: """Return True if ``now`` is inside the daily slot-enforcement window. - Outside ``[day_start, eating_end)`` the gate never fires, so unlogged slots - lapse overnight instead of trapping you at 03:00. + Outside ``[first_slot, enforcement_end)`` the gate never fires, so unlogged + slots lapse overnight instead of trapping you at 03:00. Args: now: Reference local time. + schedule: The schedule in force for that day. Returns: True if slot enforcement is active at ``now``. """ - return GATE_DAY_START_HOUR <= now.hour < GATE_EATING_END_HOUR + return schedule.slots()[0] <= now.hour < schedule.enforcement_end_hour -def elapsed_slots(now: datetime) -> tuple[int, ...]: +def elapsed_slots(now: datetime, schedule: MealSchedule) -> tuple[int, ...]: """Return today's slots whose hour has arrived as of ``now``. Empty outside the enforcement window (before the first slot, or after the @@ -68,29 +70,33 @@ def elapsed_slots(now: datetime) -> tuple[int, ...]: Args: now: Reference local time. + schedule: The schedule in force for that day. Returns: The elapsed slot hours, ascending (possibly empty). """ - if not within_enforcement_window(now): + if not within_enforcement_window(now, schedule): return () - return tuple(slot for slot in day_slots() if slot <= now.hour) + return tuple(slot for slot in day_slots(schedule) if slot <= now.hour) -def missing_slots(now: datetime, logged: set[int]) -> tuple[int, ...]: +def missing_slots( + now: datetime, logged: set[int], schedule: MealSchedule +) -> tuple[int, ...]: """Return elapsed slots that have not been satisfied by a logged meal. Args: now: Reference local time. logged: The set of slot hours already covered by today's log. + schedule: The schedule in force for that day. Returns: The unsatisfied elapsed slot hours, ascending (empty == nothing due). """ - return tuple(slot for slot in elapsed_slots(now) if slot not in logged) + return tuple(slot for slot in elapsed_slots(now, schedule) if slot not in logged) -def current_slot(now: datetime) -> int | None: +def current_slot(now: datetime, schedule: MealSchedule) -> int | None: """Return the most recent elapsed slot as of ``now``, or None. Reports the schedule position only. Tagging a *log* with a slot goes @@ -99,37 +105,42 @@ def current_slot(now: datetime) -> int | None: Args: now: Reference local time. + schedule: The schedule in force for that day. Returns: The latest elapsed slot hour, or None when none have elapsed yet. """ - elapsed = elapsed_slots(now) + elapsed = elapsed_slots(now, schedule) return elapsed[-1] if elapsed else None -def slot_for_log(now: datetime) -> int: +def slot_for_log(now: datetime, schedule: MealSchedule) -> int: """Return the slot a meal logged at ``now`` should be attributed to. CLAMP RULE (keep byte-identical with ``slot.dart``'s ``slotForLog``): before - the first window, clamp to the first slot; after the last window, clamp to - the last slot; behaviour inside a window is unchanged. + the first slot, clamp to the first slot; after the enforcement window ends, + clamp to the last slot; behaviour inside a window is unchanged. Both + languages must reach each answer by the *same* branch, not merely agree on + the value -- ``test_slots.py`` sweeps every hour of the day against several + schedules for exactly that reason. Unlike :func:`current_slot` this never returns None, which is the point: an off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30 still left the gate firing for that checkpoint. Attribution is deliberately separate from :func:`elapsed_slots`/:func:`missing_slots` -- widening *those* - would instead make every slot fall due at 23:00. + would instead make every slot fall due at the end of the day. Args: now: Reference local time. + schedule: The schedule in force for that day. Returns: The slot hour to tag the log with. """ - slots = day_slots() - if now.hour < GATE_DAY_START_HOUR: + slots = day_slots(schedule) + if now.hour < slots[0]: return slots[0] - current = current_slot(now) + current = current_slot(now, schedule) return current if current is not None else slots[-1] diff --git a/diet_guard/tests/conftest.py b/diet_guard/tests/conftest.py index 1ca0dd3..5593f0c 100644 --- a/diet_guard/tests/conftest.py +++ b/diet_guard/tests/conftest.py @@ -105,6 +105,10 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]: "diet_guard._budget_history.BUDGET_HISTORY_FILE", tmp_path / ".budget_history", ), + patch( + "diet_guard._meal_schedule_store.MEAL_SCHEDULE_FILE", + tmp_path / ".meal_schedule", + ), patch( "diet_guard._state.FOOD_LOG_FILE", tmp_path / "food_log.json", diff --git a/diet_guard/tests/test_meal_schedule_store.py b/diet_guard/tests/test_meal_schedule_store.py new file mode 100644 index 0000000..64e0c1b --- /dev/null +++ b/diet_guard/tests/test_meal_schedule_store.py @@ -0,0 +1,196 @@ +"""Tests for the meal-schedule history and its on-disk form. + +Mirrors ``test_budget_history*.py``: the two histories exist for the same +reason and share a shape, so a change to one usually wants the same change +here. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import TYPE_CHECKING +from unittest.mock import patch + +from diet_guard import _meal_schedule_store as store +from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule + +if TYPE_CHECKING: + from pathlib import Path + + +def _at(day: str) -> datetime: + """Return midnight UTC on ``day`` (``YYYY-MM-DD``).""" + return datetime.fromisoformat(f"{day}T00:00:00+00:00") + + +class TestEntryJson: + """One entry's wire/disk representation.""" + + def test_round_trips(self) -> None: + """Encoding then decoding preserves the schedule and the stamp.""" + entry = store.ScheduleEntry( + effective_from="2026-08-16", + schedule=MealSchedule(8, 20, 5), + edited_at="2026-08-16T12:00:00+00:00", + ) + assert store.entry_from_json("2026-08-16", store.entry_to_json(entry)) == entry + + def test_normalizes_on_the_way_in(self) -> None: + """A peer's out-of-range schedule is clamped, not trusted verbatim.""" + entry = store.entry_from_json("2026-08-16", {"f": 8, "l": 20, "n": 99}) + assert entry is not None + assert entry.schedule == MealSchedule(8, 20, 6) + + def test_missing_timestamp_falls_back_to_the_epoch(self) -> None: + """An entry with no stamp still parses, losing only its ordering.""" + entry = store.entry_from_json("2026-08-16", {"f": 8, "l": 20, "n": 4}) + assert entry is not None + assert entry.edited_at == "1970-01-01T00:00:00+00:00" + + def test_rejects_a_non_mapping(self) -> None: + """A scalar where a record belongs is skipped, not raised on.""" + assert store.entry_from_json("2026-08-16", "nonsense") is None + + def test_rejects_non_integer_fields(self) -> None: + """A malformed field skips just that entry.""" + assert store.entry_from_json("2026-08-16", {"f": "8", "l": 20, "n": 4}) is None + + +class TestHistoryJson: + """The whole-document form.""" + + def test_round_trips_and_sorts(self) -> None: + """Entries come back ascending regardless of insertion order.""" + entries = ( + store.ScheduleEntry("2026-08-16", MealSchedule(8, 20, 5), "t1"), + store.ScheduleEntry("2026-01-01", DEFAULT_SCHEDULE, "t0"), + ) + parsed = store.history_from_json(store.history_to_json(entries)) + assert [entry.effective_from for entry in parsed] == [ + "2026-01-01", + "2026-08-16", + ] + + def test_unreadable_documents_yield_nothing(self) -> None: + """Anything unusable degrades to "no history", never an exception.""" + assert store.history_from_json("nonsense") == () + assert store.history_from_json({"e": "nonsense"}) == () + assert store.history_from_json({}) == () + + def test_skips_only_the_bad_entry(self) -> None: + """One corrupt field from a peer cannot take out the whole history.""" + parsed = store.history_from_json( + {"e": {"2026-01-01": {"f": 8, "l": 20, "n": 4}, "2026-02-01": 7}} + ) + assert [entry.effective_from for entry in parsed] == ["2026-01-01"] + + +class TestScheduleForDay: + """Resolving the schedule that applied on a given day.""" + + def test_defaults_when_the_history_is_silent(self) -> None: + """A day before any entry uses the default, not the newest entry.""" + entries = (store.ScheduleEntry("2026-08-16", MealSchedule(8, 20, 5), "t"),) + assert store.schedule_for_day(entries, "2026-08-15") == DEFAULT_SCHEDULE + + def test_uses_the_newest_applicable_entry(self) -> None: + """The latest entry effective on or before the day wins.""" + entries = ( + store.ScheduleEntry("2026-01-01", MealSchedule(8, 20, 4), "t0"), + store.ScheduleEntry("2026-08-16", MealSchedule(8, 20, 5), "t1"), + ) + assert store.schedule_for_day(entries, "2026-08-16") == MealSchedule(8, 20, 5) + assert store.schedule_for_day(entries, "2026-05-01") == MealSchedule(8, 20, 4) + + +class TestUpsert: + """Appending an edit to the history.""" + + def test_appends_a_new_day(self) -> None: + """An edit on a fresh day adds an entry.""" + entries = store.upsert((), MealSchedule(8, 20, 5), _at("2026-08-16")) + assert len(entries) == 1 + assert entries[0].effective_from == "2026-08-16" + + def test_replaces_a_same_day_re_edit(self) -> None: + """Editing twice in one day leaves one entry, not two.""" + first = store.upsert((), MealSchedule(8, 20, 5), _at("2026-08-16")) + second = store.upsert(first, MealSchedule(9, 21, 3), _at("2026-08-16")) + assert len(second) == 1 + assert second[0].schedule == MealSchedule(9, 21, 3) + + +class TestSeedDefault: + """Grandfathering days that predate the first edit.""" + + def test_pins_the_default_at_the_epoch(self) -> None: + """Seeding makes every earlier day resolve to the old schedule.""" + seeded = store.seed_default(()) + assert seeded[0].effective_from == store.EPOCH_DAY + assert seeded[0].schedule == DEFAULT_SCHEDULE + + def test_is_idempotent(self) -> None: + """Seeding twice does not stack a second epoch entry.""" + assert store.seed_default(store.seed_default(())) == store.seed_default(()) + + +class TestPersistence: + """The on-disk file, through the conftest-redirected path.""" + + def test_absent_file_reads_as_no_history(self) -> None: + """A device that has never edited contributes nothing.""" + assert store.read_raw_history() is None + assert store.load_entries() == () + + def test_round_trips_through_disk(self) -> None: + """What is written is what is read back.""" + store.record_schedule_change(MealSchedule(8, 20, 5), when=_at("2026-08-16")) + assert store.schedule_for_day( + store.load_entries(), "2026-08-16" + ) == MealSchedule(8, 20, 5) + + def test_recording_grandfathers_earlier_days(self) -> None: + """Switching to five meals leaves past days on the four-meal schedule. + + This is the whole point of the history: without the epoch seed, every + past day would adopt the schedule chosen today and look like it had + missed a checkpoint. + """ + store.record_schedule_change(MealSchedule(8, 20, 5), when=_at("2026-08-16")) + entries = store.load_entries() + assert store.schedule_for_day(entries, "2020-01-01") == DEFAULT_SCHEDULE + assert store.schedule_for_day(entries, "2026-08-16") == MealSchedule(8, 20, 5) + + def test_corrupt_file_degrades_to_the_default(self) -> None: + """Unparsable JSON is treated as "no history", never a crash.""" + store.MEAL_SCHEDULE_FILE.parent.mkdir(parents=True, exist_ok=True) + store.MEAL_SCHEDULE_FILE.write_text("{not json") + assert store.read_raw_history() is None + assert store.current_schedule() == DEFAULT_SCHEDULE + + def test_non_mapping_document_degrades(self) -> None: + """A JSON array where an object belongs is ignored.""" + store.MEAL_SCHEDULE_FILE.parent.mkdir(parents=True, exist_ok=True) + store.MEAL_SCHEDULE_FILE.write_text("[1, 2]") + assert store.read_raw_history() is None + + def test_unreadable_file_degrades(self, tmp_path: Path) -> None: + """An OSError on read is swallowed like a parse failure.""" + directory = tmp_path / "not-a-file" + directory.mkdir() + # Patched rather than assigned: a bare assignment would outlive this + # test and silently redirect the module for everything after it. + with patch.object(store, "MEAL_SCHEDULE_FILE", directory): + assert store.read_raw_history() is None + + def test_current_schedule_defaults_before_any_edit(self) -> None: + """A fresh install behaves exactly as it did before this feature.""" + assert store.current_schedule() == DEFAULT_SCHEDULE + + def test_record_defaults_to_now(self) -> None: + """Omitting ``when`` stamps the edit with the current time.""" + store.record_schedule_change(MealSchedule(7, 19, 3)) + today = datetime.now(tz=timezone.utc).astimezone().date().isoformat() + assert store.schedule_for_day(store.load_entries(), today) == MealSchedule( + 7, 19, 3 + ) diff --git a/diet_guard/tests/test_slots.py b/diet_guard/tests/test_slots.py index e97d477..5a2bcc5 100644 --- a/diet_guard/tests/test_slots.py +++ b/diet_guard/tests/test_slots.py @@ -1,13 +1,16 @@ """Tests for _slots.py — pure meal-slot arithmetic. -Every function is a total function of ``now`` and the slot constants, so the -time-of-day edges are exercised directly with fixed ``datetime`` values. +Every function is a total function of ``now`` and an explicit schedule, so the +time-of-day edges are exercised directly with fixed ``datetime`` values. The +assertions below use ``DEFAULT_SCHEDULE`` (08/12/16/20, cutoff 22:00) so they +still pin the behaviour these functions had when those hours were hardcoded. """ from __future__ import annotations from datetime import datetime, timezone +from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule from diet_guard._slots import ( current_slot, day_slots, @@ -29,7 +32,7 @@ class TestDaySlots: def test_default_schedule(self) -> None: """Slots open every 4h from 08:00 up to (not past) the 22:00 cutoff.""" - assert day_slots() == (8, 12, 16, 20) + assert day_slots(DEFAULT_SCHEDULE) == (8, 12, 16, 20) class TestEnforcementWindow: @@ -37,19 +40,19 @@ class TestEnforcementWindow: def test_before_window(self) -> None: """An hour before the first slot is outside the window.""" - assert not within_enforcement_window(_at(7)) + assert not within_enforcement_window(_at(7), DEFAULT_SCHEDULE) def test_first_slot_is_inside(self) -> None: """The day-start hour is inside (inclusive lower bound).""" - assert within_enforcement_window(_at(8)) + assert within_enforcement_window(_at(8), DEFAULT_SCHEDULE) def test_last_active_hour_inside(self) -> None: """21:00 is still inside; the cutoff is exclusive at 22:00.""" - assert within_enforcement_window(_at(21)) + assert within_enforcement_window(_at(21), DEFAULT_SCHEDULE) def test_cutoff_is_outside(self) -> None: """The cutoff hour itself is outside (exclusive upper bound).""" - assert not within_enforcement_window(_at(22)) + assert not within_enforcement_window(_at(22), DEFAULT_SCHEDULE) class TestElapsedSlots: @@ -57,23 +60,23 @@ class TestElapsedSlots: def test_empty_before_window(self) -> None: """Before the first slot, nothing has elapsed.""" - assert elapsed_slots(_at(7)) == () + assert elapsed_slots(_at(7), DEFAULT_SCHEDULE) == () def test_empty_after_cutoff(self) -> None: """After the overnight cutoff, slots lapse to empty.""" - assert elapsed_slots(_at(23)) == () + assert elapsed_slots(_at(23), DEFAULT_SCHEDULE) == () def test_first_slot_only(self) -> None: """At 08:00 exactly, only the 08:00 slot has elapsed.""" - assert elapsed_slots(_at(8)) == (8,) + assert elapsed_slots(_at(8), DEFAULT_SCHEDULE) == (8,) def test_midday(self) -> None: """At 13:00, the 08:00 and 12:00 slots have elapsed.""" - assert elapsed_slots(_at(13)) == (8, 12) + assert elapsed_slots(_at(13), DEFAULT_SCHEDULE) == (8, 12) def test_all_elapsed_late(self) -> None: """At 21:00, every slot for the day has elapsed.""" - assert elapsed_slots(_at(21)) == (8, 12, 16, 20) + assert elapsed_slots(_at(21), DEFAULT_SCHEDULE) == (8, 12, 16, 20) class TestMissingSlots: @@ -81,11 +84,11 @@ class TestMissingSlots: def test_none_missing_when_all_logged(self) -> None: """All elapsed slots logged -> nothing due.""" - assert missing_slots(_at(13), {8, 12}) == () + assert missing_slots(_at(13), {8, 12}, DEFAULT_SCHEDULE) == () def test_reports_unlogged(self) -> None: """Only the unlogged elapsed slots are returned, ascending.""" - assert missing_slots(_at(17), {8}) == (12, 16) + assert missing_slots(_at(17), {8}, DEFAULT_SCHEDULE) == (12, 16) class TestCurrentSlot: @@ -93,11 +96,11 @@ class TestCurrentSlot: def test_none_before_any_slot(self) -> None: """Before the first slot there is no current slot.""" - assert current_slot(_at(7)) is None + assert current_slot(_at(7), DEFAULT_SCHEDULE) is None def test_latest_elapsed(self) -> None: """At 13:00 the current slot is 12:00 (the latest elapsed).""" - assert current_slot(_at(13)) == 12 + assert current_slot(_at(13), DEFAULT_SCHEDULE) == 12 class TestSlotForLog: @@ -110,35 +113,69 @@ class TestSlotForLog: def test_before_the_first_window_clamps_to_the_first_slot(self) -> None: """An early breakfast counts toward 08:00 rather than nothing.""" - assert slot_for_log(_at(7)) == 8 + assert slot_for_log(_at(7), DEFAULT_SCHEDULE) == 8 def test_midnight_clamps_to_the_first_slot(self) -> None: """The small hours are still "before the first window".""" - assert slot_for_log(_at(0)) == 8 + assert slot_for_log(_at(0), DEFAULT_SCHEDULE) == 8 def test_first_slot_boundary_is_unchanged(self) -> None: """08:00 exactly is inside the window, so no clamp applies.""" - assert slot_for_log(_at(8)) == 8 + assert slot_for_log(_at(8), DEFAULT_SCHEDULE) == 8 def test_inside_the_window_matches_current_slot(self) -> None: """Within the window attribution is just the latest elapsed slot.""" - assert slot_for_log(_at(13)) == current_slot(_at(13)) == 12 + assert ( + slot_for_log(_at(13), DEFAULT_SCHEDULE) + == current_slot(_at(13), DEFAULT_SCHEDULE) + == 12 + ) def test_last_in_window_hour_is_unchanged(self) -> None: """21:59 is still inside the window and lands on 20:00.""" - assert slot_for_log(_at(21)) == 20 + assert slot_for_log(_at(21), DEFAULT_SCHEDULE) == 20 def test_after_the_last_window_clamps_to_the_last_slot(self) -> None: """A late dinner counts toward 20:00 rather than nothing.""" - assert slot_for_log(_at(22)) == 20 + assert slot_for_log(_at(22), DEFAULT_SCHEDULE) == 20 def test_late_evening_clamps_to_the_last_slot(self) -> None: """23:00 clamps the same way as the 22:00 boundary.""" - assert slot_for_log(_at(23)) == 20 + assert slot_for_log(_at(23), DEFAULT_SCHEDULE) == 20 def test_never_returns_none(self) -> None: """Every hour of the day attributes to some slot.""" - assert all(slot_for_log(_at(hour)) in day_slots() for hour in range(24)) + assert all( + slot_for_log(_at(hour), DEFAULT_SCHEDULE) in day_slots(DEFAULT_SCHEDULE) + for hour in range(24) + ) + + def test_clamps_across_configured_schedules(self) -> None: + """The clamp rule holds for any schedule, not just the default. + + Sweeps every hour against several windows. ``slot.dart`` runs the + identical sweep: the two must agree on every cell, because a device + that attributes a meal to a different slot than its peer leaves the + other device's checkpoint permanently unsatisfied. + """ + for schedule in ( + DEFAULT_SCHEDULE, + MealSchedule(8, 20, 5), + MealSchedule(6, 22, 6), + MealSchedule(0, 23, 2), + MealSchedule(10, 14, 3), + ): + slots = day_slots(schedule) + for hour in range(24): + attributed = slot_for_log(_at(hour), schedule) + assert attributed in slots + if hour < slots[0]: + assert attributed == slots[0] + elif hour >= schedule.enforcement_end_hour: + assert attributed == slots[-1] + else: + # Inside the window: the most recent slot that has opened. + assert attributed == max(s for s in slots if s <= hour) class TestSlotLabel: @@ -151,3 +188,33 @@ class TestSlotLabel: def test_evening(self) -> None: """A two-digit hour formats plainly.""" assert slot_label(20) == "20:00" + + +class TestConfiguredSchedules: + """Slot arithmetic against schedules other than the default.""" + + def test_five_meals_shifts_the_checkpoints(self) -> None: + """The user's example schedule drives elapsed/missing correctly.""" + schedule = MealSchedule(8, 20, 5) + assert day_slots(schedule) == (8, 11, 14, 17, 20) + assert elapsed_slots(_at(14), schedule) == (8, 11, 14) + assert missing_slots(_at(14), {8, 11}, schedule) == (14,) + + def test_enforcement_follows_the_last_meal(self) -> None: + """A window ending at 18:00 stops enforcing at 20:00, not 22:00.""" + schedule = MealSchedule(8, 18, 3) + assert within_enforcement_window(_at(19), schedule) + assert not within_enforcement_window(_at(20), schedule) + assert elapsed_slots(_at(20), schedule) == () + + def test_midnight_first_slot_is_not_treated_as_absent(self) -> None: + """Slot 0 is a real slot, not a falsy stand-in for "nothing elapsed". + + Guards the ``or`` bug this used to have in ``_gatelock._pending_slots``: + ``current_slot(...) or day_slots()[0]`` silently swallowed slot 0. + """ + schedule = MealSchedule(0, 12, 3) + assert day_slots(schedule) == (0, 6, 12) + assert current_slot(_at(0), schedule) == 0 + assert current_slot(_at(0), schedule) is not None + assert slot_for_log(_at(0), schedule) == 0