Compare commits

...

5 Commits

Author SHA1 Message Date
2984683027 Document the phone-weight hook's place in run_sync
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 10:01:32 +02:00
8e0a4bddab Refresh the phone weight from run_sync, where the PC's event-driven sync actually passes
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 09:53:59 +02:00
2ea5dcac52 Take flutter_local_notifications 22.3.1 and flutter_secure_storage 11.2.0
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 09:44:05 +02:00
2e06cda31b Take gatelock 0.8.2, coverage 7.16.1 and ruff 0.16.8
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 09:42:31 +02:00
e9ff530198 Refresh the budget's stored weight from the phone's weigh-in after each sync
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 09:41:05 +02:00
11 changed files with 284 additions and 17 deletions

View File

@ -106,7 +106,7 @@ repos:
# direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.1#subdirectory=gatelock
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.2#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.2.0#subdirectory=freedays
- mcp>=2,<3

View File

@ -62,16 +62,16 @@ every idle tick to approximate the two moments state actually changes here.
never in the unlock handler: that runs on the Tk thread with the window up,
so a hanging call would keep the user locked in behind a successful log. It
also covers the "Synced from another device" unlock.
- Accepted trade: a PC that is on but neither logging nor locking does not
pull, so an inbound phone edit lands at the next log or lock. Bounded by slot
spacing — an unlogged day raises a lock.
- **`gate --demo` publishes too** (the call sits after the `finally`). "Safe,
closeable" means it cannot trap you at the keyboard, not that it is offline:
demo already writes real entries through `log_meal` (only the *slot* is
synthetic).
- `pull_shared_log()` is misnamed: it runs a *full* tick (pull, merge, re-sign,
persist, **push**, plus budget and both food banks), not just a pull. Use
`_sync_refresh.pull_peer_logs()` for anything a user waits on.
persist, **push**, budget, both food banks, and last the phone's weigh-in
into `w` via `_phone_weight`: `wake_alarm._weight`, lazy, never raises).
`_sync_refresh.pull_peer_logs()` is for anything a user waits on. What must
follow every tick goes in `run_sync`, not `cmd_sync` (the PC never runs it).
- Accepted trade: a PC neither logging nor locking does not pull.
- **Interactive paths must not block, and stale peers cost real time.** The
threading rules, the interactive timeout, and `prune-peers` (including the
`revs/` marker trap that made pruning *slower*) are in

View File

@ -163,10 +163,10 @@ packages:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "1447ba911c60f2ba3f25dae1af151ec187162566b0f57e37771bf0b400f013ad"
sha256: "357be7ff996dc272e2037c69c1bdd5d1bd21172219d55f8bd2e11aeea602e6d3"
url: "https://pub.dev"
source: hosted
version: "22.3.0"
version: "22.3.1"
flutter_local_notifications_linux:
dependency: transitive
description:
@ -203,10 +203,10 @@ packages:
dependency: "direct main"
description:
name: flutter_secure_storage
sha256: d87713a152ee2f255117bdbbf43da1dea1797e0551e499e0334f0c9dcfafddd2
sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8
url: "https://pub.dev"
source: hosted
version: "11.1.1"
version: "11.2.0"
flutter_secure_storage_darwin:
dependency: transitive
description:

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.81+1
version: 1.0.86+1
environment:
sdk: ^3.12.2
@ -16,8 +16,8 @@ dependencies:
crypto: 3.0.7
flutter:
sdk: flutter
flutter_local_notifications: 22.3.0
flutter_secure_storage: 11.1.1
flutter_local_notifications: 22.3.1
flutter_secure_storage: 11.2.0
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
# Dart so it keeps working on Linux desktop and headless.

View File

@ -0,0 +1,97 @@
"""Carry the phone's morning weigh-in into the budget's stored weight.
The wake-alarm phone app ends every morning session with a typed weight,
published as ``latest_weight_kg`` on its synced record; ``wake_alarm._weight``
reads it on the PC. That weight is what the protein target here is derived
from (``_budget_derived.protein_target_g``), so after each successful
``sync`` the stored ``w`` is refreshed from it.
Only ``w`` moves. The kcal budget is not recomputed -- biometrics are
discarded by design on this side (see ``_budget_biometrics``), so there is
nothing to recompute it *from*. ``t`` is refreshed with ``w`` because both
ride the same edit timestamp into the per-field last-write-wins merge
(``sync_merge._budget``); a new weight under an old ``t`` would lose to
every other device on the next merge.
``wake_alarm`` is an optional neighbour, imported lazily: a machine without
it (or with a broken install) syncs exactly as before and simply never
refreshes the weight.
"""
from __future__ import annotations
from importlib import import_module
from typing import TYPE_CHECKING
from diet_guard._budget import _now_local, read_raw_record, write_raw_record
if TYPE_CHECKING:
from collections.abc import Callable
__all__ = ["refresh_weight_from_phone", "update_weight"]
# Below this the scale and the record agree; a rewrite would only churn ``t``.
_SAME_WEIGHT_KG = 0.05
def update_weight(kg: float) -> bool:
"""Set the budget record's stored weight to ``kg``; False when no budget.
Writes through the raw accessors rather than :func:`_budget.write_budget`
on purpose: that path stamps a budget change into the effective-from
history, and the budget has not changed.
"""
record = read_raw_record()
if record is None:
return False
record["w"] = round(float(kg), 1)
record["t"] = _now_local().isoformat(timespec="seconds")
write_raw_record(record)
return True
def _budget_edit_day(record: dict[str, object]) -> str:
"""The local ``yyyy-mm-dd`` of the record's last edit, or '' when unknown."""
return str(record.get("t", ""))[:10]
def refresh_weight_from_phone(emit: Callable[[str], None]) -> None:
"""Apply the phone's newest weigh-in to the stored weight, if it is newer.
Skipped, silently, when: ``wake_alarm`` is not installed; nothing has
been published (or the backend is unreadable -- ``latest_weight`` never
raises); no budget exists; the weigh-in is not from a *later* day than
the budget's last edit; or it matches the stored weight within
:data:`_SAME_WEIGHT_KG`.
The day comparison is strict. A weigh-in happens in the morning and a
manual budget edit at any time of day, and ``t`` carries only the day's
granularity worth trusting here, so on a shared day the budget edit is
taken as the more recent human action and kept. The cost is one day of
lag in that one case; the alternative overwrites an edit made hours
after the weigh-in.
Args:
emit: One-line output sink, given a line only when a write happened.
"""
try:
weight_module = import_module("wake_alarm._weight")
except ImportError:
return
weight = weight_module.latest_weight()
if weight is None:
return
record = read_raw_record()
if record is None:
return
if weight.date <= _budget_edit_day(record):
return
stored = record.get("w")
if (
isinstance(stored, (int, float))
and not isinstance(stored, bool)
and abs(float(stored) - weight.kg) < _SAME_WEIGHT_KG
):
return
update_weight(weight.kg)
emit(f"weight: {weight.kg} kg from the phone ({weight.date}).")

View File

@ -37,6 +37,7 @@ from diet_guard._constants import (
)
from diet_guard._device import device_identity
from diet_guard._foodbank_rebuild import rebuild_food_bank
from diet_guard._phone_weight import refresh_weight_from_phone
from diet_guard._state_sync import (
read_raw_log,
resign_entry,
@ -202,6 +203,11 @@ def run_sync() -> DayLog:
message="diet_guard sync: revision",
)
state_store.save(SyncState(pushed_rev=revision, peer_revs=seen_revs))
# Last, after the budget merge above: the local record is then already
# the merged winner, so the refreshed ``t`` re-asserts nothing stale.
# Here rather than in the ``sync`` subcommand because on the PC a full
# tick runs from ``publish_after_log``, never from that command.
refresh_weight_from_phone(lambda line: _logger.info("%s", line))
return resigned

View File

@ -162,6 +162,11 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]:
"diet_guard._sync_client.CONFIG_FILE",
tmp_path / "nonexistent-firebase.json",
),
# Every full tick ends by reading the phone's weigh-in through
# `wake_alarm._weight`, which is installed here and reads the live
# Firebase database. `test_sync_budget` asserts the call; nothing
# else may pay for it.
patch("diet_guard._sync.refresh_weight_from_phone", return_value=None),
# Logging a meal now publishes immediately (`_sync_events`), so every
# test that logs one would otherwise open a real connection through a
# path that has nothing to do with what it is asserting. Patched at the

View File

@ -0,0 +1,141 @@
"""Tests for _phone_weight.py -- the phone's weigh-in into the stored weight.
The on-disk budget is redirected by conftest's ``_isolate_state``.
"""
from __future__ import annotations
from dataclasses import dataclass
import sys
from unittest.mock import patch
import pytest
from diet_guard import _phone_weight
from diet_guard._budget import read_raw_record, write_raw_record
from diet_guard._budget_derived import budget_weight
from diet_guard._phone_weight import refresh_weight_from_phone, update_weight
@dataclass(frozen=True)
class FakeWeight:
"""Shape of ``wake_alarm._weight.Weight``, without the dependency."""
date: str
kg: float
device_id: str = "phone"
class FakeWeightModule:
"""Stand-in for ``wake_alarm._weight`` with a canned ``latest_weight``."""
def __init__(self, weight: FakeWeight | None) -> None:
self.weight = weight
self.calls = 0
def latest_weight(self) -> FakeWeight | None:
self.calls += 1
return self.weight
def _seed(weight: float | None, edited: str) -> None:
record: dict[str, object] = {"v": 2, "b": 2000, "t": edited}
if weight is not None:
record["w"] = weight
write_raw_record(record)
@pytest.fixture
def phone(request: pytest.FixtureRequest) -> FakeWeightModule:
module = FakeWeightModule(getattr(request, "param", None))
with patch.object(_phone_weight, "import_module", return_value=module):
yield module
def _lines_after(module: FakeWeightModule, weight: FakeWeight | None) -> list[str]:
module.weight = weight
lines: list[str] = []
refresh_weight_from_phone(lines.append)
return lines
class TestUpdateWeight:
def test_sets_weight_and_refreshes_the_edit_stamp(self) -> None:
_seed(78.5, "2026-08-15T18:38:45+02:00")
assert update_weight(72.44) is True
record = read_raw_record()
assert record is not None
assert record["w"] == 72.4
assert record["b"] == 2000
assert str(record["t"]).startswith("20")
assert record["t"] != "2026-08-15T18:38:45+02:00"
assert budget_weight() == 72.4
def test_without_a_budget_writes_nothing(self) -> None:
assert update_weight(72.4) is False
assert read_raw_record() is None
class TestRefreshWeightFromPhone:
def test_applies_a_newer_weigh_in_and_reports_it(
self, phone: FakeWeightModule
) -> None:
_seed(78.5, "2026-08-15T18:38:45+02:00")
lines = _lines_after(phone, FakeWeight("2026-09-17", 72.4))
assert lines == ["weight: 72.4 kg from the phone (2026-09-17)."]
assert budget_weight() == 72.4
def test_applies_when_the_record_has_no_weight_yet(
self, phone: FakeWeightModule
) -> None:
_seed(None, "2026-08-15T18:38:45+02:00")
assert _lines_after(phone, FakeWeight("2026-09-17", 72.4))
assert budget_weight() == 72.4
def test_applies_when_the_record_has_no_edit_stamp(
self, phone: FakeWeightModule
) -> None:
write_raw_record({"v": 1, "b": 2000})
assert _lines_after(phone, FakeWeight("2026-09-17", 72.4))
assert budget_weight() == 72.4
def test_skips_a_weigh_in_from_the_budget_edit_day_or_earlier(
self, phone: FakeWeightModule
) -> None:
_seed(78.5, "2026-09-17T21:30:00+02:00")
assert _lines_after(phone, FakeWeight("2026-09-17", 72.4)) == []
assert _lines_after(phone, FakeWeight("2026-09-16", 72.4)) == []
assert budget_weight() == 78.5
def test_skips_a_weight_that_matches_within_tolerance(
self, phone: FakeWeightModule
) -> None:
_seed(72.4, "2026-08-15T18:38:45+02:00")
assert _lines_after(phone, FakeWeight("2026-09-17", 72.44)) == []
record = read_raw_record()
assert record is not None
assert record["t"] == "2026-08-15T18:38:45+02:00"
def test_a_bool_weight_in_the_record_is_not_a_weight(
self, phone: FakeWeightModule
) -> None:
write_raw_record({"v": 2, "b": 2000, "t": "2026-08-15", "w": True})
assert _lines_after(phone, FakeWeight("2026-09-17", 72.4))
assert budget_weight() == 72.4
def test_skips_when_nothing_is_published(self, phone: FakeWeightModule) -> None:
_seed(78.5, "2026-08-15T18:38:45+02:00")
assert _lines_after(phone, None) == []
assert budget_weight() == 78.5
def test_skips_when_there_is_no_budget(self, phone: FakeWeightModule) -> None:
assert _lines_after(phone, FakeWeight("2026-09-17", 72.4)) == []
assert read_raw_record() is None
def test_without_wake_alarm_installed_does_nothing(self) -> None:
_seed(78.5, "2026-08-15T18:38:45+02:00")
lines: list[str] = []
with patch.dict(sys.modules, {"wake_alarm._weight": None}):
refresh_weight_from_phone(lines.append)
assert lines == []
assert budget_weight() == 78.5

View File

@ -38,6 +38,24 @@ class TestSyncBudget:
pushed_paths = {call.args[0] for call in client.put_file_text.call_args_list}
assert f"diet-guard-sync/devices/{device_id()}/budget.json" in pushed_paths
def test_refreshes_the_weight_from_the_phone_after_the_merge(self) -> None:
"""The hook runs last, on every successful tick, into the sync log."""
_write_token()
write_budget(2000)
client = _mock_client(devices=())
with (
patch.object(_sync_client, "GitHubSyncClient", return_value=client),
patch.object(_sync, "refresh_weight_from_phone") as refresh,
):
_sync.run_sync()
refresh.assert_called_once()
(sink,) = refresh.call_args.args
with patch.object(_sync._logger, "info") as info:
sink("weight: 72.4 kg from the phone (2026-09-17).")
info.assert_called_once_with(
"%s", "weight: 72.4 kg from the phone (2026-09-17)."
)
def test_nothing_pushed_when_no_budget_ever_set(self) -> None:
"""An uninitialized device contributes nothing -- no push, no crash."""
_write_token()

View File

@ -4,7 +4,7 @@ version = "1.0.0"
description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking"
requires-python = ">=3.14"
dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.1#subdirectory=gatelock",
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.2#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.2.0#subdirectory=freedays",
"requests==2.34.2",

View File

@ -2,10 +2,10 @@
# Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below.
bandit==1.9.4
codespell==2.4.3
coverage==7.16.0
coverage==7.16.1
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.2.0#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.1#subdirectory=gatelock
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.2#subdirectory=gatelock
mcp==2.2.0
mypy==2.3.1
pre-commit==4.6.2
@ -17,4 +17,4 @@ pytest-randomly==5.0.0
pytest-sugar==1.1.1
pytest-xdist==3.8.0
requests==2.34.2
ruff==0.16.7
ruff==0.16.8