Compare commits

...

10 Commits

Author SHA1 Message Date
b8b432bee4 Add dopamine-ux session prompt to prompts/
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Copy of the canonical prompt in ~/utils/dopamine-ux/, distributed here so the
repo can be opened and the prompt run directly. Derived from a survey of this
repo plus "The Dopamine Architecture" (london-post.co.uk).

The prompt states its own completion protocol: when finished, the session
deletes this copy in the implementation commit and logs a DONE row in
~/utils/dopamine-ux/00-INDEX.md. Partial completion is never recorded as done.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FdApz7EZ1zDfvtvvi1idDv
2026-08-16 21:13:10 +02:00
d02f6aa6e8 Rebuild the slot row when settings changes the schedule
Found on the phone, not in the suite. Setting five meals updated the settings
preview and fired a reminder for the new 14:00 checkpoint, while the slot row
behind them kept showing the old 08/12/16/20 until the app was restarted:
onOpenSettings pushed the route without awaiting the pop, so the log screen
never rebuilt against the schedule the user had just chosen.

It now awaits and calls onScheduleMayHaveChanged, which re-reads the logged
slots and re-derives the selected slot -- the hour it pointed at may not be a
checkpoint at all any more. The other three destinations still fire and
forget, since none of them can change what this screen renders.

The regression test was confirmed to fail against the pre-fix behaviour
("Found 0 widgets with text 11:00") rather than passing vacuously.

Both files crossed the 250-line cap with the addition, so the hook moved to
log_meal_sync_mixin.dart -- which already owns refreshSlots and loggedSlots
and is the better home regardless -- and the new test into its own file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 15:12:57 +02:00
ed6d283ff8 Document the configurable meal schedule
The rules that are expensive to rediscover: integer-only arithmetic and why
(Python and Dart round differently), the count clamp and why a duplicate slot
hour is worse than it looks, the last+2h cutoff and its midnight clamp, and
the required-argument decision in _slots.py / slot.dart.

Split into docs/meal-schedule.md rather than inlined -- CLAUDE.md hit 276
lines against the 250 cap, the same split the Flutter rules already use.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 15:03:59 +02:00
c0564c05a2 Let the PC gate set the eating window and meal count
The second edit surface, so the schedule is editable from either device the
way the budget already is. A row on the History tab beside the budget row,
with the same Edit/Save toggle: first hour, last hour, meals per day, and the
derived checkpoint times underneath so the effect of a change is visible
before it is saved.

Validated rather than clamped. MealSchedule.normalized() would happily turn
"20 to 8" into a two-meal day ending at 09:00, which is a sensible defence
against a peer's corrupt sync data and a terrible response to a typo at the
keyboard. Each rejection says what is wrong and leaves the row in edit mode so
the value can be corrected instead of silently becoming a different schedule.
The narrow-window case has its own message, because that one is genuinely
non-obvious: six meals between 08:00 and 11:00 would round two checkpoints
onto the same hour, and a duplicate slot silently drops one.

Three structural notes:

- The row's widgets are their own module. _gatelock_calendar_widgets.py was at
  216 of the 250-line cap and is now 233; adding the row inline would have
  breached it.
- The five new StringVars are grouped in a ScheduleVars dataclass rather than
  flattened onto CalendarVars, which pylint flagged at 11 attributes. Grouping
  two unrelated concerns separately is the better shape anyway.
- _gate_fixtures.py's _GATE_TK_MODULES is a hand-listed patch target, so both
  new modules are registered there. Left out, they build real tk widgets under
  a fake parent -- which is how it failed the first time, loudly, rather than
  silently opening a window.

785 tests, 100% branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 15:02:35 +02:00
da8822006f Let the phone set the eating window and meal count
The first edit surface, landing after the sync layer so a schedule set here
reaches the PC rather than leaving the two devices deriving different slots.

Three dropdowns -- first meal, last meal, meals per day -- and a live preview
of the checkpoints they derive. Setting 08:00, 20:00 and 5 shows
08:00 · 11:00 · 14:00 · 17:00 · 20:00, which is asserted in the screen test
rather than only in the model's.

Dropdowns rather than showTimePicker: that returns a TimeOfDay with minutes,
and slots are whole hours on both devices by design. They also make the
invalid states unrepresentable instead of validated -- "last meal" offers only
hours after "first", and "meals per day" only counts the window has whole
hours for. MealSchedule.normalized() still clamps, but that is the defence
against corrupt synced data, not the input contract.

Saving re-runs the due-slot check, because reminder ids are slot hours: a
schedule change orphans the ids it no longer contains, and waiting for the
next background tick would leave a stale nag on screen for up to 15 minutes.

The UI is a `part` mixin like settings_kcal_goal.dart -- settings_screen.dart
was at 238 of the 250-line cap and is now at 247.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:56:12 +02:00
24dbffc432 Sync the meal schedule as sched: fields on the budget record
Without this the schedule would be device-local, which is the failure this
whole feature has to avoid: the phone sets five meals, the PC still derives
four, and the PC's gate nags for a 12:00 checkpoint the phone never offered
and can never satisfy. So sync lands before either edit surface, not after.

The history rides the existing `budget` CRDT record as one
`sched:<YYYY-MM-DD>` field per entry, exactly like the budget's own `hist:`
fields. merge_record is per-field LWW over the *union* of field names and both
devices push the merged record, so a device that predates the feature relays
the fields untouched -- no coordinated release. There is a test for precisely
that: merging our push with a budget-only peer keeps both schedule entries.

Verified the two languages agree on the wire, not just in their own suites --
Python and Dart both emit
  {"sched:1970-01-01":{"f":8,"l":20,"n":4},"sched:2026-08-16":{"f":8,"l":20,"n":5}}
The Hlc is derived from the *parsed* timestamp on both sides, which matters
because the epoch fallback formats differently in each language
(1970-01-01T00:00:00+00:00 vs ...000Z) and a string comparison would diverge.

Two guards worth naming:

- A device with no history contributes no `sched:` fields at all, so an unset
  default can never outrank a peer's real schedule; and an empty merge result
  is never written back, so a pre-feature peer cannot erase a real history.
- Dart's `_syncBudget` synthesises a local record when the schedule has been
  edited but the budget never has -- `budgetToLog(null, ...)` returns an empty
  Log and would otherwise drop the schedule fields too. Its budget value
  carries an epoch stamp, so it loses every LWW race against a real edit.

sync_merge/_schedule.py and sync_merge_schedule.dart are separate modules
rather than additions to the budget adapters, which were at 186 and 170 lines
against the 250 cap. Each declares its own record-id constant so the Dart
pair does not import each other.

772 Python tests at 100% branch coverage, 619 Dart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:49:08 +02:00
d2e62bf210 Read the meal schedule from a forward-only history (Dart)
The phone/desktop half of the previous commit, so both devices now derive
their slots the same way. Still no edit surface, so `MealScheduleService`
returns the default and the derived hours are unchanged at 08/12/16/20.

`slot.dart` takes the schedule as a required argument, mirroring `_slots.py`,
and `slot_test.dart` gains the same every-hour x several-schedules sweep the
Python suite runs. That sweep is the contract: the two must agree on which
checkpoint a meal satisfies for every cell, not merely on the endpoints.

Also fixes a real bug this feature would otherwise have shipped on top of.
`syncToSlots` used the slot hour as the notification id but only cancelled ids
in the *current* schedule, so changing 08/12/16/20 -> 08/11/14/17/20 would
leave ids 12 and 16 posted with nothing that could ever cancel them: permanent
reminders for checkpoints that no longer exist. It now sweeps the whole 0..23
id space. The regression test was confirmed to fail against the old loop
(4 cancels vs 24) rather than passing vacuously.

MealScheduleService.current degrades to the default when the singleton is
absent, so `due_slot_check` deliberately does not init() it -- that would
reach path_provider from widget tests and from the WorkManager isolate before
main() runs. main.dart owns the real init, and background_sync_service.dart
does its own, since a fresh isolate has its own static state and would
otherwise nag against the default four meals.

609 Dart tests, 761 Python, both suites green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:41:37 +02:00
2bdb7925a8 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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:28:22 +02:00
83c3030b55 Derive meal slots from an eating window and a meal count
First step of the configurable meal schedule: the pure arithmetic, in both
languages, with nothing wired to it yet. MealSchedule(8, 20, 5) gives
08, 11, 14, 17, 20; the default MealSchedule(8, 20, 4) reproduces the hours
that are currently hardcoded, so nothing changes behaviour until a user picks
something else.

Two properties are load-bearing and both are tested rather than asserted in
prose:

Integer arithmetic only, no floats and no round(). Python's round() is
banker's (round(2.5) == 2) and Dart's is half-away-from-zero
(2.5.round() == 3), so a floating-point derivation would silently disagree
across devices -- and a slot one device offers but the other does not is a
checkpoint that can never be satisfied, i.e. a permanent lock. The shared
vector table plus an identical 6912-case sweep in both suites is what catches
that class of bug before it reaches a device.

Counts are clamped to the window width rather than rejected. A narrow window
(08-12 across 6 meals) would otherwise repeat an hour -- 8, 9, 10, 10, 11, 12
-- and slot hours are used as set members, map keys and notification ids, so a
repeat silently drops a checkpoint. Clamping also means the two languages
cannot disagree about which inputs are errors.

The enforcement cutoff is now derived as last + 2h (clamped to midnight)
rather than sharing the constant that also bounded the slot range. The clamp
matters: 23:00 + 2 = 25 would make `hour < cutoff` vacuously true and the
window would never close.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:21:12 +02:00
cbbebee79b Pin meal pills to one row; drop the "Logged" restatement
Three independent cleanups ahead of the configurable meal schedule.

Pills: the row was a `Wrap`, so pills dropped onto a second line as soon as
they outgrew the width -- which they do even at four. Measured: a logged chip
is ~124px at Material defaults, so four need 522px against ~330px of phone
width. Now a `FittedBox(scaleDown)` over a `Row`, which scales the row down
uniformly, plus compact chip density so there is less to scale away.

A `Row` of `Expanded` children was the obvious alternative and is wrong: it
imposes a tight width, and a Chip narrower than avatar+padding+label clips its
label rather than shrinking -- measured at 10px per label, about one character,
while throwing no overflow error. The new regression test therefore asserts
both a shared baseline and a legible label width; it was confirmed to fail on
the old `Wrap` ("chip wrapped to a second line at 320.0") rather than passing
vacuously.

Card: the `Logged "<meal>".` line restated the description the user had just
typed. Removed, along with `TodayProgress.justLogged`, which nothing else read.
The kcal position, macros and streak stay.

refactor_claude_todo.md: the 250-line file-splitting refactor it tracked is
done -- `scripts/check_file_length.sh --all` exits 0 and an independent sweep
finds nothing over the cap. DESIGN_AUDIT_TODO.md is a separate, still-open
effort and stays.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:18:39 +02:00
64 changed files with 3860 additions and 331 deletions

View File

@ -1,7 +1,8 @@
# CLAUDE.md — diet_guard
A log-to-unlock gate. Every ~30 min `diet-guard-gate.timer` checks whether a
meal slot (08:00, 12:00, 16:00, 20:00) elapsed unlogged; if so it opens a
meal slot (08:00, 12:00, 16:00, 20:00 by default — the schedule is
user-configurable, see below) elapsed unlogged; if so it opens a
fullscreen Tk window that blocks the desktop until the user logs what they
ate. It also tracks a daily calorie/macro budget, seeded from biometrics at
`init` and freely editable afterward on either device. A History tab
@ -166,6 +167,16 @@ changing either hides the entire local food log).
is `diet-guard-gate.timer`.
- Never run `flutter create --platforms linux` in `app/`.
## The meal schedule
The slot hours are user-configurable: a first meal, a last meal, and how
many meals fall between them, evenly divided. Default `(8, 20, 4)` is the
old hardcoded 08/12/16/20. Four load-bearing rules (integer-only
arithmetic, whole-hour slots, the count clamp, the `last + 2h` cutoff), the
forward-only history, and the two edit surfaces are documented in
[docs/meal-schedule.md](docs/meal-schedule.md) — read it before touching
`_slots.py` / `slot.dart`.
## Averages (`_averages.py` / `average_service.dart`)
Three load-bearing rules; changing any silently changes what "under budget"
@ -187,9 +198,15 @@ phone show both.
## Do NOT
- Don't relax the meal-slot logic without re-reading `docs/design.md`. The
off-hours clamp in `slot_for_log`/`slotForLog` (before 08:00 → 08:00, after
22:00 → 20:00) must stay byte-identical across Python and Dart; do NOT widen
`elapsed_slots`, which would make every slot fall due at 23:00.
off-hours clamp in `slot_for_log`/`slotForLog` (before the first slot → the
first slot, after the enforcement window → the last slot) must stay
byte-identical across Python and Dart; do NOT widen `elapsed_slots`, which
would make every slot fall due at the end of the day.
- Don't reintroduce floating point into the slot derivation. Python's `round`
is banker's (`round(2.5) == 2`), Dart's is half-away-from-zero
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
and a slot one device offers while the other does not is a checkpoint that
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
- Don't re-add the meal builder, "repeat last meal", the reward prompt, or
**meal photos** — all removed deliberately, enforced by
`app/test/repo_invariants_test.dart`. Photos also took `image_picker`, the

View File

@ -2,7 +2,6 @@
/// background due-slot check, then shows the primary meal-logging screen.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -11,6 +10,7 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/ui/theme.dart';
@ -24,6 +24,7 @@ Future<void> main() async {
await LogStorageService.init();
await AppSettingsService.init();
await BudgetHistoryService.init();
await MealScheduleService.init();
await FoodBankService.init();
final notifications = await NotificationService.init();
// Deliberately *not* awaited before the first frame: the browser's

View File

@ -0,0 +1,154 @@
/// The user's eating window and meal count, and the slot hours they imply.
///
/// A schedule is three numbers -- the first meal hour, the last meal hour, and
/// how many meals fall between them inclusive -- from which the intermediate
/// checkpoints are derived by even division. `MealSchedule(8, 20, 5)` yields
/// `[8, 11, 14, 17, 20]`.
///
/// This file is pure: no clock, no storage, no settings lookup. Persistence
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
/// that consumes a schedule lives in `models/slot.dart`.
///
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on
/// every input, because a device that derives different slots than its peer
/// nags for checkpoints the other never offers -- and a slot that can never be
/// satisfied is a permanent lock. Two rules make that agreement checkable:
///
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`)
/// while Python's is banker's rounding (`round(2.5) == 2`), so any
/// floating-point path is a latent cross-language split brain. `~/` here,
/// `//` there.
/// * **Clamp, don't reject.** Every out-of-range input is normalised to the
/// nearest legal schedule rather than throwing, so the two languages cannot
/// disagree about which inputs are errors.
library;
import 'package:flutter/foundation.dart';
/// Fewest meals a schedule may describe.
const int kMinMealCount = 2;
/// Most meals a schedule may describe.
///
/// Bounded by legibility, not nutrition: the pills that render these have to
/// stay readable on a phone at their widest (all-logged) size -- see
/// `test/widgets/slot_selector_row_test.dart`.
const int kMaxMealCount = 6;
/// Earliest hour a meal may be scheduled at.
const int kFirstHour = 0;
/// Latest hour a meal may be scheduled at.
const int kLastHour = 23;
/// Grace period after the final checkpoint, before the gate stops firing.
///
/// Deliberately a constant rather than the slot spacing: it is how long you
/// have to log a late dinner, which has nothing to do with how many meals you
/// eat. Tying it to the spacing would stretch the lockout window to midnight
/// at four meals, contradicting the "don't trap me overnight" intent.
const int kEnforcementTailHours = 2;
const int _hoursPerDay = 24;
int _clamp(int value, int low, int high) =>
value < low ? low : (value > high ? high : value);
/// An eating window and the number of meals inside it.
@immutable
class MealSchedule {
/// Creates a [MealSchedule].
const MealSchedule({
required this.first,
required this.last,
required this.count,
});
/// Hour of the first meal, 0-23.
final int first;
/// Hour of the last meal, strictly after [first].
final int last;
/// Total meals including both endpoints.
final int count;
/// Returns an equivalent schedule guaranteed to satisfy the invariants.
///
/// Ordering matters: [first] is clamped into the day, then [last] is clamped
/// to leave at least one hour of window, then [count] is clamped to the
/// window's width. That last clamp is the load-bearing one -- see [slots].
MealSchedule normalized() {
final normFirst = _clamp(first, kFirstHour, kLastHour - 1);
final normLast = _clamp(last, normFirst + 1, kLastHour);
// A window of N hours holds at most N+1 whole-hour checkpoints; asking for
// more would repeat an hour (see slots()).
final normCount = _clamp(
count,
kMinMealCount,
kMaxMealCount < normLast - normFirst + 1
? kMaxMealCount
: normLast - normFirst + 1,
);
return MealSchedule(first: normFirst, last: normLast, count: normCount);
}
/// Returns the meal-slot hours, ascending, with both endpoints exact.
///
/// Meals are spread evenly across the window and rounded to whole hours by
/// integer arithmetic: slot *i* is `first + (i*span + d ~/ 2) ~/ d` where
/// `span = last - first` and `d = count - 1`. The `d ~/ 2` term is a
/// round-half-up bias applied before the division, which is what keeps this
/// free of floating point.
///
/// Both endpoints land exactly on [first] and [last] by construction, so the
/// eating window is always honoured even when interior spacing must round.
///
/// The result is strictly ascending because [normalized] caps [count] at
/// `last - first + 1`. Without that cap a narrow window repeats an hour
/// (`08-12` with 6 meals would give `8, 9, 10, 10, 11, 12`), and since slot
/// hours are used as set members, map keys *and* notification ids, a repeat
/// silently drops a checkpoint.
List<int> slots() {
final schedule = normalized();
final span = schedule.last - schedule.first;
final divisions = schedule.count - 1;
return [
for (var index = 0; index < schedule.count; index++)
schedule.first + (index * span + divisions ~/ 2) ~/ divisions,
];
}
/// The hour at which slot enforcement stops for the day.
///
/// Clamped to the end of the day: a 23:00 last meal would otherwise put the
/// cutoff at 25, making `hour < cutoff` vacuously true so the enforcement
/// window never closes and the reminder can never stop firing.
int get enforcementEndHour {
final end = last + kEnforcementTailHours;
return end < _hoursPerDay ? end : _hoursPerDay;
}
@override
bool operator ==(Object other) =>
other is MealSchedule &&
other.first == first &&
other.last == last &&
other.count == count;
@override
int get hashCode => Object.hash(first, last, count);
@override
String toString() => 'MealSchedule($first-$last x$count)';
}
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement
/// closing at 22:00. Still what a device uses before the user has chosen
/// anything, so upgrading changes no behaviour.
const MealSchedule kDefaultSchedule = MealSchedule(
first: 8,
last: 20,
count: 4,
);

View File

@ -1,81 +1,81 @@
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py`.
///
/// Deliberately I/O-free and clock-free: every function is a total function
/// of its `now` argument and the fixed slot constants below, so the
/// time-of-day edges are exhaustively unit-testable without mocking the
/// wall clock. Shared between the in-app status bar and the background
/// notification check (Milestone 4), exactly like the Python original is
/// shared between the gate dashboard and the lock decision.
/// Deliberately I/O-free and clock-free: every function is a total function of
/// its `now` and `schedule` arguments, so the time-of-day edges are
/// exhaustively unit-testable without mocking the wall clock. Shared between
/// the in-app status row and the background notification check, exactly like
/// the Python original is shared between the gate dashboard and the lock
/// decision.
///
/// `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. Callers resolve the value at the impure edge, through
/// `MealScheduleService.current`.
library;
/// First slot hour of the day (08:00), mirrors `GATE_DAY_START_HOUR`.
const int gateDayStartHour = 8;
import 'package:diet_guard_app/models/meal_schedule.dart';
/// Hours between slots, mirrors `GATE_SLOT_INTERVAL_HOURS`.
const int gateSlotIntervalHours = 4;
/// Exclusive end of the enforcement window (22:00), mirrors
/// `GATE_EATING_END_HOUR`.
const int gateEatingEndHour = 22;
/// Returns the fixed meal-slot hours for a day, e.g. `(8, 12, 16, 20)`.
/// Returns the meal-slot hours for a day, e.g. `[8, 12, 16, 20]`.
///
/// Mirrors `_slots.day_slots`.
List<int> daySlots() {
final slots = <int>[];
for (
var hour = gateDayStartHour;
hour < gateEatingEndHour;
hour += gateSlotIntervalHours
) {
slots.add(hour);
}
return slots;
}
List<int> daySlots(MealSchedule schedule) => schedule.slots();
/// Returns true if [now] is inside the daily slot-enforcement window.
///
/// Mirrors `_slots.within_enforcement_window`.
bool withinEnforcementWindow(DateTime now) =>
now.hour >= gateDayStartHour && now.hour < gateEatingEndHour;
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) =>
now.hour >= schedule.slots().first &&
now.hour < schedule.enforcementEndHour;
/// Returns today's slots whose hour has arrived as of [now].
///
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
List<int> elapsedSlots(DateTime now) {
if (!withinEnforcementWindow(now)) return const [];
return daySlots().where((slot) => slot <= now.hour).toList();
List<int> elapsedSlots(DateTime now, MealSchedule schedule) {
if (!withinEnforcementWindow(now, schedule)) return const [];
return daySlots(schedule).where((slot) => slot <= now.hour).toList();
}
/// Returns elapsed slots not yet covered by [logged].
///
/// Mirrors `_slots.missing_slots`.
List<int> missingSlots(DateTime now, Set<int> logged) =>
elapsedSlots(now).where((slot) => !logged.contains(slot)).toList();
List<int> missingSlots(
DateTime now,
Set<int> logged,
MealSchedule schedule,
) => elapsedSlots(
now,
schedule,
).where((slot) => !logged.contains(slot)).toList();
/// Returns the most recent elapsed slot as of [now], or null.
///
/// Mirrors `_slots.current_slot`.
int? currentSlot(DateTime now) {
final elapsed = elapsedSlots(now);
int? currentSlot(DateTime now, MealSchedule schedule) {
final elapsed = elapsedSlots(now, schedule);
return elapsed.isEmpty ? null : elapsed.last;
}
/// Returns the slot a meal logged at [now] should be attributed to.
///
/// CLAMP RULE (keep byte-identical with `_slots.slot_for_log`): before the
/// first window, clamp to the first slot; after the last window, clamp to the
/// last slot; behaviour inside a window is unchanged.
/// first slot, clamp to the first slot; after the enforcement window ends,
/// clamp to the last slot; behaviour inside a window is unchanged. The two
/// languages must reach each answer by the *same* branch, not merely agree on
/// the value -- `test/models/slot_test.dart` sweeps every hour of the day
/// against several schedules for exactly that reason.
///
/// Unlike [currentSlot] this never returns null, which is the point: an
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or
/// 22:30 still produced a "you haven't logged your meal" reminder. Attribution
/// is deliberately separate from [elapsedSlots]/[missingSlots] -- widening
/// *those* would instead make every slot fall due at 23:00.
int slotForLog(DateTime now) {
final slots = daySlots();
if (now.hour < gateDayStartHour) return slots.first;
return currentSlot(now) ?? slots.last;
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
/// still produced a "you haven't logged your meal" reminder. Attribution is
/// deliberately separate from [elapsedSlots]/[missingSlots] -- widening
/// *those* would instead make every slot fall due at the end of the day.
int slotForLog(DateTime now, MealSchedule schedule) {
final slots = daySlots(schedule);
if (now.hour < slots.first) return slots.first;
return currentSlot(now, schedule) ?? slots.last;
}
/// Returns a human `HH:00` label for [slot], e.g. `"08:00"`.

View File

@ -13,6 +13,16 @@ mixin LogMealNavMixin<T extends StatefulWidget> on State<T> {
/// The screen's injected HTTP client, forwarded to [SettingsScreen].
http.Client? get syncHttpClient;
/// Re-reads the meal schedule and today's logged slots.
///
/// Called when [SettingsScreen] pops, because the schedule editor lives
/// there: without it the slot row keeps rendering the schedule that was in
/// force when this screen was built, so switching from four meals to five
/// showed the old four checkpoints until the app was restarted. Verified on
/// the phone -- the settings preview and the reminder both updated while the
/// row behind them did not.
Future<void> onScheduleMayHaveChanged();
/// Pushes the entry history screen.
void onOpenHistory() {
Navigator.of(context).push<void>(
@ -35,11 +45,17 @@ mixin LogMealNavMixin<T extends StatefulWidget> on State<T> {
}
/// Pushes the settings screen, forwarding the HTTP client.
void onOpenSettings() {
Navigator.of(context).push<void>(
///
/// Awaits the pop, unlike the other three: settings owns the meal-schedule
/// editor, so the slot row has to be rebuilt against whatever the user
/// chose there.
Future<void> onOpenSettings() async {
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => SettingsScreen(httpClient: syncHttpClient),
),
);
if (!mounted) return;
await onScheduleMayHaveChanged();
}
}

View File

@ -15,7 +15,7 @@ double parseMacroField(TextEditingController controller) =>
///
/// Takes the already-read [log] rather than re-reading, so the card can
/// never disagree with the write that produced it.
TodayProgress buildTodayProgress(DayLog log, String desc) {
TodayProgress buildTodayProgress(DayLog log) {
final budget = AppSettingsService.dailyKcalGoal;
final today = localDateKey(DateTime.now());
final entries = (log[today] ?? const <FoodEntry>[])
@ -23,7 +23,6 @@ TodayProgress buildTodayProgress(DayLog log, String desc) {
.toList();
final macros = sumMacros(entries);
return TodayProgress(
justLogged: desc,
consumedKcal: sumKcal(entries),
budgetKcal: budget,
proteinG: macros.proteinG,

View File

@ -15,6 +15,7 @@ import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
@ -49,13 +50,12 @@ class _LogMealScreenState extends State<LogMealScreen>
final TextEditingController _descController = TextEditingController();
final MacroControllers _macros = MacroControllers();
List<FoodSuggestion> _suggestions = const [];
int? _selectedSlot;
@override
int? selectedSlot;
String _source = 'manual';
String? _status;
TodayProgress? _progress;
@override
void initState() {
super.initState();
@ -71,7 +71,7 @@ class _LogMealScreenState extends State<LogMealScreen>
]) {
controller.addListener(_onMacroEdited);
}
_selectedSlot = slotForLog(DateTime.now());
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
unawaited(refreshSlots());
unawaited(_onDescChanged());
// Read health before the first sync finishes, so a device that stalled in
@ -140,7 +140,7 @@ class _LogMealScreenState extends State<LogMealScreen>
await LogStorageService.instance.logMeal(
desc,
nutrition,
slot: _selectedSlot,
slot: selectedSlot,
);
final log = await LogStorageService.instance.readLog();
await FoodBankService.instance.rebuildAndPersist(log);
@ -157,13 +157,13 @@ class _LogMealScreenState extends State<LogMealScreen>
_macros.clear();
setState(() {
_source = 'manual';
_selectedSlot = slotForLog(DateTime.now());
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
});
await refreshSlots();
if (!mounted) return;
setState(() {
_status = null;
_progress = buildTodayProgress(log, desc);
_progress = buildTodayProgress(log);
});
}
@ -179,7 +179,6 @@ class _LogMealScreenState extends State<LogMealScreen>
/// the meal -- written before this runs -- can never be lost to one.
Future<void> _dismissStaleReminder() => checkAndNotify(pullWhenDue: false);
@override
Widget build(BuildContext context) {
return Scaffold(
@ -203,8 +202,8 @@ class _LogMealScreenState extends State<LogMealScreen>
SlotSelectorRow(
now: DateTime.now(),
loggedSlots: loggedSlots,
selectedSlot: _selectedSlot,
onSlotSelected: (slot) => setState(() => _selectedSlot = slot),
selectedSlot: selectedSlot,
onSlotSelected: (slot) => setState(() => selectedSlot = slot),
),
const SizedBox(height: 8),
TextField(

View File

@ -1,10 +1,12 @@
import 'dart:async';
import 'dart:developer';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
@ -30,6 +32,12 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
/// The slots that already carry a logged meal today.
Set<int> loggedSlots = {};
/// The slot the screen is currently logging for.
///
/// Owned by the screen's own state; declared here so
/// [onScheduleMayHaveChanged] can re-derive it when the schedule changes.
abstract int? selectedSlot;
/// The screen's injected HTTP client, or null to use the default.
///
/// Declared abstract so the mixin stays independent of the widget's own
@ -137,4 +145,22 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
if (!mounted) return;
setState(() => loggedSlots = logged);
}
/// Rebuilds the slot row after the settings screen pops.
///
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
/// `MealScheduleService.current` at build time, so refreshing is enough to
/// re-derive the row -- but the selected slot also has to be recomputed,
/// since the hour it referred to may no longer be a checkpoint at all.
///
/// Found on the phone: without this the settings preview and the overdue
/// reminder both updated while the row behind them kept the old four
/// checkpoints until the app was restarted.
Future<void> onScheduleMayHaveChanged() async {
await refreshSlots();
if (!mounted) return;
setState(() {
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
});
}
}

View File

@ -0,0 +1,147 @@
// The meal-schedule editor: first meal, last meal, how many meals, and a
// live preview of the checkpoint times they derive.
//
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
// private state and calls `setState`.
part of 'settings_screen.dart';
mixin _SettingsMealSchedule on State<SettingsScreen> {
MealSchedule _schedule = kDefaultSchedule;
void _loadSchedule() {
_schedule = MealScheduleService.current;
}
/// The meal counts selectable for the current window.
///
/// Capped at the number of whole hours the window holds, so the count
/// dropdown can never offer a value that would round two meals onto the
/// same hour. Invalid states are made unrepresentable here rather than
/// validated after the fact -- `MealSchedule.normalized` still clamps, but
/// that is the defence against corrupt synced data, not the input contract.
List<int> get _selectableCounts {
final span = _schedule.last - _schedule.first;
final maxCount = span + 1 < kMaxMealCount ? span + 1 : kMaxMealCount;
return [for (var n = kMinMealCount; n <= maxCount; n++) n];
}
Future<void> _applySchedule(MealSchedule next) async {
final normalized = next.normalized();
setState(() => _schedule = normalized);
if (!MealScheduleService.isInitialized) return;
await MealScheduleService.instance.recordChange(normalized);
// The reminder ids are slot hours, so a schedule change orphans the ones
// it no longer contains. Re-running the check cancels them immediately
// rather than leaving a stale nag until the next background tick.
await checkAndNotify(pullWhenDue: false);
}
/// Dropdowns rather than a time picker: `showTimePicker` returns minutes,
/// and slots are whole hours on both devices by design.
Widget _hourDropdown({
required String label,
required int value,
required List<int> hours,
required ValueChanged<int> onChanged,
}) => ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: InputDecoration(labelText: label),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: value,
isDense: true,
isExpanded: true,
items: [
for (final hour in hours)
DropdownMenuItem(value: hour, child: Text(slotLabel(hour))),
],
onChanged: (hour) => hour == null ? null : onChanged(hour),
),
),
),
);
List<Widget> _mealScheduleSection(BuildContext context) {
final theme = Theme.of(context);
final counts = _selectableCounts;
return [
Text('Meal times', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
'Checkpoints are spread evenly between your first and last meal.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
_hourDropdown(
label: 'First meal',
value: _schedule.first,
// Leaves at least one hour of window, so `last` always has a value
// strictly after `first` to offer.
hours: [for (var h = kFirstHour; h < kLastHour; h++) h],
onChanged: (hour) => unawaited(
_applySchedule(
MealSchedule(
first: hour,
last: _schedule.last,
count: _schedule.count,
),
),
),
),
const SizedBox(height: 12),
_hourDropdown(
label: 'Last meal',
value: _schedule.last,
hours: [for (var h = _schedule.first + 1; h <= kLastHour; h++) h],
onChanged: (hour) => unawaited(
_applySchedule(
MealSchedule(
first: _schedule.first,
last: hour,
count: _schedule.count,
),
),
),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: const InputDecoration(labelText: 'Meals per day'),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: counts.contains(_schedule.count)
? _schedule.count
: counts.last,
isDense: true,
isExpanded: true,
items: [
for (final count in counts)
DropdownMenuItem(value: count, child: Text('$count')),
],
onChanged: (count) => count == null
? null
: unawaited(
_applySchedule(
MealSchedule(
first: _schedule.first,
last: _schedule.last,
count: count,
),
),
),
),
),
),
),
const SizedBox(height: 12),
Text(
_schedule.slots().map(slotLabel).join(' · '),
style: theme.textTheme.bodyMedium,
),
];
}
}

View File

@ -11,11 +11,15 @@ library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@ -25,6 +29,7 @@ import 'package:permission_handler/permission_handler.dart';
import 'package:sync_settings_ui/sync_settings_ui.dart';
part 'settings_kcal_goal.dart';
part 'settings_meal_schedule.dart';
/// Screen for app-specific settings and links to sync configuration.
class SettingsScreen extends StatefulWidget {
@ -91,13 +96,14 @@ class SettingsScreen extends StatefulWidget {
}
class _SettingsScreenState extends State<SettingsScreen>
with _SettingsKcalGoal {
with _SettingsKcalGoal, _SettingsMealSchedule {
final _kcalGoalController = TextEditingController();
@override
void initState() {
super.initState();
_kcalGoalController.text = AppSettingsService.dailyKcalGoal.toString();
_loadSchedule();
}
@override
@ -177,6 +183,10 @@ class _SettingsScreenState extends State<SettingsScreen>
),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
..._mealScheduleSection(context),
const SizedBox(height: 24),
const Divider(),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Sync settings'),

View File

@ -12,6 +12,7 @@ import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart';
@ -50,6 +51,11 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
await AppSettingsService.init();
// runSync also merges the budget history through this singleton.
await BudgetHistoryService.init();
// A fresh isolate has its own static state, so the schedule must be loaded
// here too -- otherwise the due-slot check in this isolate would fall back
// to the default four meals and nag for checkpoints the user's actual
// schedule does not have.
await MealScheduleService.init();
final SyncSettings settings;
try {
settings = await SyncSettings.load();

View File

@ -12,6 +12,7 @@ library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:http/http.dart' as http;
@ -55,9 +56,15 @@ Future<void> checkAndNotify({
// WorkManager isolate, including the token read and singleton init.
await backgroundSyncPush(httpClient: httpClient);
}
// Deliberately not init()ed here: `current` degrades to the default
// schedule when the singleton is absent, and forcing initialisation would
// reach path_provider from contexts that have no plugin channel (widget
// tests, and the WorkManager isolate before main() has run). `main.dart`
// owns the real init, the same way it does for the other stores.
final due = missingSlots(
at,
await LogStorageService.instance.loggedSlotsToday(),
MealScheduleService.current,
);
await _reconcileNotifications(due);
}

View File

@ -0,0 +1,186 @@
/// Forward-only history of the user's meal schedule.
///
/// The pure half: parsing, encoding, and resolving which schedule applied on a
/// given day. Persistence lives in `meal_schedule_service.dart`.
///
/// 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.
///
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule_store.py`.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:flutter/foundation.dart';
/// The effective-from date a seed uses, so the pre-history schedule covers
/// every day that was ever logged. Any real date is >= this.
const String kScheduleEpochDay = '1970-01-01';
const String _epochIso = '1970-01-01T00:00:00.000Z';
/// One meal schedule and the date it started applying.
@immutable
class ScheduleEntry {
/// Creates a [ScheduleEntry].
const ScheduleEntry({
required this.effectiveFrom,
required this.schedule,
required this.editedAt,
});
/// `YYYY-MM-DD`; the first day this schedule applies to.
final String effectiveFrom;
/// The eating window and meal count from that day onward.
final MealSchedule schedule;
/// ISO-8601 timestamp of the edit that created this entry.
final String editedAt;
@override
bool operator ==(Object other) =>
other is ScheduleEntry &&
other.effectiveFrom == effectiveFrom &&
other.schedule == schedule &&
other.editedAt == editedAt;
@override
int get hashCode => Object.hash(effectiveFrom, schedule, editedAt);
}
/// Returns the wire/disk form of one entry's value.
Map<String, Object?> scheduleEntryToJson(ScheduleEntry entry) => {
'f': entry.schedule.first,
'l': entry.schedule.last,
'n': entry.schedule.count,
't': entry.editedAt,
};
/// Returns an entry parsed from its stored value, or null if unusable.
///
/// Never throws: a malformed entry is skipped so one bad field from a peer
/// cannot take out the whole history.
ScheduleEntry? scheduleEntryFromJson(String effectiveFrom, Object? raw) {
if (raw is! Map) return null;
final first = raw['f'];
final last = raw['l'];
final count = raw['n'];
if (first is! int || last is! int || count is! int) return null;
final editedAt = raw['t'];
return ScheduleEntry(
effectiveFrom: effectiveFrom,
// 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: first,
last: last,
count: count,
).normalized(),
editedAt: editedAt is String ? editedAt : _epochIso,
);
}
/// A forward-only list of schedule entries, ascending by date.
@immutable
class MealScheduleHistory {
/// Creates a history from [entries], sorting them ascending.
MealScheduleHistory(List<ScheduleEntry> entries)
: entries = List.unmodifiable(_sorted(entries));
/// A history with no entries; every day resolves to [kDefaultSchedule].
static final MealScheduleHistory empty = MealScheduleHistory(const []);
/// The entries, ascending by [ScheduleEntry.effectiveFrom].
final List<ScheduleEntry> entries;
/// Returns the schedule in force on [day] (`YYYY-MM-DD`).
///
/// The newest entry effective on or before [day], or the default when the
/// history says nothing about that day.
MealSchedule forDay(String day) {
var result = kDefaultSchedule;
for (final entry in entries) {
if (entry.effectiveFrom.compareTo(day) <= 0) {
result = entry.schedule;
}
}
return result;
}
/// Returns this history with [schedule] effective from [when]'s date.
///
/// Re-editing on the same day replaces that day's entry rather than
/// stacking a second one.
MealScheduleHistory upsert(MealSchedule schedule, {DateTime? when}) {
final moment = when ?? DateTime.now();
final day = _dayKey(moment);
return MealScheduleHistory([
...entries.where((entry) => entry.effectiveFrom != day),
ScheduleEntry(
effectiveFrom: day,
schedule: schedule.normalized(),
editedAt: moment.toIso8601String(),
),
]);
}
/// Returns this history 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.
MealScheduleHistory seedDefault() {
if (entries.any((entry) => entry.effectiveFrom == kScheduleEpochDay)) {
return this;
}
return MealScheduleHistory([
const ScheduleEntry(
effectiveFrom: kScheduleEpochDay,
schedule: kDefaultSchedule,
editedAt: _epochIso,
),
...entries,
]);
}
/// Parses a stored document into entries, ascending.
///
/// Anything unreadable yields no entries, which callers treat as "fall back
/// to the default schedule" -- the pre-feature behaviour.
static List<ScheduleEntry> parse(Object? raw) {
if (raw is! Map) return const [];
final stored = raw['e'];
if (stored is! Map) return const [];
final parsed = <ScheduleEntry>[];
for (final entry in stored.entries) {
final key = entry.key;
if (key is! String) continue;
final value = scheduleEntryFromJson(key, entry.value);
if (value != null) parsed.add(value);
}
parsed.sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
return parsed;
}
/// Returns the on-disk document for [entries].
static Map<String, Object?> encode(List<ScheduleEntry> entries) => {
'v': 1,
'e': {
for (final entry in entries)
entry.effectiveFrom: scheduleEntryToJson(entry),
},
};
}
List<ScheduleEntry> _sorted(List<ScheduleEntry> entries) =>
List<ScheduleEntry>.of(entries)
..sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
String _dayKey(DateTime moment) {
final local = moment.toLocal();
final month = local.month.toString().padLeft(2, '0');
final day = local.day.toString().padLeft(2, '0');
return '${local.year}-$month-$day';
}

View File

@ -0,0 +1,142 @@
/// Persistence for the meal-schedule history.
///
/// Shaped exactly like [BudgetHistoryService]: a singleton over the platform
/// [DocumentStore], with a static getter that degrades to the default schedule
/// when uninitialised so widget tests that never call [init] still render.
///
/// Mirrors the storage half of `diet_guard/_meal_schedule_store.py`.
library;
import 'dart:convert';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/meal_schedule_history.dart';
import 'package:flutter/foundation.dart';
/// Singleton owning the meal-schedule history document.
class MealScheduleService {
MealScheduleService._(this._store);
/// Document name this service owns.
static const documentName = 'meal_schedule.json';
static MealScheduleService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static MealScheduleService get instance => _instance!;
/// True when [init]/[initForTesting]/[resetForTesting] has run.
static bool get isInitialized => _instance != null;
/// The schedule in force today, or the default when uninitialised.
///
/// This is the impure edge every `slot.dart` caller resolves through; the
/// slot arithmetic itself stays a pure function of its arguments.
static MealSchedule get current =>
_instance?._history.forDay(_todayKey()) ?? kDefaultSchedule;
/// The whole stored history, for the sync layer and past-day lookups.
static MealScheduleHistory get history =>
_instance?._history ?? MealScheduleHistory.empty;
/// When this device last set the schedule, or null if it never has.
///
/// Null is what tells the sync layer this device has nothing of its own to
/// contribute, rather than silently syncing the unset default.
static DateTime? get updatedAt => _instance?._updatedAt;
final DocumentStore _store;
MealScheduleHistory _history = MealScheduleHistory.empty;
DateTime? _updatedAt;
/// Initialises the singleton against the platform document store.
static Future<MealScheduleService> init() async {
if (_instance != null) return _instance!;
// Resolving the platform store is a plugin call (path_provider /
// IndexedDB), not reachable from `flutter test`.
// coverage:ignore-start
final svc = MealScheduleService._(await openDocumentStore());
// coverage:ignore-end
await svc._load();
_instance = svc;
return svc;
}
/// Resets the singleton so [init] can be called again in tests.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : MealScheduleService._(store);
}
/// Initialises from [store], calling the loader, for use in unit tests.
@visibleForTesting
static Future<MealScheduleService> initForTesting(DocumentStore store) async {
final svc = MealScheduleService._(store);
await svc._load();
_instance = svc;
return svc;
}
Future<void> _load() async {
final raw = await _store.read(documentName);
if (raw == null) return;
try {
final decoded = jsonDecode(raw);
_history = MealScheduleHistory(MealScheduleHistory.parse(decoded));
final stamp = decoded is Map ? decoded['t'] : null;
_updatedAt = stamp is String ? DateTime.tryParse(stamp) : null;
} on FormatException {
// Ignore parse errors: no history means "use the default schedule",
// which is exactly the pre-feature behaviour.
}
}
/// Records 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.
Future<void> recordChange(MealSchedule schedule, {DateTime? when}) async {
final moment = when ?? DateTime.now();
_history = _history.seedDefault().upsert(schedule, when: moment);
_updatedAt = moment;
await _writeToDisk();
}
/// Replaces the stored history with a merge result from the sync layer.
///
/// An empty merge result is ignored rather than persisted: a pre-feature
/// peer contributes no `sched:` fields, and writing the empty document back
/// would discard this device's own history.
Future<void> applyMerged(
List<ScheduleEntry> entries, {
DateTime? updatedAt,
}) async {
if (entries.isEmpty) return;
_history = MealScheduleHistory(entries);
// The winner's stamp is persisted verbatim, not "now", so re-syncing an
// unchanged history is idempotent.
if (updatedAt != null) _updatedAt = updatedAt;
await _writeToDisk();
}
/// Writes the whole in-memory history to the store.
///
/// Deliberately *not* a read-modify-write, for the same reason as
/// [BudgetHistoryService]: edits arrive in bursts and re-reading a
/// date-keyed map per write could drop entries.
Future<void> _writeToDisk() async {
final document = MealScheduleHistory.encode(_history.entries);
final stamp = _updatedAt;
if (stamp != null) document['t'] = stamp.toIso8601String();
await _store.write(documentName, jsonEncode(document));
}
}
String _todayKey() {
final now = DateTime.now();
final month = now.month.toString().padLeft(2, '0');
final day = now.day.toString().padLeft(2, '0');
return '${now.year}-$month-$day';
}

View File

@ -9,6 +9,8 @@ import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:diet_guard_app/services/notification_backend_factory.dart';
import 'package:flutter/foundation.dart';
const int _hoursPerDay = 24;
/// Owns the due-slot notification logic ([syncToSlots]) independently of the
/// platform surface that actually posts them: `flutter_local_notifications`
/// on Android, the browser's Notifications API in the desktop web build (see
@ -60,7 +62,12 @@ class NotificationService {
/// behavior rather than firing once and forgetting.
Future<void> syncToSlots(List<int> dueSlots) async {
final due = dueSlots.toSet();
for (final slot in daySlots()) {
// Sweeps every hour of the day, not just the *current* schedule's slots.
// The slot hour doubles as the notification id, so a schedule change
// orphans the ids it no longer contains: going 08/12/16/20 -> 08/11/14/17
// used to leave 12 and 16 posted with nothing left to ever cancel them,
// nagging forever about checkpoints that no longer exist.
for (var slot = 0; slot < _hoursPerDay; slot++) {
if (due.contains(slot)) {
await _backend.show(
slot,

View File

@ -14,7 +14,9 @@ import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/budget_schedule.dart';
import 'package:diet_guard_app/services/meal_schedule_history.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_merge_schedule.dart';
/// Stable id: exactly one budget record per device-pushed `budget.json`.
const budgetRecordId = 'budget';
@ -75,6 +77,7 @@ Hlc historyHlc(BudgetEntry entry) {
Log budgetToLog(
Map<String, dynamic>? record, [
List<BudgetEntry> entries = const [],
List<ScheduleEntry> scheduleEntries = const [],
]) {
if (record == null) return {};
final hlc = budgetHlc(record);
@ -88,6 +91,9 @@ Log budgetToLog(
historyHlc(entry),
);
}
// The meal-schedule history rides the same record as its own `sched:`
// fields; see `sync_merge_schedule.dart`.
fields.addAll(scheduleFields(scheduleEntries));
return {budgetRecordId: Record(id: budgetRecordId, fields: fields)};
}

View File

@ -0,0 +1,98 @@
/// Meal-schedule history as extra fields on the shared `budget` record.
///
/// Split out of `sync_merge_budget.dart` to keep both under the repo's
/// 250-line limit; the two halves are otherwise the same idea and share one
/// record.
///
/// The schedule rides as one `sched:<YYYY-MM-DD>` field per history entry,
/// exactly like the budget's `hist:` fields. `mergeRecord` is 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 predates meal
/// schedules neither clobbers those fields nor blocks them -- it relays them
/// untouched. That is what makes this shippable without a coordinated
/// release.
///
/// KEEP IN SYNC WITH `diet_guard/sync_merge/_schedule.py`.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/services/meal_schedule_history.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
/// The shared record these fields live on. Declared here rather than imported
/// from `sync_merge_budget.dart` so the two modules do not import each other;
/// `_schedule.py` declares its own copy for the same reason.
const _budgetRecordId = 'budget';
/// Field-name prefix for the effective-from meal-schedule history.
const scheduleFieldPrefix = 'sched:';
/// Derives a deterministic [Hlc] for one schedule entry from its edit time.
///
/// Identical inputs always yield the same clock, so re-syncing an unchanged
/// history is a no-op. Derived from the *parsed* timestamp rather than the
/// raw string, so the two languages agree even though they format the epoch
/// fallback differently.
Hlc scheduleHlc(ScheduleEntry entry) {
final wallTimeMs =
DateTime.tryParse(entry.editedAt)?.toUtc().millisecondsSinceEpoch ?? 0;
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
}
/// Returns the `sched:` fields contributed by [entries].
///
/// Empty when this device has no history, so a device that has never edited
/// a schedule contributes nothing to the merge rather than pushing the unset
/// default over a peer's real value.
Map<String, (dynamic, Hlc)> scheduleFields(List<ScheduleEntry> entries) => {
for (final entry in entries)
'$scheduleFieldPrefix${entry.effectiveFrom}': (
{
'f': entry.schedule.first,
'l': entry.schedule.last,
'n': entry.schedule.count,
},
scheduleHlc(entry),
),
};
/// Extracts the meal-schedule history from a merged budget [Log].
///
/// Each entry's `editedAt` is reconstructed from its field Hlc rather than
/// carried separately, so the stored timestamp and the clock the merge
/// compared can never drift apart. Malformed values are skipped, so one bad
/// field from a peer cannot take out the whole history.
List<ScheduleEntry> logToScheduleHistory(Log log) {
final record = log[_budgetRecordId];
if (record == null) return const [];
final entries = <ScheduleEntry>[];
for (final field in record.fields.entries) {
if (!field.key.startsWith(scheduleFieldPrefix)) continue;
final value = field.value.$1;
if (value is! Map) continue;
final first = value['f'];
final last = value['l'];
final count = value['n'];
if (first is! int || last is! int || count is! int) continue;
entries.add(
ScheduleEntry(
effectiveFrom: field.key.substring(scheduleFieldPrefix.length),
// Normalised on the way in, so a peer running a future version with a
// wider range cannot hand us a schedule we would derive slots
// differently from.
schedule: MealSchedule(
first: first,
last: last,
count: count,
).normalized(),
editedAt: DateTime.fromMillisecondsSinceEpoch(
field.value.$2.wallTimeMs,
isUtc: true,
).toLocal().toIso8601String(),
),
);
}
entries.sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
return entries;
}

View File

@ -18,8 +18,10 @@ import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
import 'package:diet_guard_app/services/sync_merge_schedule.dart';
import 'package:diet_guard_app/services/sync_state_factory.dart';
const _devicesDir = 'diet-guard-sync/devices';
@ -113,12 +115,23 @@ Future<void> _syncManualBank(RemoteStore client) async {
/// from elsewhere.
Future<void> _syncBudget(RemoteStore client) async {
final updatedAt = AppSettingsService.dailyKcalGoalUpdatedAt;
final localRecord = updatedAt == null
final scheduleEntries = MealScheduleService.history.entries;
// `budgetToLog` returns an empty Log for a null record, which would also
// drop the `sched:` fields. A device that has edited its schedule but never
// its budget still has something to contribute, so synthesise a record from
// the schedule's own edit time in that case. Its `value` carries the
// unset-default budget, but that loses every LWW race against a device that
// has actually set one, because this stamp is older than any real edit.
final scheduleStamp = MealScheduleService.updatedAt;
final recordStamp =
updatedAt ?? (scheduleEntries.isEmpty ? null : scheduleStamp);
final localRecord = recordStamp == null
? null
: <String, dynamic>{
'v': 2,
'b': AppSettingsService.dailyKcalGoal,
't': updatedAt.toIso8601String(),
't': (updatedAt ?? DateTime.fromMillisecondsSinceEpoch(0))
.toIso8601String(),
};
final mergedBudgetLog = await syncLog(
@ -129,6 +142,7 @@ Future<void> _syncBudget(RemoteStore client) async {
localLog: budgetToLog(
localRecord,
BudgetHistoryService.schedule.entries,
scheduleEntries,
),
encode: encodeBudgetForPush,
decode: parseRemoteBudget,
@ -141,6 +155,14 @@ Future<void> _syncBudget(RemoteStore client) async {
await BudgetHistoryService.instance.applyMerged(
logToHistory(mergedBudgetLog),
);
// Same reasoning for the meal schedule: field-union merge, so applied
// regardless of how the scalar budget resolved.
if (MealScheduleService.isInitialized) {
await MealScheduleService.instance.applyMerged(
logToScheduleHistory(mergedBudgetLog),
updatedAt: scheduleStamp,
);
}
final merged = logToBudget(mergedBudgetLog);
final mergedKcal = merged?['b'];

View File

@ -4,6 +4,7 @@
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
@ -48,43 +49,62 @@ class SlotSelectorRow extends StatelessWidget {
// matches production exactly when the extension is genuinely absent.
final statusColors =
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
final elapsed = elapsedSlots(now).toSet();
return Wrap(
spacing: AppSpacing.xs + 2,
runSpacing: AppSpacing.xs,
children: [
...daySlots().map((slot) {
final isLogged = loggedSlots.contains(slot);
final isDue = !isLogged && elapsed.contains(slot);
final color = isLogged
? statusColors.success
: isDue
? scheme.error
: scheme.onSurfaceVariant;
final isSelected = selectedSlot == slot;
return ChoiceChip(
label: Text(slotLabel(slot)),
selected: isSelected,
// Icon reads lighter than the label text (rule 28): reduced
// opacity instead of the label's full-strength color.
avatar: isLogged
? Icon(
Icons.check,
size: 14,
color: color.withValues(alpha: 0.72),
)
: null,
backgroundColor: color.withValues(alpha: 0.15),
selectedColor: color.withValues(alpha: 0.35),
labelStyle: TextStyle(color: color),
side: BorderSide(
width: isSelected ? 2 : 1,
color: isSelected ? color : color.withValues(alpha: 0.4),
),
onSelected: (_) => onSlotSelected(slot),
);
}),
],
final schedule = MealScheduleService.current;
final elapsed = elapsedSlots(now, schedule).toSet();
// One row, always. A Wrap dropped the later pills onto a second line as
// soon as the row outgrew the width, which it does even at four: a logged
// chip measures ~124px at Material defaults, so four already need 522px
// against ~330px of phone width.
//
// FittedBox scales the whole row down uniformly instead. A Row of
// Expanded children also avoids the wrap, but imposes a *tight* width on
// each chip, and a Chip narrower than avatar+padding+label clips its label
// rather than shrinking -- measured at 10px per label, about one
// character, and it throws no overflow error while doing it.
return FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.xs + 2,
children: [
...daySlots(schedule).map((slot) {
final isLogged = loggedSlots.contains(slot);
final isDue = !isLogged && elapsed.contains(slot);
final color = isLogged
? statusColors.success
: isDue
? scheme.error
: scheme.onSurfaceVariant;
final isSelected = selectedSlot == slot;
return ChoiceChip(
label: Text(slotLabel(slot)),
selected: isSelected,
// Icon reads lighter than the label text (rule 28): reduced
// opacity instead of the label's full-strength color.
avatar: isLogged
? Icon(
Icons.check,
size: 14,
color: color.withValues(alpha: 0.72),
)
: null,
backgroundColor: color.withValues(alpha: 0.15),
selectedColor: color.withValues(alpha: 0.35),
labelStyle: TextStyle(color: color),
side: BorderSide(
width: isSelected ? 2 : 1,
color: isSelected ? color : color.withValues(alpha: 0.4),
),
// Trim the Material defaults so the row needs less scaling down:
// every pixel saved here is legibility kept at six meals.
visualDensity: VisualDensity.compact,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onSelected: (_) => onSlotSelected(slot),
);
}),
],
),
);
}
}

View File

@ -15,7 +15,6 @@ import 'package:flutter/material.dart';
class TodayProgress {
/// Creates a [TodayProgress].
const TodayProgress({
required this.justLogged,
required this.consumedKcal,
required this.budgetKcal,
required this.proteinG,
@ -24,9 +23,6 @@ class TodayProgress {
required this.adherenceStreak,
});
/// Description of the meal that was just logged.
final String justLogged;
/// Today's total calories, including the meal just logged.
final double consumedKcal;
@ -53,7 +49,11 @@ class TodayProgress {
bool get isOverBudget => remainingKcal < 0;
}
/// Shows the just-logged meal and today's running budget position.
/// Shows today's running budget position after a meal is logged.
///
/// It used to open with a `Logged "<meal>".` line, removed 2026-08-16: the
/// user had just typed that description, so it restated the input instead of
/// telling them anything. What remains is what they act on.
///
/// Replaces the old one-tap-reward prompt: the same slot in the log screen,
/// but showing information the user actually acts on instead of an
@ -92,11 +92,6 @@ class TodayProgressCard extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Logged "${progress.justLogged}".',
style: theme.textTheme.bodyMedium,
),
const SizedBox(height: AppSpacing.sm),
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,

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.29+1
version: 1.0.39+1
environment:
sdk: ^3.12.2

View File

@ -0,0 +1,153 @@
/// Tests for the pure meal-schedule derivation.
///
/// The vector table below is duplicated verbatim from
/// `diet_guard/tests/test_meal_schedule.py`. KEEP THE TWO IN SYNC: it is the
/// only thing that catches a Python/Dart divergence before it reaches a
/// device, and a divergence there means one device nags for a checkpoint the
/// other never offers -- a slot that can never be satisfied, i.e. a permanent
/// lock.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:flutter_test/flutter_test.dart';
/// (first, last, count, expected slots). Shared with the Python mirror.
const List<(int, int, int, List<int>)> scheduleVectors = [
// The eating window the user described, at every supported meal count.
(8, 20, 2, [8, 20]),
(8, 20, 3, [8, 14, 20]),
(8, 20, 4, [8, 12, 16, 20]), // today's hardcoded schedule
(8, 20, 5, [8, 11, 14, 17, 20]), // the user's stated example
(8, 20, 6, [8, 10, 13, 15, 18, 20]),
// A window that does not divide evenly: 14 hours across 3 gaps.
(7, 21, 4, [7, 12, 16, 21]),
(7, 21, 5, [7, 11, 14, 18, 21]),
(9, 19, 4, [9, 12, 16, 19]),
// Narrow windows: count is capped at the number of whole hours available,
// so the slots stay distinct instead of repeating an hour.
(8, 12, 6, [8, 9, 10, 11, 12]),
(8, 10, 5, [8, 9, 10]),
(8, 9, 4, [8, 9]),
// Whole-day extremes.
(0, 23, 6, [0, 5, 9, 14, 18, 23]),
(0, 1, 2, [0, 1]),
];
void main() {
group('slots', () {
for (final (first, last, count, expected) in scheduleVectors) {
test('$first-$last x$count derives $expected', () {
expect(
MealSchedule(first: first, last: last, count: count).slots(),
expected,
);
});
}
test('the default is the historical schedule', () {
expect(kDefaultSchedule.slots(), [8, 12, 16, 20]);
});
test('endpoints stay exact when the spacing rounds', () {
final slots = const MealSchedule(first: 8, last: 20, count: 6).slots();
expect(slots.first, 8);
expect(slots.last, 20);
});
});
group('normalized', () {
const cases = <(MealSchedule, MealSchedule)>[
(
MealSchedule(first: 8, last: 20, count: 99),
MealSchedule(first: 8, last: 20, count: kMaxMealCount),
),
(
MealSchedule(first: 8, last: 20, count: 0),
MealSchedule(first: 8, last: 20, count: kMinMealCount),
),
(
MealSchedule(first: -5, last: 20, count: 4),
MealSchedule(first: 0, last: 20, count: 4),
),
(
MealSchedule(first: 8, last: 99, count: 4),
MealSchedule(first: 8, last: 23, count: 4),
),
// last <= first is pulled forward to leave a one-hour window.
(
MealSchedule(first: 12, last: 12, count: 4),
MealSchedule(first: 12, last: 13, count: 2),
),
(
MealSchedule(first: 12, last: 3, count: 4),
MealSchedule(first: 12, last: 13, count: 2),
),
// first cannot occupy the final hour, or no window would remain.
(
MealSchedule(first: 23, last: 23, count: 2),
MealSchedule(first: 22, last: 23, count: 2),
),
];
for (final (input, expected) in cases) {
test('$input clamps to $expected', () {
expect(input.normalized(), expected);
});
}
test('garbage still yields usable slots', () {
expect(
const MealSchedule(first: 99, last: -5, count: 999).slots(),
[22, 23],
);
});
});
group('enforcementEndHour', () {
test('the default keeps the historical 22:00 cutoff', () {
expect(kDefaultSchedule.enforcementEndHour, 22);
});
test('the tail follows the last meal', () {
expect(
const MealSchedule(first: 8, last: 18, count: 4).enforcementEndHour,
20,
);
});
test('is clamped to the end of the day', () {
// An unclamped 23 + 2 = 25 would make `hour < cutoff` vacuously true,
// so the enforcement window would never close.
expect(
const MealSchedule(first: 8, last: 23, count: 4).enforcementEndHour,
24,
);
});
});
test('every input yields ascending slots with exact endpoints', () {
// The Dart half of the cross-language parity guarantee; the Python mirror
// runs the identical sweep.
for (var first = -2; first < 26; first++) {
for (var last = -2; last < 26; last++) {
for (var count = -2; count < 10; count++) {
final schedule = MealSchedule(
first: first,
last: last,
count: count,
);
final normalized = schedule.normalized();
final slots = schedule.slots();
expect(slots.first, normalized.first);
expect(slots.last, normalized.last);
expect(slots.length, normalized.count);
expect(slots.toSet().length, slots.length);
expect(slots, orderedEquals(List<int>.of(slots)..sort()));
expect(slots.length, greaterThanOrEqualTo(kMinMealCount));
expect(slots.length, lessThanOrEqualTo(kMaxMealCount));
}
}
}
});
}

View File

@ -1,60 +1,91 @@
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('daySlots', () {
test('returns the four fixed hourly slots', () {
expect(daySlots(), [8, 12, 16, 20]);
expect(daySlots(kDefaultSchedule), [8, 12, 16, 20]);
});
});
group('withinEnforcementWindow', () {
test('false before the day start hour', () {
expect(withinEnforcementWindow(DateTime(2026, 6, 22, 7, 59)), isFalse);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 7, 59), kDefaultSchedule),
isFalse,
);
});
test('true at the day start hour', () {
expect(withinEnforcementWindow(DateTime(2026, 6, 22, 8, 0)), isTrue);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule),
isTrue,
);
});
test('true just before the eating end hour', () {
expect(withinEnforcementWindow(DateTime(2026, 6, 22, 21, 59)), isTrue);
expect(
withinEnforcementWindow(
DateTime(2026, 6, 22, 21, 59),
kDefaultSchedule,
),
isTrue,
);
});
test('false at the eating end hour (exclusive)', () {
expect(withinEnforcementWindow(DateTime(2026, 6, 22, 22, 0)), isFalse);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 22, 0), kDefaultSchedule),
isFalse,
);
});
});
group('elapsedSlots', () {
test('empty outside the enforcement window', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 23, 0)), isEmpty);
expect(
elapsedSlots(DateTime(2026, 6, 22, 23, 0), kDefaultSchedule),
isEmpty,
);
});
test('only the 8 slot right at day start', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 8, 0)), [8]);
expect(elapsedSlots(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule), [8]);
});
test('8 and 12 mid-afternoon before 16', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 15, 59)), [8, 12]);
expect(elapsedSlots(DateTime(2026, 6, 22, 15, 59), kDefaultSchedule), [
8,
12,
]);
});
test('all four slots once 20:00 has passed', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 21, 0)), [8, 12, 16, 20]);
expect(elapsedSlots(DateTime(2026, 6, 22, 21, 0), kDefaultSchedule), [
8,
12,
16,
20,
]);
});
});
group('missingSlots', () {
test('excludes already-logged elapsed slots', () {
expect(
missingSlots(DateTime(2026, 6, 22, 17, 0), {8}),
missingSlots(DateTime(2026, 6, 22, 17, 0), {8}, kDefaultSchedule),
[12, 16],
);
});
test('empty once every elapsed slot is logged', () {
expect(
missingSlots(DateTime(2026, 6, 22, 17, 0), {8, 12, 16}),
missingSlots(DateTime(2026, 6, 22, 17, 0), {
8,
12,
16,
}, kDefaultSchedule),
isEmpty,
);
});
@ -62,15 +93,18 @@ void main() {
group('currentSlot', () {
test('null outside the enforcement window', () {
expect(currentSlot(DateTime(2026, 6, 22, 6, 0)), isNull);
expect(
currentSlot(DateTime(2026, 6, 22, 6, 0), kDefaultSchedule),
isNull,
);
});
test('returns the most recently elapsed slot', () {
expect(currentSlot(DateTime(2026, 6, 22, 17, 41)), 16);
expect(currentSlot(DateTime(2026, 6, 22, 17, 41), kDefaultSchedule), 16);
});
test('returns 8 right at day start', () {
expect(currentSlot(DateTime(2026, 6, 22, 8, 0)), 8);
expect(currentSlot(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule), 8);
});
});
@ -81,39 +115,106 @@ void main() {
DateTime at(int hour) => DateTime(2026, 6, 22, hour, 0);
test('clamps to the first slot before the window opens', () {
expect(slotForLog(at(7)), 8);
expect(slotForLog(at(7), kDefaultSchedule), 8);
});
test('clamps to the first slot in the small hours', () {
expect(slotForLog(at(0)), 8);
expect(slotForLog(at(0), kDefaultSchedule), 8);
});
test('is unchanged exactly at the first slot', () {
expect(slotForLog(at(8)), 8);
expect(slotForLog(at(8), kDefaultSchedule), 8);
});
test('matches currentSlot inside the window', () {
expect(slotForLog(at(13)), currentSlot(at(13)));
expect(slotForLog(at(13)), 12);
expect(
slotForLog(at(13), kDefaultSchedule),
currentSlot(at(13), kDefaultSchedule),
);
expect(slotForLog(at(13), kDefaultSchedule), 12);
});
test('is unchanged at the last in-window hour', () {
expect(slotForLog(at(21)), 20);
expect(slotForLog(at(21), kDefaultSchedule), 20);
});
test('clamps to the last slot once the window closes', () {
expect(slotForLog(at(22)), 20);
expect(slotForLog(at(22), kDefaultSchedule), 20);
});
test('clamps to the last slot late in the evening', () {
expect(slotForLog(at(23)), 20);
expect(slotForLog(at(23), kDefaultSchedule), 20);
});
test('never returns a slot outside the schedule', () {
for (var hour = 0; hour < 24; hour++) {
expect(daySlots(), contains(slotForLog(at(hour))));
expect(
daySlots(kDefaultSchedule),
contains(slotForLog(at(hour), kDefaultSchedule)),
);
}
});
test('clamps the same way across configured schedules', () {
// Sweeps every hour against several windows. `test_slots.py` 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.
const schedules = [
kDefaultSchedule,
MealSchedule(first: 8, last: 20, count: 5),
MealSchedule(first: 6, last: 22, count: 6),
MealSchedule(first: 0, last: 23, count: 2),
MealSchedule(first: 10, last: 14, count: 3),
];
for (final schedule in schedules) {
final slots = daySlots(schedule);
for (var hour = 0; hour < 24; hour++) {
final attributed = slotForLog(at(hour), schedule);
expect(slots, contains(attributed));
if (hour < slots.first) {
expect(attributed, slots.first);
} else if (hour >= schedule.enforcementEndHour) {
expect(attributed, slots.last);
} else {
// Inside the window: the most recent slot that has opened.
expect(attributed, slots.where((s) => s <= hour).last);
}
}
}
});
});
group('configured schedules', () {
test('five meals shifts the checkpoints', () {
const schedule = MealSchedule(first: 8, last: 20, count: 5);
expect(daySlots(schedule), [8, 11, 14, 17, 20]);
expect(elapsedSlots(DateTime(2026, 6, 22, 14), schedule), [8, 11, 14]);
expect(
missingSlots(DateTime(2026, 6, 22, 14), {8, 11}, schedule),
[14],
);
});
test('enforcement follows the last meal', () {
const schedule = MealSchedule(first: 8, last: 18, count: 3);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 19), schedule),
isTrue,
);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 20), schedule),
isFalse,
);
expect(elapsedSlots(DateTime(2026, 6, 22, 20), schedule), isEmpty);
});
test('midnight is a real slot, not a falsy absence', () {
const schedule = MealSchedule(first: 0, last: 12, count: 3);
expect(daySlots(schedule), [0, 6, 12]);
expect(currentSlot(DateTime(2026, 6, 22), schedule), 0);
expect(slotForLog(DateTime(2026, 6, 22), schedule), 0);
});
});
group('slotLabel', () {

View File

@ -0,0 +1,73 @@
/// The log screen's slot row versus a meal-schedule change.
///
/// Split from `log_meal_screen_test.dart` for the repo's 250-line cap.
library;
import 'dart:io';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
late Directory tempDir;
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_sched_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir));
await MealScheduleService.initForTesting(FileDocumentStore(tempDir));
});
tearDown(() async {
LogStorageService.resetForTesting();
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
await tempDir.delete(recursive: true);
});
Future<void> settle(WidgetTester tester) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pumpAndSettle();
}
testWidgets('the slot row follows a schedule change made in settings', (
tester,
) async {
// Found on the phone: the settings preview and the overdue reminder both
// picked up a four -> five meal change while the row behind them kept
// rendering the old four checkpoints until the app was restarted, because
// onOpenSettings pushed without awaiting the pop.
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
expect(find.text('12:00'), findsOneWidget);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
);
final state = tester.state<State<LogMealScreen>>(
find.byType(LogMealScreen),
);
await (state as LogMealNavMixin<LogMealScreen>)
.onScheduleMayHaveChanged();
await settle(tester);
expect(find.text('11:00'), findsOneWidget);
expect(find.text('17:00'), findsOneWidget);
expect(find.text('12:00'), findsNothing);
});
});
}

View File

@ -1,12 +1,15 @@
import 'dart:io';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
@ -40,7 +43,6 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
/// it as a real image instead of throwing on bogus bytes.
void main() {
late Directory tempDir;
setUp(() async {
@ -51,6 +53,7 @@ void main() {
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
await MealScheduleService.initForTesting(FileDocumentStore(tempDir));
});
tearDown(() async {
@ -58,6 +61,7 @@ void main() {
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
await tempDir.delete(recursive: true);
});
@ -94,7 +98,10 @@ void main() {
await tester.tap(logMealButton);
await settle(tester);
expect(find.text('Logged "toast".'), findsOneWidget);
// The card itself is the "it logged" signal; the `Logged "<meal>".`
// line it used to open with was removed 2026-08-16.
expect(find.byType(TodayProgressCard), findsOneWidget);
expect(find.textContaining('Logged'), findsNothing);
final entries = await LogStorageService.instance.todayEntries();
expect(entries.single.source, 'manual');
expect(entries.single.kcal, 150);

View File

@ -1,6 +1,7 @@
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -8,6 +9,7 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler/permission_handler.dart';
@ -16,7 +18,6 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../fake_secure_storage.dart';
void main() {
late Directory tempDir;
setUp(() async {
@ -27,6 +28,7 @@ void main() {
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
await MealScheduleService.initForTesting(FileDocumentStore(tempDir));
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
});
@ -36,6 +38,7 @@ void main() {
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
await tempDir.delete(recursive: true);
});
@ -64,6 +67,40 @@ void main() {
expect(find.widgetWithText(TextField, '1800'), findsOneWidget);
});
});
testWidgets('shows the derived meal times for the stored schedule', (
tester,
) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);
// The default schedule still derives the hours that used to be
// hardcoded, so an existing install sees no change.
expect(
find.text('08:00 · 12:00 · 16:00 · 20:00'),
findsOneWidget,
);
expect(find.text('First meal'), findsOneWidget);
expect(find.text('Last meal'), findsOneWidget);
expect(find.text('Meals per day'), findsOneWidget);
});
});
testWidgets('reflects a five-meal schedule as the user\'s example', (
tester,
) async {
await tester.runAsync(() async {
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
);
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);
expect(
find.text('08:00 · 11:00 · 14:00 · 17:00 · 20:00'),
findsOneWidget,
);
});
});
testWidgets('typing a kcal goal debounces the save', (tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));

View File

@ -11,6 +11,7 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
@ -34,6 +35,7 @@ void main() {
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
MealScheduleService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {
@ -41,6 +43,7 @@ void main() {
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
await tempDir.delete(recursive: true);
});
@ -120,7 +123,10 @@ void main() {
expect(pushedPaths, isNotEmpty);
expect(pushedPaths.every((path) => path.contains(uuid)), isTrue);
expect(pushedPaths.any((path) => path.contains('/devices/phone/')), isFalse);
expect(
pushedPaths.any((path) => path.contains('/devices/phone/')),
isFalse,
);
});
test('reports failure (retry) when the push errors', () async {

View File

@ -13,6 +13,7 @@ import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter/services.dart';
@ -50,6 +51,7 @@ void main() {
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
MealScheduleService.resetForTesting(store: FileDocumentStore(tempDir));
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
notificationLog = installFakeAndroidNotifications();
@ -63,6 +65,7 @@ void main() {
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
NotificationService.resetForTesting();
await tempDir.delete(recursive: true);
});
@ -83,7 +86,10 @@ void main() {
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(shown, {8, 16});
expect(cancelled, {12, 20});
// Every other id in the 0..23 space is cancelled, not just the other
// slots of the current schedule -- see syncToSlots' comment.
expect(cancelled, containsAll(<int>{12, 20}));
expect(cancelled.intersection(shown), isEmpty);
},
);
@ -93,7 +99,9 @@ void main() {
await checkAndNotify(now: DateTime(2026, 1, 1, 8));
expect(notificationLog.where((c) => c.method == 'show'), isEmpty);
expect(notificationLog.where((c) => c.method == 'cancel'), hasLength(4));
// 24, not 4: syncToSlots sweeps the whole id space so a schedule change
// cannot orphan the ids it no longer contains.
expect(notificationLog.where((c) => c.method == 'cancel'), hasLength(24));
});
test('uses the real clock when now is omitted', () async {

View File

@ -0,0 +1,146 @@
/// Tests for the pure meal-schedule history: parsing, encoding, forDay,
/// upsert and seeding.
///
/// Split from `meal_schedule_service_test.dart` (250-line cap); that file
/// keeps the persistence half. Mirrors
/// `diet_guard/tests/test_meal_schedule_store.py`.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/services/meal_schedule_history.dart';
import 'package:flutter_test/flutter_test.dart';
DateTime _at(String day) => DateTime.parse('${day}T12:00:00');
void main() {
group('scheduleEntryFromJson', () {
test('round trips', () {
const entry = ScheduleEntry(
effectiveFrom: '2026-08-16',
schedule: MealSchedule(first: 8, last: 20, count: 5),
editedAt: '2026-08-16T12:00:00.000',
);
expect(
scheduleEntryFromJson('2026-08-16', scheduleEntryToJson(entry)),
entry,
);
});
test('normalizes on the way in', () {
final entry = scheduleEntryFromJson('2026-08-16', {
'f': 8,
'l': 20,
'n': 99,
});
expect(entry!.schedule, const MealSchedule(first: 8, last: 20, count: 6));
});
test('falls back to the epoch when the stamp is missing', () {
final entry = scheduleEntryFromJson('2026-08-16', {
'f': 8,
'l': 20,
'n': 4,
});
expect(entry!.editedAt, '1970-01-01T00:00:00.000Z');
});
test('rejects a non-mapping', () {
expect(scheduleEntryFromJson('2026-08-16', 'nonsense'), isNull);
});
test('rejects non-integer fields', () {
expect(
scheduleEntryFromJson('2026-08-16', {'f': '8', 'l': 20, 'n': 4}),
isNull,
);
});
});
group('MealScheduleHistory', () {
test('parse degrades on anything unreadable', () {
expect(MealScheduleHistory.parse('nonsense'), isEmpty);
expect(MealScheduleHistory.parse({'e': 'nonsense'}), isEmpty);
expect(MealScheduleHistory.parse(const <String, Object?>{}), isEmpty);
});
test('parse skips only the bad entry', () {
final parsed = MealScheduleHistory.parse(const {
'e': {
'2026-01-01': {'f': 8, 'l': 20, 'n': 4},
'2026-02-01': 7,
},
});
expect(parsed.map((e) => e.effectiveFrom), ['2026-01-01']);
});
test('parse ignores a non-string key', () {
final parsed = MealScheduleHistory.parse(const {
'e': {
7: {'f': 8, 'l': 20, 'n': 4},
},
});
expect(parsed, isEmpty);
});
test('forDay defaults when the history is silent', () {
final history = MealScheduleHistory(const [
ScheduleEntry(
effectiveFrom: '2026-08-16',
schedule: MealSchedule(first: 8, last: 20, count: 5),
editedAt: 't',
),
]);
expect(history.forDay('2026-08-15'), kDefaultSchedule);
});
test('forDay uses the newest applicable entry', () {
final history = MealScheduleHistory(const [
ScheduleEntry(
effectiveFrom: '2026-08-16',
schedule: MealSchedule(first: 8, last: 20, count: 5),
editedAt: 't1',
),
ScheduleEntry(
effectiveFrom: '2026-01-01',
schedule: kDefaultSchedule,
editedAt: 't0',
),
]);
expect(
history.forDay('2026-08-16'),
const MealSchedule(first: 8, last: 20, count: 5),
);
expect(history.forDay('2026-05-01'), kDefaultSchedule);
});
test('upsert replaces a same-day re-edit', () {
final once = MealScheduleHistory.empty.upsert(
const MealSchedule(first: 8, last: 20, count: 5),
when: _at('2026-08-16'),
);
final twice = once.upsert(
const MealSchedule(first: 9, last: 21, count: 3),
when: _at('2026-08-16'),
);
expect(twice.entries, hasLength(1));
expect(
twice.entries.single.schedule,
const MealSchedule(first: 9, last: 21, count: 3),
);
});
test('upsert defaults to now', () {
final history = MealScheduleHistory.empty.upsert(
const MealSchedule(first: 8, last: 20, count: 5),
);
expect(history.entries, hasLength(1));
});
test('seedDefault pins the default at the epoch and is idempotent', () {
final seeded = MealScheduleHistory.empty.seedDefault();
expect(seeded.entries.first.effectiveFrom, kScheduleEpochDay);
expect(seeded.entries.first.schedule, kDefaultSchedule);
expect(seeded.seedDefault().entries, hasLength(1));
});
});
}

View File

@ -0,0 +1,147 @@
/// Tests for meal-schedule persistence.
///
/// Split from `meal_schedule_history_test.dart` (250-line cap); that file
/// keeps the pure parsing/derivation half. Mirrors the storage half of
/// `diet_guard/tests/test_meal_schedule_store.py`.
library;
import 'dart:convert';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/meal_schedule_history.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
DateTime _at(String day) => DateTime.parse('${day}T12:00:00');
void main() {
late _MemoryStore store;
setUp(() {
store = _MemoryStore();
MealScheduleService.resetForTesting(store: store);
});
tearDown(MealScheduleService.resetForTesting);
group('MealScheduleService', () {
test('current is the default before any edit', () {
expect(MealScheduleService.current, kDefaultSchedule);
expect(MealScheduleService.updatedAt, isNull);
});
test('current degrades to the default when uninitialised', () {
MealScheduleService.resetForTesting();
expect(MealScheduleService.current, kDefaultSchedule);
expect(MealScheduleService.history.entries, isEmpty);
expect(MealScheduleService.isInitialized, isFalse);
});
test(
'recordChange persists, reloads, and grandfathers past days',
() async {
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
);
await MealScheduleService.initForTesting(store);
expect(
MealScheduleService.current,
const MealSchedule(first: 8, last: 20, count: 5),
);
// The whole point of the history: a day before the edit keeps the
// four-meal schedule it was actually judged against.
expect(
MealScheduleService.history.forDay('2020-01-01'),
kDefaultSchedule,
);
expect(MealScheduleService.updatedAt, isNotNull);
},
);
test('a corrupt document degrades to the default', () async {
store.documents[MealScheduleService.documentName] = '{not json';
await MealScheduleService.initForTesting(store);
expect(MealScheduleService.current, kDefaultSchedule);
});
test('an absent document loads as no history', () async {
await MealScheduleService.initForTesting(store);
expect(MealScheduleService.history.entries, isEmpty);
});
test(
'updatedAt stays null when the stored stamp is not a string',
() async {
store.documents[MealScheduleService.documentName] = jsonEncode({
'v': 1,
'e': <String, Object?>{},
't': 7,
});
await MealScheduleService.initForTesting(store);
expect(MealScheduleService.updatedAt, isNull);
},
);
test(
'applyMerged replaces the history but ignores an empty merge',
() async {
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
);
// A pre-feature peer contributes no `sched:` fields; writing that back
// would discard this device's own history.
await MealScheduleService.instance.applyMerged(const []);
expect(
MealScheduleService.current,
const MealSchedule(first: 8, last: 20, count: 5),
);
final stamp = DateTime.parse('2026-08-16T09:00:00.000');
await MealScheduleService.instance.applyMerged([
ScheduleEntry(
effectiveFrom: kScheduleEpochDay,
schedule: const MealSchedule(first: 7, last: 19, count: 3),
editedAt: stamp.toIso8601String(),
),
], updatedAt: stamp);
expect(
MealScheduleService.current,
const MealSchedule(first: 7, last: 19, count: 3),
);
// The winner's stamp is kept verbatim, so re-syncing is idempotent.
expect(MealScheduleService.updatedAt, stamp);
},
);
test('the stored document is plain readable JSON', () async {
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
when: _at('2026-08-16'),
);
final decoded =
jsonDecode(store.documents[MealScheduleService.documentName]!)
as Map<String, Object?>;
expect(decoded['v'], 1);
expect((decoded['e']! as Map).keys, contains('2026-08-16'));
});
});
}

View File

@ -60,10 +60,13 @@ void main() {
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(shown, {12, 20});
expect(cancelled, {8, 16});
// Every other id in the 0..23 space is cancelled, not just the other
// slots of the current schedule -- see syncToSlots' comment.
expect(cancelled, containsAll(<int>{8, 16}));
expect(cancelled.intersection(shown), isEmpty);
});
test('syncToSlots with no due slots cancels every known slot', () async {
test('syncToSlots with no due slots cancels every id in the day', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
@ -74,7 +77,34 @@ void main() {
await NotificationService.instance.syncToSlots(const []);
expect(log.where((c) => c.method == 'show'), isEmpty);
expect(log.where((c) => c.method == 'cancel'), hasLength(4));
// 24, not 4: the slot hour doubles as the notification id, so a
// schedule change would otherwise orphan the ids it no longer contains.
expect(log.where((c) => c.method == 'cancel'), hasLength(24));
});
test('syncToSlots cancels ids orphaned by a schedule change', () async {
// The regression this guards: the slot hour *is* the notification id,
// and syncToSlots used to iterate only the current schedule's slots.
// Switching 08/12/16/20 -> 08/11/14/17/20 therefore left ids 12 and 16
// posted with nothing that would ever cancel them, so the phone nagged
// forever about checkpoints that no longer existed.
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
// Due under the old four-meal schedule.
await NotificationService.instance.syncToSlots([12, 16]);
log.clear();
// Now due under a five-meal schedule, which has neither 12 nor 16.
await NotificationService.instance.syncToSlots([11]);
final cancelled = log
.where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(cancelled, containsAll(<int>{12, 16}));
});
test(

View File

@ -0,0 +1,171 @@
/// Tests for the meal-schedule half of the shared `budget` CRDT record.
///
/// Mirrors `diet_guard/tests/test_sync_merge_schedule.py`.
library;
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/services/meal_schedule_history.dart';
import 'package:diet_guard_app/services/sync_merge_budget.dart';
import 'package:diet_guard_app/services/sync_merge_schedule.dart';
import 'package:flutter_test/flutter_test.dart';
const _record = <String, dynamic>{
'v': 2,
'b': 2200,
't': '2026-08-16T10:00:00+02:00',
};
ScheduleEntry _entry(String day, MealSchedule schedule, String when) =>
ScheduleEntry(effectiveFrom: day, schedule: schedule, editedAt: when);
String _wire(Log log) => jsonEncode({
for (final entry in log.entries) entry.key: entry.value.toJson(),
});
void main() {
group('scheduleFields', () {
test('no entries contributes nothing', () {
// A device that never edited a schedule cannot outrank a peer.
expect(scheduleFields(const []), isEmpty);
});
test('one field per entry', () {
final fields = scheduleFields([
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00',
),
]);
expect(fields.keys, ['${scheduleFieldPrefix}2026-08-16']);
expect(fields['${scheduleFieldPrefix}2026-08-16']!.$1, {
'f': 8,
'l': 20,
'n': 5,
});
});
test('the Hlc is deterministic', () {
final entry = _entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00',
);
expect(
scheduleHlc(entry).wallTimeMs,
scheduleHlc(entry).wallTimeMs,
);
});
test('an unparsable timestamp falls back to the epoch', () {
final entry = _entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
'not-a-timestamp',
);
expect(scheduleHlc(entry).wallTimeMs, 0);
});
});
group('logToScheduleHistory', () {
test('an absent record yields nothing', () {
expect(logToScheduleHistory(const {}), isEmpty);
});
test('round trips', () {
final back = logToScheduleHistory(
budgetToLog(_record, const [], [
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00',
),
]),
);
expect(back, hasLength(1));
expect(back.single.effectiveFrom, '2026-08-16');
expect(
back.single.schedule,
const MealSchedule(first: 8, last: 20, count: 5),
);
});
test("normalizes a peer's out-of-range schedule", () {
final log = budgetToLog(_record);
final record = log[budgetRecordId]!;
final hlc = record.fields.values.first.$2;
record.fields['${scheduleFieldPrefix}2026-08-16'] = (
{'f': 8, 'l': 20, 'n': 99},
hlc,
);
expect(
logToScheduleHistory(log).single.schedule,
const MealSchedule(first: 8, last: 20, count: 6),
);
});
test('skips malformed values', () {
final log = budgetToLog(_record);
final record = log[budgetRecordId]!;
final hlc = record.fields.values.first.$2;
record.fields['${scheduleFieldPrefix}2026-01-01'] = (7, hlc);
record.fields['${scheduleFieldPrefix}2026-02-01'] = ({'f': '8'}, hlc);
expect(logToScheduleHistory(log), isEmpty);
});
});
group('cross-device merge', () {
test('a pre-feature peer relays the schedule untouched', () {
// `mergeRecord` is per-field LWW over the *union* of field names, and
// both devices push the merged record, so a budget-only push merges the
// fields in rather than clobbering them. This is what makes the feature
// shippable without a coordinated release.
final ours = budgetToLog(_record, const [], [
_entry('1970-01-01', kDefaultSchedule, '1970-01-01T00:00:00.000Z'),
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00',
),
]);
final peer = budgetToLog(const <String, dynamic>{
'v': 2,
'b': 1900,
't': '2026-08-16T11:00:00+02:00',
});
final merged = mergeLogs(parseRemoteBudget(_wire(ours)), peer);
expect(logToScheduleHistory(merged).map((e) => e.schedule), [
kDefaultSchedule,
const MealSchedule(first: 8, last: 20, count: 5),
]);
});
test('the newer edit wins per day', () {
final older = budgetToLog(_record, const [], [
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00',
),
]);
final newer = budgetToLog(_record, const [], [
_entry(
'2026-08-16',
const MealSchedule(first: 7, last: 21, count: 3),
'2026-08-16T18:00:00+02:00',
),
]);
final merged = mergeLogs(parseRemoteBudget(_wire(older)), newer);
expect(
logToScheduleHistory(merged).single.schedule,
const MealSchedule(first: 7, last: 21, count: 3),
);
});
});
}

View File

@ -1,3 +1,4 @@
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:flutter/material.dart';
@ -27,8 +28,11 @@ void main() {
testWidgets('renders exactly one chip per day slot', (tester) async {
await _pump(tester, now: DateTime(2026, 8, 14, 13));
expect(find.byType(ChoiceChip), findsNWidgets(daySlots().length));
for (final slot in daySlots()) {
expect(
find.byType(ChoiceChip),
findsNWidgets(daySlots(kDefaultSchedule).length),
);
for (final slot in daySlots(kDefaultSchedule)) {
expect(find.text(slotLabel(slot)), findsOneWidget);
}
});
@ -52,11 +56,11 @@ void main() {
onSlotSelected: selected.add,
);
for (final slot in daySlots()) {
for (final slot in daySlots(kDefaultSchedule)) {
await tester.tap(find.text(slotLabel(slot)));
}
expect(selected, daySlots());
expect(selected, daySlots(kDefaultSchedule));
expect(selected, isNot(contains(null)));
});
@ -64,14 +68,14 @@ void main() {
await _pump(
tester,
now: DateTime(2026, 8, 14, 13),
loggedSlots: {daySlots().first},
loggedSlots: {daySlots(kDefaultSchedule).first},
);
expect(find.byIcon(Icons.check), findsOneWidget);
});
testWidgets('marks the selected slot', (tester) async {
final slot = daySlots().first;
final slot = daySlots(kDefaultSchedule).first;
await _pump(
tester,
now: DateTime(2026, 8, 14, 13),
@ -86,5 +90,46 @@ void main() {
);
expect(chip.selected, isTrue);
});
// The row used to be a Wrap, which pushed the later pills onto a second
// line: a logged chip is ~124px at Material defaults, so even four need
// more width than a phone has. Both halves below matter -- a Row of
// Expanded children also passes the "one line" check while squeezing each
// label to ~10px (about one character) and throwing nothing at all.
testWidgets('keeps every chip on one legible row at phone widths', (
tester,
) async {
for (final width in <double>[320, 360, 412]) {
tester.view.physicalSize = Size(width, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
// Every slot logged is the widest case: each chip carries a check
// avatar on top of its label.
await _pump(
tester,
now: DateTime(2026, 8, 14, 21),
loggedSlots: daySlots(kDefaultSchedule).toSet(),
);
expect(tester.takeException(), isNull, reason: 'overflowed at $width');
final labels = daySlots(
kDefaultSchedule,
).map((slot) => tester.getRect(find.text(slotLabel(slot)))).toList();
for (final label in labels) {
expect(
label.top,
moreOrLessEquals(labels.first.top, epsilon: 0.5),
reason: 'chip wrapped to a second line at $width',
);
expect(
label.width,
greaterThan(20),
reason: 'label squeezed to ${label.width}px at $width',
);
}
}
});
});
}

View File

@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
TodayProgress _progress({
String justLogged = 'toast',
double consumedKcal = 1450,
int budgetKcal = 2200,
double proteinG = 90,
@ -11,7 +10,6 @@ TodayProgress _progress({
double fatG = 40,
int adherenceStreak = 3,
}) => TodayProgress(
justLogged: justLogged,
consumedKcal: consumedKcal,
budgetKcal: budgetKcal,
proteinG: proteinG,
@ -48,12 +46,14 @@ void main() {
});
group('TodayProgressCard', () {
testWidgets('shows the meal, the kcal position, and macros', (
testWidgets('shows the kcal position and macros, but not the meal', (
tester,
) async {
await _pump(tester, _progress());
expect(find.text('Logged "toast".'), findsOneWidget);
// The `Logged "<meal>".` line was removed 2026-08-16 -- it restated
// what the user had just typed. Pinned so it does not creep back.
expect(find.textContaining('Logged'), findsNothing);
expect(find.text('1450 / 2200'), findsOneWidget);
expect(find.text('750 left'), findsOneWidget);
expect(find.text('P 90g · C 120g · F 40g'), findsOneWidget);

View File

@ -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:

View File

@ -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 <number> 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"

View File

@ -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:

View File

@ -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:

View File

@ -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 []

View File

@ -37,7 +37,6 @@ from diet_guard._calendar_view import (
ytd_text,
)
from diet_guard._daystatus import DayStatus, status_map
from diet_guard._gatelock_budgetedit import _GateBudgetEdit
from diet_guard._gatelock_calendar_ui import (
_DECEMBER,
_DEFAULT_BUDGET_KCAL,
@ -51,6 +50,10 @@ from diet_guard._gatelock_calendar_ui import (
make_calendar_vars,
)
from diet_guard._gatelock_layout import build_layout
from diet_guard._gatelock_scheduleedit import _GateScheduleEdit
from diet_guard._meal_schedule_store import (
current_schedule as current_meal_schedule,
)
from diet_guard._state import load_log, now_local
if TYPE_CHECKING:
@ -69,7 +72,7 @@ __all__ = [
]
class _GateCalendar(_GateBudgetEdit):
class _GateCalendar(_GateScheduleEdit):
"""History tab: calendar, streaks, YTD tally, and budget editing."""
_cal_vars: CalendarVars
@ -78,6 +81,7 @@ class _GateCalendar(_GateBudgetEdit):
_cal_year: int
_cal_month: int
_cal_editing_budget: bool
_cal_editing_schedule: bool
_notebook: ttk.Notebook
def _build_tabs(self, parent: tk.Misc, callbacks: GateCallbacks) -> GateWidgets:
@ -95,6 +99,7 @@ class _GateCalendar(_GateBudgetEdit):
self._cal_year = today.year
self._cal_month = today.month
self._cal_editing_budget = False
self._cal_editing_schedule = False
_style_notebook(parent)
notebook = ttk.Notebook(parent)
notebook.place(relx=0, rely=0, relwidth=1, relheight=1)
@ -109,6 +114,7 @@ class _GateCalendar(_GateBudgetEdit):
on_prev_month=self._on_prev_month,
on_next_month=self._on_next_month,
on_edit_or_save_budget=self._on_edit_or_save_budget,
on_edit_or_save_schedule=self._on_edit_or_save_schedule,
)
cal_widgets = build_calendar_frame(notebook, self._cal_vars, cal_callbacks)
notebook.add(cal_widgets.frame, text="History")
@ -162,6 +168,8 @@ class _GateCalendar(_GateBudgetEdit):
self._cal_vars.averages.set(averages_text(log, schedule=schedule))
if not self._cal_editing_budget:
self._refresh_budget_field(budget)
if not self._cal_editing_schedule:
self._show_schedule(current_meal_schedule())
def _render_month(self, status_map_: dict[str, DayStatus] | None) -> None:
"""Redraw the day-cell grid and month label for the displayed month."""

View File

@ -0,0 +1,109 @@
"""The History tab's meal-schedule row widgets.
Split out of :mod:`._gatelock_calendar_widgets` (216 lines against the repo's
250-line cap) rather than added to it. The behaviour behind these widgets
lives in :mod:`._gatelock_scheduleedit`, mirroring how the budget row's
widgets and its edit/save logic are split.
"""
from __future__ import annotations
import tkinter as tk
from typing import TYPE_CHECKING
from gatelock import make_button
from diet_guard._gatelock_calendar_types import _COLORS, _FIELD_BG
from diet_guard._gatelock_spacing import SM, XS
from diet_guard._gatelock_typography import BODY, LABEL
from diet_guard._gatelock_ui import BG, FG
if TYPE_CHECKING:
from collections.abc import Callable
from diet_guard._gatelock_calendar_types import CalendarVars
__all__ = ["build_schedule_row"]
_ENTRY_WIDTH = 4
def _spin_entry(row: tk.Frame, variable: tk.StringVar) -> tk.Entry:
"""Return one read-only-by-default numeric entry in the schedule row."""
entry = tk.Entry(
row,
textvariable=variable,
font=(_COLORS.font_family, BODY),
width=_ENTRY_WIDTH,
bg=_FIELD_BG,
fg=FG,
insertbackground=FG,
justify="center",
state="readonly",
readonlybackground=_FIELD_BG,
)
entry.pack(side="left", padx=(XS, SM), ipady=XS)
return entry
def build_schedule_row(
parent: tk.Frame,
vars_: CalendarVars,
on_edit_or_save_schedule: Callable[[], None],
) -> tuple[tk.Entry, tk.Entry, tk.Entry, tk.Button, tk.Label]:
"""Build the meal-schedule row.
Returns the three hour/count entries, the edit button, and the status
label, in that order. Like the budget row the entries start read-only:
the schedule is displayed but not directly typeable until "Edit".
Returns:
``(first_entry, last_entry, count_entry, edit_button, status_label)``.
"""
row = tk.Frame(parent, bg=BG)
row.pack(pady=(SM, XS))
tk.Label(
row,
text="Meals:",
font=(_COLORS.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
first_entry = _spin_entry(row, vars_.schedule.first)
tk.Label(
row,
text="to",
font=(_COLORS.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
last_entry = _spin_entry(row, vars_.schedule.last)
tk.Label(
row,
text="x",
font=(_COLORS.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
count_entry = _spin_entry(row, vars_.schedule.count)
edit_button = make_button(row, _COLORS, "Edit", on_edit_or_save_schedule)
edit_button.pack(side="left")
# The derived checkpoint times, so the effect of a change is visible
# before it is saved rather than only after the next lock.
tk.Label(
parent,
textvariable=vars_.schedule.times,
font=(_COLORS.font_family, LABEL),
bg=BG,
fg=FG,
).pack(pady=(0, XS))
status_label = tk.Label(
parent,
textvariable=vars_.schedule.status,
font=(_COLORS.font_family, LABEL),
bg=BG,
fg=FG,
)
status_label.pack(pady=(0, XS))
return first_entry, last_entry, count_entry, edit_button, status_label

View File

@ -45,10 +45,27 @@ __all__ = [
"CalendarCallbacks",
"CalendarVars",
"CalendarWidgets",
"ScheduleVars",
"make_calendar_vars",
]
@dataclass
class ScheduleVars:
"""Tk string variables backing the History tab's meal-schedule row.
Grouped rather than flattened into :class:`CalendarVars`, which would
otherwise carry eleven fields for two unrelated concerns.
"""
status: tk.StringVar
first: tk.StringVar
last: tk.StringVar
count: tk.StringVar
times: tk.StringVar
"""The derived checkpoint times, e.g. ``"08:00 11:00 14:00"``."""
@dataclass
class CalendarVars:
"""Tk string variables bound to the History tab's live fields."""
@ -60,6 +77,7 @@ class CalendarVars:
budget_status: tk.StringVar
budget: tk.StringVar
"""Backs the budget entry so its per-monitor copies cannot disagree."""
schedule: ScheduleVars
@dataclass
@ -71,6 +89,11 @@ class CalendarWidgets:
budget_entry: tk.Entry
budget_edit_button: tk.Button
budget_status_label: tk.Label
schedule_first_entry: tk.Entry
schedule_last_entry: tk.Entry
schedule_count_entry: tk.Entry
schedule_edit_button: tk.Button
schedule_status_label: tk.Label
@dataclass
@ -80,6 +103,7 @@ class CalendarCallbacks:
on_prev_month: Callable[[], None]
on_next_month: Callable[[], None]
on_edit_or_save_budget: Callable[[], None]
on_edit_or_save_schedule: Callable[[], None]
def make_calendar_vars(root: tk.Misc) -> CalendarVars:
@ -91,4 +115,11 @@ def make_calendar_vars(root: tk.Misc) -> CalendarVars:
averages=tk.StringVar(master=root, value=""),
budget_status=tk.StringVar(master=root, value=""),
budget=tk.StringVar(master=root, value=""),
schedule=ScheduleVars(
status=tk.StringVar(master=root, value=""),
first=tk.StringVar(master=root, value=""),
last=tk.StringVar(master=root, value=""),
count=tk.StringVar(master=root, value=""),
times=tk.StringVar(master=root, value=""),
),
)

View File

@ -20,6 +20,7 @@ from typing import TYPE_CHECKING
from gatelock import ButtonStyle, make_button
from diet_guard._gatelock_calendar_schedule import build_schedule_row
from diet_guard._gatelock_calendar_types import (
_ACCENT,
_COLORS,
@ -182,6 +183,17 @@ def build_calendar_frame(
vars_,
callbacks.on_edit_or_save_budget,
)
(
schedule_first_entry,
schedule_last_entry,
schedule_count_entry,
schedule_edit_button,
schedule_status_label,
) = build_schedule_row(
frame,
vars_,
callbacks.on_edit_or_save_schedule,
)
_build_month_nav(frame, vars_, callbacks)
day_cells = _build_grid(frame)
@ -213,4 +225,9 @@ def build_calendar_frame(
budget_entry=budget_entry,
budget_edit_button=budget_edit_button,
budget_status_label=budget_status_label,
schedule_first_entry=schedule_first_entry,
schedule_last_entry=schedule_last_entry,
schedule_count_entry=schedule_count_entry,
schedule_edit_button=schedule_edit_button,
schedule_status_label=schedule_status_label,
)

View File

@ -0,0 +1,152 @@
"""Meal-schedule editing on the gate's History tab.
Sibling of :mod:`._gatelock_budgetedit`, with the same edit/save toggle shape:
the row displays the schedule read-only, "Edit" unlocks it, "Save" validates
and persists. ``_GateScheduleEdit`` sits between
:class:`~diet_guard._gatelock_budgetedit._GateBudgetEdit` and
:class:`~diet_guard._gatelock_calendar._GateCalendar` in the mixin chain.
Editing here changes what the gate itself asks for, so the value is validated
before it is written rather than relying on
:meth:`~diet_guard._meal_schedule.MealSchedule.normalized` to clamp it. The
clamp is the defence against a peer's corrupt sync data; a typo at the
keyboard should say so instead of silently becoming a different schedule.
"""
from __future__ import annotations
import abc
import contextlib
import tkinter as tk
from diet_guard._gatelock_budgetedit import _GateBudgetEdit
from diet_guard._gatelock_ui import ERR, FG
from diet_guard._meal_schedule import (
FIRST_HOUR,
LAST_HOUR,
MAX_MEAL_COUNT,
MIN_MEAL_COUNT,
MealSchedule,
)
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
from diet_guard._slots import day_slots, slot_label
__all__ = ["_GateScheduleEdit", "schedule_summary"]
def schedule_summary(schedule: MealSchedule) -> str:
"""Return the derived checkpoint times, e.g. ``"08:00 11:00 ..."``."""
return " ".join(slot_label(slot) for slot in day_slots(schedule))
class _GateScheduleEdit(_GateBudgetEdit):
"""The History tab's meal-schedule row: display, edit, validate, persist.
Like :class:`~diet_guard._gatelock_budgetedit._GateBudgetEdit`, this half
only reads and writes its own row; the tab's construction and refresh are
owned by :class:`~diet_guard._gatelock_calendar._GateCalendar`, further
down the mixin chain.
"""
_cal_editing_schedule: bool
@abc.abstractmethod
def _refresh_calendar(self) -> None:
"""Repaint the History tab; implemented by ``_GateCalendar``."""
def _set_schedule_entry_state(self, state: str) -> None:
"""Lock or unlock the three schedule entries on every monitor."""
for surface in self._cal_surfaces:
with contextlib.suppress(tk.TclError):
surface.schedule_first_entry.config(state=state)
surface.schedule_last_entry.config(state=state)
surface.schedule_count_entry.config(state=state)
def _set_schedule_button_text(self, text: str) -> None:
"""Relabel the schedule edit/save button on every monitor."""
for surface in self._cal_surfaces:
with contextlib.suppress(tk.TclError):
surface.schedule_edit_button.config(text=text)
def _set_schedule_status(self, text: str, *, error: bool) -> None:
"""Update the schedule-edit status line, red for errors."""
self._cal_vars.schedule.status.set(text)
colour = ERR if error else FG
for surface in self._cal_surfaces:
with contextlib.suppress(tk.TclError):
surface.schedule_status_label.config(fg=colour)
def _show_schedule(self, schedule: MealSchedule) -> None:
"""Populate the row's fields and derived-times label."""
self._cal_vars.schedule.first.set(str(schedule.first))
self._cal_vars.schedule.last.set(str(schedule.last))
self._cal_vars.schedule.count.set(str(schedule.count))
self._cal_vars.schedule.times.set(schedule_summary(schedule))
def _on_edit_or_save_schedule(self) -> None:
"""Toggle the schedule row between read-only display and editing.
Mirrors :meth:`_GateBudgetEdit._on_edit_or_save_budget`: a failed
validation leaves editing open so the value can be corrected rather
than silently discarded.
"""
if not self._cal_editing_schedule:
self._cal_editing_schedule = True
self._set_schedule_entry_state("normal")
self._set_schedule_button_text("Save")
self._set_schedule_status("", error=False)
return
if not self._save_schedule_entry():
return
self._cal_editing_schedule = False
self._set_schedule_entry_state("readonly")
self._set_schedule_button_text("Edit")
self._refresh_calendar()
def _read_schedule_fields(self) -> MealSchedule | None:
"""Parse the three entries, or None (with a status set) if unusable."""
raw = (
self._cal_vars.schedule.first.get().strip(),
self._cal_vars.schedule.last.get().strip(),
self._cal_vars.schedule.count.get().strip(),
)
try:
first, last, count = (int(value) for value in raw)
except ValueError:
self._set_schedule_status("Enter whole hours, e.g. 8 20 5.", error=True)
return None
return MealSchedule(first, last, count)
def _save_schedule_entry(self) -> bool:
"""Validate and persist the row's current values.
Returns:
Whether the schedule was valid and persisted.
"""
schedule = self._read_schedule_fields()
if schedule is None:
return False
if not FIRST_HOUR <= schedule.first < schedule.last <= LAST_HOUR:
self._set_schedule_status(
f"First meal must be before the last, both {FIRST_HOUR}-{LAST_HOUR}.",
error=True,
)
return False
if not MIN_MEAL_COUNT <= schedule.count <= MAX_MEAL_COUNT:
self._set_schedule_status(
f"Meals per day must be {MIN_MEAL_COUNT}-{MAX_MEAL_COUNT}.",
error=True,
)
return False
# A window of N hours holds at most N+1 whole-hour checkpoints; asking
# for more would round two meals onto the same hour.
if schedule.count > schedule.last - schedule.first + 1:
self._set_schedule_status(
"Too many meals for that window -- widen it or eat less often.",
error=True,
)
return False
record_schedule_change(schedule)
self._show_schedule(current_schedule())
self._set_schedule_status("Saved.", error=False)
return True

View File

@ -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=<number> 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,

View File

@ -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),
}

View File

@ -0,0 +1,134 @@
"""The user's eating window and meal count, and the slot hours they imply.
A schedule is three numbers -- the first meal hour, the last meal hour, and how
many meals fall between them inclusive -- from which the intermediate
checkpoints are derived by even division. ``MealSchedule(8, 20, 5)`` yields
``(8, 11, 14, 17, 20)``.
This module is pure: no clock, no filesystem, no configuration lookup. Storage
lives in :mod:`diet_guard._meal_schedule_store`, and the slot arithmetic that
consumes a schedule lives in :mod:`diet_guard._slots`.
KEEP IN SYNC WITH ``app/lib/models/meal_schedule.dart``. The two must agree on
every input, because a device that derives different slots than its peer nags
for checkpoints the other never offers -- and a slot that can never be
satisfied is a permanent lock. Two rules make that agreement checkable:
* **Integer arithmetic only.** No floats and no ``round()`` anywhere in the
derivation. Python's ``round`` is banker's rounding (``round(2.5) == 2``)
while Dart's is half-away-from-zero (``2.5.round() == 3``), so any float path
is a latent cross-language split brain. ``//`` here, ``~/`` there.
* **Clamp, don't reject.** Every out-of-range input is normalised to the
nearest legal schedule rather than raising, so the two languages cannot
disagree about which inputs are errors.
"""
from __future__ import annotations
from dataclasses import dataclass
# A day's meals must fit inside a day, and the pills that render them have to
# stay legible on a phone at the widest (all-logged) size -- see
# ``app/test/widgets/slot_selector_row_test.dart``.
MIN_MEAL_COUNT = 2
MAX_MEAL_COUNT = 6
FIRST_HOUR = 0
LAST_HOUR = 23
# Grace period after the final checkpoint, before the gate stops firing for
# the day. Deliberately a constant rather than the slot spacing: it is how
# long you have to log a late dinner, which has nothing to do with how many
# meals you eat. Tying it to the spacing would stretch the lockout window to
# midnight at four meals, contradicting the "don't trap me overnight" intent
# this cutoff exists to serve.
ENFORCEMENT_TAIL_HOURS = 2
_HOURS_PER_DAY = 24
def _clamp(value: int, low: int, high: int) -> int:
"""Return ``value`` confined to ``[low, high]``."""
return max(low, min(high, value))
@dataclass(frozen=True)
class MealSchedule:
"""An eating window and the number of meals inside it.
Attributes:
first: Hour of the first meal, 0-23.
last: Hour of the last meal, strictly after ``first``.
count: Total meals including both endpoints.
"""
first: int
last: int
count: int
def normalized(self) -> MealSchedule:
"""Return an equivalent schedule guaranteed to satisfy the invariants.
Ordering matters: ``first`` is clamped into the day, then ``last`` is
clamped to leave at least one hour of window, then ``count`` is clamped
to the window's width. That last clamp is the load-bearing one -- see
:meth:`slots`.
Returns:
A schedule whose ``slots()`` is strictly ascending.
"""
first = _clamp(self.first, FIRST_HOUR, LAST_HOUR - 1)
last = _clamp(self.last, first + 1, LAST_HOUR)
# A window of N hours holds at most N+1 whole-hour checkpoints; asking
# for more would repeat an hour (see slots()).
count = _clamp(
self.count, MIN_MEAL_COUNT, min(MAX_MEAL_COUNT, last - first + 1)
)
return MealSchedule(first, last, count)
def slots(self) -> tuple[int, ...]:
"""Return the meal-slot hours, ascending, endpoints exact.
Meals are spread evenly across the window and rounded to whole hours by
integer arithmetic: slot *i* is ``first + (i*span + d//2) // d`` where
``span = last - first`` and ``d = count - 1``. The ``d//2`` term is a
round-half-up bias applied before the division, which is what keeps
this float-free.
Both endpoints land exactly on ``first`` and ``last`` by construction,
so the eating window is always honoured even when the interior spacing
has to round.
The result is strictly ascending because :meth:`normalized` caps
``count`` at ``last - first + 1``. Without that cap a narrow window
repeats an hour (``08-12`` with 6 meals would give
``8, 9, 10, 10, 11, 12``), and since slot hours are used as set
members, dict keys *and* notification ids, a repeat silently drops a
checkpoint.
Returns:
The slot hours, ascending, of length ``normalized().count``.
"""
schedule = self.normalized()
span = schedule.last - schedule.first
divisions = schedule.count - 1
return tuple(
schedule.first + (index * span + divisions // 2) // divisions
for index in range(schedule.count)
)
@property
def enforcement_end_hour(self) -> int:
"""Return the hour at which slot enforcement stops for the day.
Clamped to the end of the day: a 23:00 last meal would otherwise put
the cutoff at 25, making ``hour < cutoff`` vacuously true so the
enforcement window never closes and the gate can never stop firing.
"""
return min(self.last + ENFORCEMENT_TAIL_HOURS, _HOURS_PER_DAY)
# The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, with the
# enforcement window closing at 22:00. Still what a device uses before the
# user has ever chosen anything, so upgrading changes no behaviour.
DEFAULT_SCHEDULE = MealSchedule(first=8, last=20, count=4)

View File

@ -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:<YYYY-MM-DD>`` *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)))

View File

@ -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]

View File

@ -28,6 +28,15 @@ from diet_guard._budget_history import (
from diet_guard._device import device_identity
from diet_guard._foodbank import read_food_bank, write_food_bank
from diet_guard._foodbank_manual import read_manual_bank, write_manual_bank
from diet_guard._meal_schedule_store import (
history_to_json as schedule_history_to_json,
)
from diet_guard._meal_schedule_store import (
load_entries as load_schedule_entries,
)
from diet_guard._meal_schedule_store import (
write_raw_history as write_raw_schedule,
)
from diet_guard._sync_paths import (
_DEVICES_DIR,
_device_budget_path,
@ -41,6 +50,7 @@ from diet_guard.sync_merge import (
log_to_food_bank,
log_to_history,
log_to_manual_bank,
log_to_schedule_history,
manual_bank_to_log,
parse_remote_budget,
parse_remote_food_bank,
@ -161,7 +171,7 @@ def _sync_budget(client: GitHubSyncClient) -> None:
*no* device has ever set one, nothing is written or pushed.
"""
identity = device_identity()
merged = budget_to_log(read_raw_record(), load_entries())
merged = budget_to_log(read_raw_record(), load_entries(), load_schedule_entries())
for device_id in client.list_directory(_DEVICES_DIR):
if identity.is_own(device_id):
continue
@ -187,6 +197,12 @@ def _sync_budget(client: GitHubSyncClient) -> None:
# seed from ever running.
if merged_history:
write_raw_history(history_to_json(merged_history))
# Same guard for the meal schedule: a pre-feature peer contributes no
# `sched:` fields, and writing the empty document back would discard this
# device's own history.
merged_schedule = log_to_schedule_history(merged)
if merged_schedule:
write_raw_schedule(schedule_history_to_json(merged_schedule))
push_json = json.dumps(
{record_id: record.to_dict() for record_id, record in merged.items()},

View File

@ -45,11 +45,17 @@ from diet_guard.sync_merge._daylog import (
parse_remote_log,
record_to_entry,
)
from diet_guard.sync_merge._schedule import (
SCHEDULE_FIELD_PREFIX,
log_to_schedule_history,
schedule_fields,
)
__all__ = [
# Private helpers the tests reach for directly. Re-exported deliberately:
# they were importable from the flat module, and dropping them here would
# break those tests for a naming reason rather than a behavioural one.
"SCHEDULE_FIELD_PREFIX",
"_budget_hlc",
"_entry_hlc",
"_legacy_entry_id",
@ -62,10 +68,12 @@ __all__ = [
"log_to_food_bank",
"log_to_history",
"log_to_manual_bank",
"log_to_schedule_history",
"manual_bank_to_log",
"parse_remote_budget",
"parse_remote_food_bank",
"parse_remote_log",
"parse_remote_manual_bank",
"record_to_entry",
"schedule_fields",
]

View File

@ -23,10 +23,13 @@ from crdt_sync import Hlc, Record
from diet_guard._budget_history import BudgetEntry
from diet_guard._device import device_id
from diet_guard.sync_merge._clock import _EPOCH
from diet_guard.sync_merge._schedule import schedule_fields
if TYPE_CHECKING:
from crdt_sync import Log
from diet_guard._meal_schedule_store import ScheduleEntry
_BUDGET_RECORD_ID = "budget"
# Field-name prefix for the effective-from budget history, one field per date.
@ -77,6 +80,7 @@ def _history_hlc(entry: BudgetEntry) -> Hlc:
def budget_to_log(
record: dict[str, object] | None,
entries: tuple[BudgetEntry, ...] = (),
schedule_entries: tuple[ScheduleEntry, ...] = (),
) -> Log:
"""Convert a raw local budget record plus its history into a Log.
@ -112,6 +116,9 @@ def budget_to_log(
entry.kcal,
_history_hlc(entry),
)
# The meal-schedule history rides the same record as its own `sched:`
# fields; see :mod:`diet_guard.sync_merge._schedule`.
fields.update(schedule_fields(schedule_entries))
rec = Record(id=_BUDGET_RECORD_ID, fields=fields)
return {rec.id: rec}

View File

@ -0,0 +1,111 @@
"""Meal-schedule history as extra fields on the shared ``budget`` record.
Split out of :mod:`._budget` to keep both modules under the repo's 250-line
limit; the two halves are otherwise the same idea and share one record.
The schedule rides as one ``sched:<YYYY-MM-DD>`` field per history entry,
exactly like the budget's ``hist:`` fields. ``crdt_sync``'s ``merge_record``
is 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
predates meal schedules neither clobbers those fields nor blocks them -- it
relays them untouched. That is what makes this shippable without a
coordinated release.
The value is a small map (``{"f": 8, "l": 20, "n": 5}``) rather than a scalar.
``Record.to_dict``/``from_dict`` round-trip nested values unchanged, and a
malformed one is skipped exactly as a non-int ``hist:`` value is.
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from crdt_sync import Hlc
from diet_guard._device import device_id
from diet_guard._meal_schedule import MealSchedule
from diet_guard._meal_schedule_store import ScheduleEntry
from diet_guard.sync_merge._clock import _EPOCH
if TYPE_CHECKING:
from crdt_sync import Log
_BUDGET_RECORD_ID = "budget"
# Field-name prefix for the effective-from meal-schedule history, one field
# per date. A separate *field* rather than a separate document, for the
# reason spelled out in this module's docstring.
SCHEDULE_FIELD_PREFIX = "sched:"
def schedule_hlc(entry: ScheduleEntry) -> Hlc:
"""Derive a deterministic Hlc for one schedule entry from its edit time.
Same trick as the budget's ``_history_hlc``: identical inputs always yield
the same clock, so re-syncing an unchanged history is a no-op. Derived
from the parsed timestamp rather than the raw string, so the two languages
agree even though they format the epoch fallback differently.
"""
try:
moment = datetime.fromisoformat(entry.edited_at)
except ValueError:
moment = _EPOCH
return Hlc.new_tick(device_id(), wall_time_ms=int(moment.timestamp() * 1000))
def schedule_fields(
entries: tuple[ScheduleEntry, ...],
) -> dict[str, tuple[object, Hlc]]:
"""Return the ``sched:`` fields contributed by ``entries``.
Empty when this device has no history, so a device that has never edited
a schedule contributes nothing to the merge rather than pushing the unset
default over a peer's real value.
"""
return {
f"{SCHEDULE_FIELD_PREFIX}{entry.effective_from}": (
{
"f": entry.schedule.first,
"l": entry.schedule.last,
"n": entry.schedule.count,
},
schedule_hlc(entry),
)
for entry in entries
}
def log_to_schedule_history(log: Log) -> tuple[ScheduleEntry, ...]:
"""Extract the meal-schedule history from a merged budget ``Log``.
Each entry's ``edited_at`` is reconstructed from its field Hlc rather than
carried separately, so the stored timestamp and the clock the merge
compared can never drift apart. Malformed values are skipped, so one bad
field from a peer cannot take out the whole history.
"""
record = log.get(_BUDGET_RECORD_ID)
if record is None:
return ()
entries = []
for name, (value, hlc) in record.fields.items():
if not name.startswith(SCHEDULE_FIELD_PREFIX):
continue
if not isinstance(value, dict):
continue
first, last, count = value.get("f"), value.get("l"), value.get("n")
if not (
isinstance(first, int) and isinstance(last, int) and isinstance(count, int)
) or any(isinstance(part, bool) for part in (first, last, count)):
continue
edited = datetime.fromtimestamp(hlc.wall_time_ms / 1000, tz=timezone.utc)
entries.append(
ScheduleEntry(
effective_from=name[len(SCHEDULE_FIELD_PREFIX) :],
# Normalised on the way in, so a peer running a future version
# with a wider range cannot hand us a schedule we would derive
# slots differently from.
schedule=MealSchedule(first, last, count).normalized(),
edited_at=edited.astimezone().isoformat(timespec="seconds"),
),
)
return tuple(sorted(entries, key=lambda entry: entry.effective_from))

View File

@ -25,6 +25,7 @@ from diet_guard import (
_gatelock,
_gatelock_budgetedit,
_gatelock_calendar,
_gatelock_calendar_schedule,
_gatelock_calendar_types,
_gatelock_calendar_ui,
_gatelock_calendar_widgets,
@ -33,6 +34,7 @@ from diet_guard import (
_gatelock_layout,
_gatelock_mealflow,
_gatelock_nutrition,
_gatelock_scheduleedit,
_gatelock_ui,
)
from diet_guard._gatelock import MealGate
@ -155,11 +157,14 @@ _GATE_TK_MODULES = (
# separately in fake_tk(). Listing it here fails with "does not have the
# attribute 'tk'".
_gatelock_calendar_widgets,
# The History tab's meal-schedule row builds its own tk widgets.
_gatelock_calendar_schedule,
# Builds the History tab's StringVars (make_calendar_vars); without the
# fake those are REAL tkinter vars over a MagicMock root, so every
# `.get()` returns a MagicMock instead of the text under test.
_gatelock_calendar_types,
_gatelock_budgetedit,
_gatelock_scheduleedit,
_gatelock_core,
_gatelock_fields,
_gatelock_layout,

View File

@ -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",

View File

@ -0,0 +1,145 @@
"""Tests for the gate History tab's meal-schedule row.
Covers :mod:`._gatelock_scheduleedit`. The functional fake ``tk`` widgets and
the ``gate`` fixture live in ``conftest.py``, shared with the other gate
tests.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._gatelock_scheduleedit import schedule_summary
from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
if TYPE_CHECKING:
from diet_guard._gatelock import MealGate
def _type(gate: MealGate, first: str, last: str, count: str) -> None:
"""Fill the three schedule entries as the user would."""
gate._cal_vars.schedule.first.set(first)
gate._cal_vars.schedule.last.set(last)
gate._cal_vars.schedule.count.set(count)
class TestScheduleSummary:
"""The derived-times label."""
def test_lists_every_checkpoint(self) -> None:
"""The label spells out the hours the schedule derives."""
assert schedule_summary(MealSchedule(8, 20, 5)) == (
"08:00 11:00 14:00 17:00 20:00"
)
class TestEditToggle:
"""The Edit/Save button's two states."""
def test_first_click_unlocks_without_saving(self, gate: MealGate) -> None:
"""Clicking Edit opens the fields but persists nothing yet."""
gate._on_edit_or_save_schedule()
assert gate._cal_editing_schedule
assert current_schedule() == DEFAULT_SCHEDULE
def test_second_click_persists_and_relocks(self, gate: MealGate) -> None:
"""Clicking Save validates, writes, and returns to read-only."""
gate._on_edit_or_save_schedule()
_type(gate, "8", "20", "5")
gate._on_edit_or_save_schedule()
assert not gate._cal_editing_schedule
assert current_schedule() == MealSchedule(8, 20, 5)
assert gate._cal_vars.schedule.status.get() == "Saved."
def test_a_failed_save_leaves_editing_open(self, gate: MealGate) -> None:
"""A bad value can be corrected rather than silently discarded."""
gate._on_edit_or_save_schedule()
_type(gate, "20", "8", "4")
gate._on_edit_or_save_schedule()
assert gate._cal_editing_schedule
assert current_schedule() == DEFAULT_SCHEDULE
class TestValidation:
"""Rejected input, with the reason shown rather than silently clamped."""
def test_rejects_non_numeric(self, gate: MealGate) -> None:
"""Letters in an hour field are refused, not coerced."""
_type(gate, "eight", "20", "4")
assert not gate._save_schedule_entry()
assert "whole hours" in gate._cal_vars.schedule.status.get()
def test_rejects_a_backwards_window(self, gate: MealGate) -> None:
"""The last meal must come after the first."""
_type(gate, "20", "8", "4")
assert not gate._save_schedule_entry()
assert "before the last" in gate._cal_vars.schedule.status.get()
def test_rejects_an_out_of_range_hour(self, gate: MealGate) -> None:
"""Hours outside 0-23 are refused."""
_type(gate, "8", "25", "4")
assert not gate._save_schedule_entry()
assert "0-23" in gate._cal_vars.schedule.status.get()
def test_rejects_too_few_meals(self, gate: MealGate) -> None:
"""One meal a day is below the supported range."""
_type(gate, "8", "20", "1")
assert not gate._save_schedule_entry()
assert "Meals per day" in gate._cal_vars.schedule.status.get()
def test_rejects_too_many_meals(self, gate: MealGate) -> None:
"""More than the cap is refused."""
_type(gate, "8", "20", "9")
assert not gate._save_schedule_entry()
assert "Meals per day" in gate._cal_vars.schedule.status.get()
def test_rejects_more_meals_than_the_window_holds(self, gate: MealGate) -> None:
"""A narrow window cannot hold six distinct whole-hour checkpoints.
Without this the derivation would round two meals onto the same hour,
and a duplicate slot silently drops a checkpoint.
"""
_type(gate, "8", "11", "6")
assert not gate._save_schedule_entry()
assert "Too many meals" in gate._cal_vars.schedule.status.get()
class TestDisplay:
"""Showing the stored schedule in the row."""
def test_shows_the_stored_schedule(self, gate: MealGate) -> None:
"""The fields and the derived-times label reflect what is stored."""
gate._show_schedule(MealSchedule(7, 21, 3))
assert gate._cal_vars.schedule.first.get() == "7"
assert gate._cal_vars.schedule.last.get() == "21"
assert gate._cal_vars.schedule.count.get() == "3"
assert gate._cal_vars.schedule.times.get() == "07:00 14:00 21:00"
def test_a_refresh_does_not_clobber_an_open_edit(self, gate: MealGate) -> None:
"""Typing survives a calendar refresh landing mid-edit."""
gate._on_edit_or_save_schedule()
_type(gate, "6", "22", "6")
gate._refresh_calendar()
assert gate._cal_vars.schedule.first.get() == "6"
def test_a_refresh_shows_the_stored_schedule_when_idle(
self, gate: MealGate
) -> None:
"""Outside an edit the row tracks whatever is stored."""
record_schedule_change(MealSchedule(9, 19, 3))
gate._refresh_calendar()
assert gate._cal_vars.schedule.first.get() == "9"
assert gate._cal_vars.schedule.times.get() == "09:00 14:00 19:00"

View File

@ -0,0 +1,134 @@
"""Tests for the pure meal-schedule derivation.
The vector table below is duplicated verbatim in
``app/test/models/meal_schedule_test.dart``. KEEP THE TWO IN SYNC: it is the
only thing that catches a Python/Dart divergence before it reaches a device,
and a divergence there means one device nags for a checkpoint the other never
offers -- a slot that can never be satisfied, i.e. a permanent lock.
"""
from __future__ import annotations
import pytest
from diet_guard._meal_schedule import (
DEFAULT_SCHEDULE,
MAX_MEAL_COUNT,
MIN_MEAL_COUNT,
MealSchedule,
)
# (first, last, count) -> expected slot hours. Shared with the Dart mirror.
SCHEDULE_VECTORS: list[tuple[int, int, int, tuple[int, ...]]] = [
# The eating window the user described, at every supported meal count.
(8, 20, 2, (8, 20)),
(8, 20, 3, (8, 14, 20)),
(8, 20, 4, (8, 12, 16, 20)), # today's hardcoded schedule
(8, 20, 5, (8, 11, 14, 17, 20)), # the user's stated example
(8, 20, 6, (8, 10, 13, 15, 18, 20)),
# A window that does not divide evenly: 14 hours across 3 gaps.
(7, 21, 4, (7, 12, 16, 21)),
(7, 21, 5, (7, 11, 14, 18, 21)),
(9, 19, 4, (9, 12, 16, 19)),
# Narrow windows: count is capped at the number of whole hours available,
# so the slots stay distinct instead of repeating an hour.
(8, 12, 6, (8, 9, 10, 11, 12)),
(8, 10, 5, (8, 9, 10)),
(8, 9, 4, (8, 9)),
# Whole-day extremes.
(0, 23, 6, (0, 5, 9, 14, 18, 23)),
(0, 1, 2, (0, 1)),
]
class TestSlots:
"""Slot derivation from a schedule."""
@pytest.mark.parametrize(("first", "last", "count", "expected"), SCHEDULE_VECTORS)
def test_matches_shared_vectors(
self, first: int, last: int, count: int, expected: tuple[int, ...]
) -> None:
"""Each shared vector derives its documented slot hours."""
assert MealSchedule(first, last, count).slots() == expected
def test_default_is_the_historical_schedule(self) -> None:
"""The default reproduces the hours that used to be hardcoded."""
assert DEFAULT_SCHEDULE.slots() == (8, 12, 16, 20)
def test_endpoints_are_exact_when_spacing_rounds(self) -> None:
"""Rounding the interior never drags an endpoint off the window."""
slots = MealSchedule(8, 20, 6).slots()
assert slots[0] == 8
assert slots[-1] == 20
class TestNormalization:
"""Out-of-range input is clamped, never rejected."""
@pytest.mark.parametrize(
("schedule", "expected"),
[
(MealSchedule(8, 20, 99), MealSchedule(8, 20, MAX_MEAL_COUNT)),
(MealSchedule(8, 20, 0), MealSchedule(8, 20, MIN_MEAL_COUNT)),
(MealSchedule(-5, 20, 4), MealSchedule(0, 20, 4)),
(MealSchedule(8, 99, 4), MealSchedule(8, 23, 4)),
# last <= first is pulled forward to leave a one-hour window.
(MealSchedule(12, 12, 4), MealSchedule(12, 13, 2)),
(MealSchedule(12, 3, 4), MealSchedule(12, 13, 2)),
# first cannot occupy the final hour, or no window would remain.
(MealSchedule(23, 23, 2), MealSchedule(22, 23, 2)),
],
)
def test_clamps_to_the_nearest_legal_schedule(
self, schedule: MealSchedule, expected: MealSchedule
) -> None:
"""Illegal values are pulled into range rather than raising."""
assert schedule.normalized() == expected
def test_garbage_still_yields_usable_slots(self) -> None:
"""Wildly invalid input degrades to a schedule, not an exception."""
assert MealSchedule(99, -5, 999).slots() == (22, 23)
class TestEnforcementEndHour:
"""The daily cutoff derived from the last meal."""
def test_default_keeps_the_historical_cutoff(self) -> None:
"""The default schedule still stops enforcing at 22:00."""
assert DEFAULT_SCHEDULE.enforcement_end_hour == 22
def test_tail_follows_the_last_meal(self) -> None:
"""Moving the last meal moves the cutoff with it."""
assert MealSchedule(8, 18, 4).enforcement_end_hour == 20
def test_clamped_to_the_end_of_the_day(self) -> None:
"""A late last meal cannot push the cutoff past midnight.
An unclamped 23 + 2 = 25 would make ``hour < cutoff`` vacuously true,
so the enforcement window would never close.
"""
assert MealSchedule(8, 23, 4).enforcement_end_hour == 24
class TestExhaustiveInvariants:
"""Properties that must hold for every input the UI or sync can produce."""
def test_every_input_yields_ascending_slots_with_exact_endpoints(self) -> None:
"""Sweep the whole input space, including out-of-range values.
This is the cheap half of the cross-language parity guarantee; the
Dart mirror runs the identical sweep.
"""
for first in range(-2, 26):
for last in range(-2, 26):
for count in range(-2, 10):
schedule = MealSchedule(first, last, count)
normalized = schedule.normalized()
slots = schedule.slots()
assert slots[0] == normalized.first
assert slots[-1] == normalized.last
assert len(slots) == normalized.count
assert len(set(slots)) == len(slots)
assert list(slots) == sorted(slots)
assert MIN_MEAL_COUNT <= len(slots) <= MAX_MEAL_COUNT

View File

@ -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
)

View File

@ -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

View File

@ -14,6 +14,11 @@ from diet_guard._budget import daily_budget, write_budget
from diet_guard._budget_derived import budget_weight
from diet_guard._budget_history import load_entries
from diet_guard._device import device_id
from diet_guard._meal_schedule import MealSchedule
from diet_guard._meal_schedule_store import (
load_entries as load_schedule_entries,
)
from diet_guard._meal_schedule_store import record_schedule_change
from diet_guard.tests._sync_fakes import (
_mock_client,
_remote_budget_json,
@ -113,6 +118,21 @@ class TestSyncBudget:
_sync.run_sync()
assert load_entries()[-1].kcal == 2000
def test_meal_schedule_survives_a_round_trip(self) -> None:
"""The meal schedule is written back locally after every merge.
Without this the schedule would be device-local: the phone could set
five meals while the PC still derived four, and the PC's gate would
nag for a checkpoint the phone never offered.
"""
_write_token()
write_budget(2000)
record_schedule_change(MealSchedule(8, 20, 5))
client = _mock_client(devices=())
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
assert load_schedule_entries()[-1].schedule == MealSchedule(8, 20, 5)
def test_malformed_remote_budget_is_skipped(self) -> None:
"""A corrupt remote budget.json is skipped, not a crash."""
_write_token()

View File

@ -0,0 +1,158 @@
"""Tests for the meal-schedule half of the shared ``budget`` CRDT record."""
from __future__ import annotations
import json
from crdt_sync import Log, merge_logs
from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
from diet_guard._meal_schedule_store import ScheduleEntry
from diet_guard.sync_merge import (
SCHEDULE_FIELD_PREFIX,
budget_to_log,
log_to_schedule_history,
parse_remote_budget,
schedule_fields,
)
_RECORD = {"v": 2, "b": 2200, "t": "2026-08-16T10:00:00+02:00"}
def _entry(day: str, schedule: MealSchedule, when: str) -> ScheduleEntry:
"""Return a schedule entry effective from ``day``."""
return ScheduleEntry(effective_from=day, schedule=schedule, edited_at=when)
def _wire(log: Log) -> str:
"""Return the JSON one device would push for ``log``."""
return json.dumps(
{rid: rec.to_dict() for rid, rec in log.items()},
indent=2,
)
class TestScheduleFields:
"""The per-entry fields a device contributes."""
def test_no_entries_contributes_nothing(self) -> None:
"""A device that never edited a schedule cannot outrank a peer."""
assert schedule_fields(()) == {}
def test_one_field_per_entry(self) -> None:
"""Each entry becomes its own ``sched:<date>`` field."""
fields = schedule_fields(
(_entry("2026-08-16", MealSchedule(8, 20, 5), "2026-08-16T10:00:00+02:00"),)
)
assert set(fields) == {f"{SCHEDULE_FIELD_PREFIX}2026-08-16"}
value, _ = fields[f"{SCHEDULE_FIELD_PREFIX}2026-08-16"]
assert value == {"f": 8, "l": 20, "n": 5}
def test_hlc_is_deterministic(self) -> None:
"""Re-syncing an unchanged history is a no-op, not a fresh write."""
entry = _entry(
"2026-08-16", MealSchedule(8, 20, 5), "2026-08-16T10:00:00+02:00"
)
first = schedule_fields((entry,))[f"{SCHEDULE_FIELD_PREFIX}2026-08-16"][1]
second = schedule_fields((entry,))[f"{SCHEDULE_FIELD_PREFIX}2026-08-16"][1]
assert first.wall_time_ms == second.wall_time_ms
def test_unparsable_timestamp_falls_back_to_the_epoch(self) -> None:
"""A malformed stamp still yields a clock, so the entry still merges."""
entry = _entry("2026-08-16", MealSchedule(8, 20, 5), "not-a-timestamp")
hlc = schedule_fields((entry,))[f"{SCHEDULE_FIELD_PREFIX}2026-08-16"][1]
assert hlc.wall_time_ms == 0
class TestLogToScheduleHistory:
"""Extracting the history back out of a merged log."""
def test_absent_record_yields_nothing(self) -> None:
"""No budget record at all means no schedule history."""
assert log_to_schedule_history({}) == ()
def test_round_trips(self) -> None:
"""What one device pushes is what the other reads back."""
entries = (
_entry("2026-08-16", MealSchedule(8, 20, 5), "2026-08-16T10:00:00+02:00"),
)
back = log_to_schedule_history(budget_to_log(_RECORD, (), entries))
assert len(back) == 1
assert back[0].effective_from == "2026-08-16"
assert back[0].schedule == MealSchedule(8, 20, 5)
def test_normalizes_a_peers_out_of_range_schedule(self) -> None:
"""A future peer cannot make this device derive different slots."""
log = budget_to_log(_RECORD, ())
record = log["budget"]
hlc = next(iter(record.fields.values()))[1]
record.fields[f"{SCHEDULE_FIELD_PREFIX}2026-08-16"] = (
{"f": 8, "l": 20, "n": 99},
hlc,
)
assert log_to_schedule_history(log)[0].schedule == MealSchedule(8, 20, 6)
def test_skips_malformed_values(self) -> None:
"""One bad field from a peer cannot take out the whole history."""
log = budget_to_log(_RECORD, ())
record = log["budget"]
hlc = next(iter(record.fields.values()))[1]
record.fields[f"{SCHEDULE_FIELD_PREFIX}2026-01-01"] = (7, hlc)
record.fields[f"{SCHEDULE_FIELD_PREFIX}2026-02-01"] = ({"f": "8"}, hlc)
record.fields[f"{SCHEDULE_FIELD_PREFIX}2026-03-01"] = (
{"f": True, "l": 20, "n": 4},
hlc,
)
assert log_to_schedule_history(log) == ()
class TestCrossDeviceMerge:
"""The property that makes this shippable without a coordinated release."""
def test_a_pre_feature_peer_relays_the_schedule_untouched(self) -> None:
"""A device that knows nothing about schedules cannot drop them.
``merge_record`` is per-field LWW over the *union* of field names, and
both devices push the merged record, so the peer's budget-only push
merges the fields in rather than clobbering them.
"""
entries = (
_entry("1970-01-01", DEFAULT_SCHEDULE, "1970-01-01T00:00:00+00:00"),
_entry("2026-08-16", MealSchedule(8, 20, 5), "2026-08-16T10:00:00+02:00"),
)
ours = budget_to_log(_RECORD, (), entries)
peer = budget_to_log(
{"v": 2, "b": 1900, "t": "2026-08-16T11:00:00+02:00"}, (), ()
)
merged = merge_logs(parse_remote_budget(_wire(ours)), peer)
back = log_to_schedule_history(merged)
assert [entry.schedule for entry in back] == [
DEFAULT_SCHEDULE,
MealSchedule(8, 20, 5),
]
def test_the_newer_edit_wins_per_day(self) -> None:
"""Two devices editing the same day converge on the later edit."""
older = budget_to_log(
_RECORD,
(),
(
_entry(
"2026-08-16", MealSchedule(8, 20, 5), "2026-08-16T10:00:00+02:00"
),
),
)
newer = budget_to_log(
_RECORD,
(),
(
_entry(
"2026-08-16", MealSchedule(7, 21, 3), "2026-08-16T18:00:00+02:00"
),
),
)
merged = merge_logs(parse_remote_budget(_wire(older)), newer)
assert log_to_schedule_history(merged)[0].schedule == MealSchedule(7, 21, 3)

51
docs/meal-schedule.md Normal file
View File

@ -0,0 +1,51 @@
# The meal schedule (`_meal_schedule.py` / `meal_schedule.dart`)
_Split out of `CLAUDE.md` to keep it under the repo's 250-line cap._
The user sets a first meal hour, a last meal hour, and how many meals fall
between them; the intermediate checkpoints are derived by even division.
`MealSchedule(8, 20, 5)` → `08:00, 11:00, 14:00, 17:00, 20:00`. The default
`MealSchedule(8, 20, 4)` reproduces the hours that used to be hardcoded, so an
existing install sees no change until it is edited.
Four rules, each load-bearing:
- **Integer arithmetic only** — see the `Do NOT` entry below. The shared
test-vector table plus an identical 0..23 × 0..23 × 2..6 sweep in
`test_meal_schedule.py` and `meal_schedule_test.dart` is what catches a
cross-language divergence before it reaches a device.
- **Slots stay whole hours.** Changing that changes the on-disk log's `slot`
tag and the sync wire format, on both devices.
- **Counts are clamped to the window width** (`last - first + 1`), because a
narrow window would otherwise round two meals onto the same hour, and slot
hours are set members, dict keys *and* notification ids — a duplicate
silently drops a checkpoint. The two edit surfaces reject such input with a
message; `normalized()` clamps it, which is the defence against a peer's
corrupt sync data rather than the input contract.
- **The enforcement cutoff is `last + 2h`, clamped to midnight.** It is a
grace period for a late dinner, deliberately independent of meal count.
Unclamped, a 23:00 last meal gives 25 and `hour < cutoff` is vacuously
true — the window never closes.
`_slots.py` / `slot.dart` take the schedule as a **required** argument. A
default there would let a call site missed in a refactor keep deriving the old
fixed hours on one device only, which is the split brain that can lock the
user out; making it required lets mypy and `flutter analyze` enumerate the
sites. Callers resolve it at the impure edge through
`_meal_schedule_store.current_schedule()` / `MealScheduleService.current`.
The history is forward-only (`_meal_schedule_store.py` /
`meal_schedule_history.dart`), so switching from four meals to five does not
retroactively mark past days as having missed a checkpoint. It seeds the
default at `1970-01-01` **before** recording today's value — same ordering
requirement as `_budget_history.py`. It syncs as `sched:<YYYY-MM-DD>` fields
on the existing `budget` CRDT record, so devices predating the feature relay
them untouched.
Editable on both surfaces: the app's Settings screen
(`settings_meal_schedule.dart`) and the gate's History tab
(`_gatelock_scheduleedit.py`).
**Notification ids are slot hours.** `syncToSlots` must sweep the whole 0..23
id space, not the current schedule's slots — otherwise a schedule change
orphans the ids it no longer contains and they nag forever.

View File

@ -0,0 +1,206 @@
> **This file is a ready-to-use prompt.** Open this repo and say
> "do dopamine-ux-diet-guard". It is self-contained -- it needs no context from
> any other session.
>
> Canonical copy: `~/utils/dopamine-ux/03-diet-guard.md` (source of truth; this is a
> distributed copy). Running order and cross-prompt rules: `~/utils/dopamine-ux/00-INDEX.md`.
> Generated 2026-08-16 from a survey of this repo -- line numbers are accurate
> as of that date; **anchor on the symbol names, not the line numbers.**
## ⛔ WHEN YOU FINISH THIS PROMPT
Do **both**, in the same session that completes the work:
1. **Delete this file** and commit that deletion together with the
implementation:
```bash
git rm prompts/dopamine-ux-diet-guard.md
```
Do not leave a finished prompt lying in the repo -- a stale prompt is
indistinguishable from a pending one, and the next session will re-run it.
2. **Log completion in the canonical index**, in `~/utils` (a *different* repo,
so it needs its own commit):
```bash
cd ~/utils
# append to the "Completion log" table in dopamine-ux/00-INDEX.md:
# | 03-diet-guard.md | DONE <YYYY-MM-DD> | <impl commit sha> | <one-line note> |
git add dopamine-ux/00-INDEX.md
git commit -m "dopamine-ux: mark 03-diet-guard.md done"
git push
```
If you finish only part of the prompt, do **neither** -- instead edit this file
to strike out what is done and state what remains, so the next session starts
from the true state. Partial completion must never be recorded as DONE.
---
Make logging a meal feel satisfying in diet_guard_app
## findings (4, ranked by value over effort)
1. **`_onLogMeal()` gives zero feedback** — no haptic, no sound, no animation, no
confirmation. The flagship gap. Fix needs no new dependency.
2. **Streak text is inert** — "Adherence streak: N days" is a plain `Text` that
blinks to a new value. Real data, no salience.
3. **No VIBRATE permission** — blocks haptics until added to the manifest.
4. **No audio capability at all** — no package, no `assets:` block. Step 2 only.
## what
Logging a meal currently produces **no feedback whatsoever**. `_onLogMeal()` in
`lib/screens/log_meal_screen.dart` writes the meal, syncs it, clears the fields,
and calls `setState(() { _progress = buildTodayProgress(log); })`. The progress
card silently appears. No SnackBar, no haptic, no sound, no animation.
That is the whole problem. In kuhy's words: *"noting what you ate should be
SATISFYING and ADDICTING so you WANT TO ACTUALLY note down what you ate."* The
data quality of the entire app depends on the logging habit surviving the days
you don't feel like it, and right now the act of logging gives nothing back.
Make the moment of logging land: an immediate haptic, a real confirmation, and
the streak/progress reacting visibly rather than blinking into existence.
## where
Repo: `~/diet-guard`. Flutter app: `~/diet-guard/app` (package `diet_guard_app`).
Primary:
- `app/lib/screens/log_meal_screen.dart` — `_onLogMeal()` (line 122-168 as of
2026-08-16; **grep the symbol, the line will drift**). The `setState` that
silently swaps in the progress card is at ~:164-166. Card rendered at ~:240.
- `app/lib/widgets/today_progress_card.dart` — `TodayProgress` model (~:15),
`TodayProgressCard` (~:64). Consumed/budget kcal ~:100, P/C/F macro row ~:122,
**"Adherence streak: N days"** ~:129-130 — all plain `Text`, no ring, no bar.
- `app/lib/widgets/streak_summary_row.dart` — `StreakSummaryRow`: logging streak,
adherence streak, YTD tally. Also text-only.
- `app/lib/screens/log_meal_progress.dart` — `buildTodayProgress(DayLog)` (~:18),
`adherenceStreak(...)` (~:31).
Theme (local hand-copy, **no `design_system` dependency**):
- `app/lib/ui/theme.dart` — `buildAppTheme()` ~:12, `AppStatusColors`
ThemeExtension ~:89, redeclared `AppSpacing` ~:124, `AppRadius` ~:146,
`AppTextSize`, plus an `AppWidth` class the shared package does not have.
Settings (for the sound opt-out in step 2):
- `app/lib/screens/settings_screen.dart` — body is a `ListView` inside
`Center > ConstrainedBox(maxWidth: AppWidth.prose)` at ~:161-165.
**No `SwitchListTile` exists anywhere in this app** — you are adding the first.
- `app/lib/services/app_settings_service.dart` — the store. **Not
SharedPreferences**: a singleton over a `DocumentStore` writing JSON to
`app_settings.json` (~:26). `init()` ~:49, `_load()` ~:95-112, setters funnel
through `_persist`/`_writeToDisk` ~:147-165 (read the comment at ~:153-155 —
`_writeToDisk` is the single write path every setter must use).
`resetForTesting`/`initForTesting` at ~:66/:74.
## must
**Step 1 — motion + haptics (no new dependency; land this first).**
- On successful meal log, fire `HapticFeedback.mediumImpact()` (or the token
vocabulary's "complete" cue if prompt 01 defined one). `HapticFeedback` comes
from `package:flutter/services.dart` — **no pubspec change needed**. Add
`<uses-permission android:name="android.permission.VIBRATE"/>` to
`app/android/app/src/main/AndroidManifest.xml`; it is currently absent.
- Fire it **immediately on the tap**, before the write/sync completes. The
article's point about micro-animations is that they replace latency with
feedback; a haptic that waits for a network round-trip defeats it.
- Animate the progress card's arrival and the numbers' change rather than
snapping: the kcal figure and the streak count should visibly move to their new
value. Use the motion tokens from prompt 01.
- Show an explicit confirmation of what was recorded — the user should not have
to infer success from a card appearing.
- Honour `MediaQuery.of(context).disableAnimations`: collapse durations to zero.
Haptics still fire (they are not motion).
**Step 2 — sound (separate, independently revertable).**
- Add an audio dependency and an `assets:` block to `app/pubspec.yaml` (neither
exists today), plus a short confirmation cue asset.
- Sound ships **on**, with an opt-out `SwitchListTile` in `settings_screen.dart`,
backed by a new bool in `app_settings_service.dart` following the existing
field pattern: private field + static getter, parsed in `_load()`, written via
`_writeToDisk`.
- The toggle controls **UI sound only**. Never route notification-channel
behaviour through it.
**Both steps:**
- must not: **reward the calorie number.** The satisfying moment fires on
*logging*, not on being under budget. Rewarding a low number teaches the user
to eat less rather than record honestly, and corrupts the app's own data. A
meal that blows the budget gets the same confirmation as one that doesn't.
- must not: fabricate or round up any displayed value. The streak counts real
consecutive days; the progress bar reflects the true ratio. Framing, timing
and salience are fair game — the numbers are not.
- must not: add a celebratory cue to *deleting* or editing a meal. Only the
record-creating act gets it.
- must not: touch `~/diet-guard/diet_guard/` (the Python desktop side) — it has
its own streak logic and is out of scope here.
- optional: a progress ring instead of the plain kcal text. The article's
near-miss point applies honestly here — a ring at 80% of budget is truthful
and more motivating than a number. Only if it stays accurate.
## done
1. Logging a meal on the phone produces a haptic within ~50ms of the tap, an
explicit confirmation, and a visible (not instant) update of the streak/progress.
2. `cd ~/diet-guard/app && flutter analyze` is clean.
3. `cd ~/diet-guard/app && flutter test` passes.
4. With OS "remove animations" enabled, the screen still works and durations are
zero — verified by toggling it, not by reading the code.
5. Step 2 only: the settings toggle flips, persists across an app restart, and
silences the cue.
## verify
**On the phone — this app is mobile-primary; desktop is not sufficient.**
```
adb devices # confirm 23181JEGR08034 is attached
cd ~/diet-guard/app
flutter build apk --release
adb install -r build/app/outputs/flutter-apk/app-release.apk
```
Never `flutter install`, never `adb uninstall`, never `pm clear` — those wipe
real logged food data. `adb install -r` preserves it.
Then log a real meal on the device and report what you felt and saw. A haptic is
a physical outcome: state what the phone did, do not claim it worked from code.
If `com.kuhy.*` focus-mode kills the app on launch, the app needs a focus
whitelist entry before it can be tested.
## read first
- `app/lib/screens/log_meal_screen.dart` — `_onLogMeal()`. Read the whole method
before editing; the sync call and the field-clearing both matter for where the
haptic goes.
- `app/lib/services/app_settings_service.dart` — the `dailyKcalGoal` field
(~:34/:40) is the pattern to copy for a new bool. Note the `_writeToDisk`
comment.
- `~/diet-guard/diet_guard/_calendar_view.py` — `streaks_text()` ~:136 and
`ytd_text()` ~:154. The Dart `streak_summary_row.dart` docstring says it mirrors
this formatting; keep them consistent if you change wording.
- `~/utils/unified-design-system/motion.md` — the motion/haptic vocabulary from
prompt 01. **Prompt 01 must have run first.**
## context you would otherwise rediscover
- This app has **no `design_system` dependency** — `app/lib/ui/theme.dart` is a
hand-transcription of the shared tokens (values are byte-identical, names in
comments). Motion tokens from prompt 01 must be **transcribed into that local
theme file**, matching the existing convention. Do not add the dependency here;
that is a separate, larger refactor.
- Capability baseline, verified 2026-08-16: **no audio package, no `assets:`
block, no `vibration` package, no VIBRATE permission.** The only existing
audio-adjacent thing is the `diet_guard_due_slot` notification channel
(`app/lib/services/notification_backend_io.dart` ~:17-18, :52-55) at
`Importance.high` with no explicit sound/vibration override — leave it alone.
- The app already computes both a **logging streak** and an **adherence streak**
(`_daystatus.py:144`/`:153` on the Python side, mirrored in Dart). You are
making existing true data feel like something, not inventing a new metric.
- diet-guard state lives under XDG (`~/.local/share/diet_guard`), unlike
screen-locker's in-repo JSON. Tests isolate it via
`~/diet-guard/diet_guard/tests/conftest.py:97` `_isolate_state`.

View File

@ -1,96 +0,0 @@
# Refactor TODO — enforce the 250-line file cap
> **This file is a ready-to-use prompt.** Paste it to Claude, or open this repo
> and say "do refactor_claude_todo". It is self-contained: everything needed to
> execute is below. Generated 2026-08-14 from a measured survey of every repo.
## Goal
Every file in this repo must be **at most 250 lines** — source, tests, and
prose (`.md`/`.txt`/`.rst`/`.tex`) alike — and must **stay** that way forever,
enforced by a gate that fails the commit, not by a note anyone can ignore.
Why: a file that cannot be read in one piece forces re-reads and partial edits,
which is the single largest avoidable cost in an LLM-assisted workflow. Aim by
churn, not size alone — refactoring pays where code is read and changed often
(Fowler, _refactoring economic benefit_).
## Scope in this repo
- **53 files** currently exceed 250 lines (of 222 eligible files).
- **21,714 lines** sit in violation; longest file is **1101 lines**.
Exempt (do NOT split these):
- generated files — `*.g.dart`, `*.freezed.dart`, `*.gr.dart`, `**/l10n/generated/**`,
anything with a `GENERATED` header
- markup — `.html`, `.css`, `.scss`
- data files — `.json`, `.yaml`, `.csv`, wordlists and other data-ish `.txt`
(mean line length under 25 chars)
## Violations, highest ROI first
ROI = lines x commits in the last year. Work top-down; a long file nobody edits
has near-zero payoff and should not be first.
| lines | commits/yr | kind | file |
| ----: | ---------: | :---- | :------------------------------------------- |
| 1101 | 12 | prose | `CLAUDE.md` |
| 440 | 15 | code | `app/lib/screens/log_meal_screen.dart` |
| 1052 | 6 | code | `app/lib/screens/history_screen.dart` |
| 1017 | 6 | code | `app/test/screens/history_screen_test.dart` |
| 498 | 10 | code | `diet_guard/_sync.py` |
| 286 | 16 | code | `app/lib/screens/settings_screen.dart` |
| 482 | 9 | code | `diet_guard/tests/test_sync.py` |
| 694 | 5 | code | `app/test/services/sync_merge_test.dart` |
| 472 | 7 | code | `diet_guard/_gatelock_ui.py` |
| 466 | 7 | code | `diet_guard/_cli.py` |
| 282 | 11 | code | `diet_guard/tests/conftest.py` |
| 274 | 11 | code | `app/test/screens/settings_screen_test.dart` |
| 362 | 8 | code | `app/test/screens/log_meal_screen_test.dart` |
| 357 | 8 | code | `diet_guard/_state.py` |
| 475 | 6 | code | `app/lib/services/sync_merge.dart` |
_(38 further files over 250 lines not listed — re-run the survey for the full set.)_
## How to split
- **Python** — extract cohesive helpers into sibling modules; keep the public
API and imports stable.
- **Shell** — split into `lib/*.sh` sourced by a thin entry script. Keep
`set -euo pipefail` in each.
- **Dart / TypeScript** — extract widgets/components into their own files.
- **Tests** — split by test-group into sibling files
(`foo.test.ts` -> `foo.parsing.test.ts`, `foo.render.test.ts`). Coverage must
not drop.
- **Docs** — split into topic files under `docs/` with an index. For an
oversized `CLAUDE.md`, move detail into referenced docs so the
always-loaded part shrinks.
**Do not** game the cap: no one-lining, no deleting tests, no moving code into
an exempt extension, no `# noqa`-style suppressions.
## Make it permanent (required — this is the point)
A refactor without a gate silently regrows. Before this task is done:
1. Wire the shared gate `~/utils/scripts/check_file_length.sh` into this repo's
`.pre-commit-config.yaml` as a local hook. If the repo has no pre-commit
config, add a minimal one.
2. The hook checks **files in the commit** (not the whole tree), so unrelated
commits never break, and it **fails** — exit 1, not a warning.
3. No baseline file and no allowlist. Those are suppressions.
4. If this repo has CI (`.github/workflows`), add the same check there so it
also fails on push.
## Done condition
- `bash ~/utils/scripts/check_file_length.sh --all` from this repo root exits 0.
- The repo's own test suite and coverage bar are still green.
- `pre-commit run --files <changed files>` passes.
- A deliberately over-250-line test file, staged, makes `git commit` **fail**.
- For a deployed daemon/app: the entry point still actually runs.
## Verify
Run the Python suite AND the Flutter app tests. Verify the companion app on the phone via the `phone-deploy` skill (`adb install -r`, never uninstall).