mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-11 13:27:39 +01:00
The periodic diet-guard-sync.timer paid a network round-trip every ~15 min to approximate the two moments the shared log actually changes on this device. Sync now fires on those events instead: * before a lock -- already present in _cli_gate._should_lock, which pulls only when a lock is otherwise due, so a phone-logged meal clears the lock and a not-due tick never touches the network; * after a meal is logged here -- new _sync_events.publish_after_log, wired into all three write paths (_cli_log, _cli_gate, _mcp). This is what stops the PHONE nagging for a slot already logged on the PC, the mirror image of the rule that keeps the phone's own tick unconditional. The gate's publish sits in cmd_gate AFTER MealGate.run() returns, never in the unlock handler: that runs on the Tk thread with the window still up, so a hanging network call would keep the user locked in behind a successful log. It also covers the "Synced from another device" unlock, which hooking log_meal would miss. Accepted trade: a PC that is on but neither logging nor locking no longer pulls, so an inbound phone edit lands at the next log or lock rather than within 15 min. Bounded by slot spacing -- an unlogged day raises a lock. install.sh now disables and removes the installed timer (guarded, since a fresh machine has no such unit and `disable` would abort under `set -euo pipefail`); the .service stays for manual one-off ticks. Every test that logs a meal would otherwise reach the network through the new call sites, so conftest patches publish_after_log at each of the three call sites -- not on _sync_events, so test_sync_events still exercises the real helper. Suite stays at ~8s, which is the actual leak detector. Two files had to be split to commit at all, since file-length passes filenames and both were already over the 250-line cap: _cli.py 466 -> 207, + _cli_args.py, _cli_init.py, _cli_log.py _mcp.py 370 -> 194, + _mcp_server.py (singleton + annotations), _mcp_read.py Their conftest/test patch targets moved in the same commit; a stale target redirects nothing and fails open. Verified: 701 python tests at 100% branch coverage, 555 flutter tests, `python -m diet_guard sync` -> 402 entries/exit 0, `gate --check` -> exit 0, all five MCP tools still register, live ~/.local/share/diet_guard byte-identical. Over-cap files: 44 -> 42. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
86 lines
2.6 KiB
Python
86 lines
2.6 KiB
Python
"""CLI handler for the ``init`` subcommand.
|
|
|
|
Split out of :mod:`diet_guard._cli` to hold the repo's 250-line cap, following
|
|
the same thin-per-subcommand-handler shape as ``_cli_gate.py`` (``gate``),
|
|
``_cli_log.py`` (``ate``) and ``_cli_sync.py`` (``sync``).
|
|
|
|
The biometrics prompted for here are used **once** and discarded: only the
|
|
computed budget (and the body weight, which the protein target needs) is ever
|
|
persisted. See ``CLAUDE.md``'s "Biometrics are used once and discarded".
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
from diet_guard._budget import Biometrics, compute_target_budget, write_budget
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable
|
|
|
|
# Accepted answers for the sex prompt that map to the male BMR constant.
|
|
MALE_ANSWERS = {"m", "male"}
|
|
FEMALE_ANSWERS = {"f", "female"}
|
|
|
|
|
|
def read_init_inputs(
|
|
emit: Callable[[str], None],
|
|
ask: Callable[[str], str],
|
|
) -> tuple[Biometrics, float, float] | None:
|
|
"""Prompt for biometrics on stdin; return (bio, activity, deficit) or None.
|
|
|
|
Returns None (after printing why) on any unparsable or out-of-range input,
|
|
so a typo never sets a wrong budget.
|
|
"""
|
|
try:
|
|
weight = float(ask("weight in kg:"))
|
|
height = float(ask("height in cm:"))
|
|
age = float(ask("age in years:"))
|
|
sex_raw = ask("sex (m/f):").lower()
|
|
activity = float(
|
|
ask(
|
|
"activity factor "
|
|
"(1.2 sedentary / 1.375 light / 1.55 moderate / 1.725 active):",
|
|
),
|
|
)
|
|
deficit = float(ask("daily deficit in kcal (e.g. 200):"))
|
|
except ValueError:
|
|
emit("that was not a number; nothing was set.")
|
|
return None
|
|
|
|
if sex_raw in MALE_ANSWERS:
|
|
is_male = True
|
|
elif sex_raw in FEMALE_ANSWERS:
|
|
is_male = False
|
|
else:
|
|
emit('sex must be "m" or "f"; nothing was set.')
|
|
return None
|
|
|
|
bio = Biometrics(
|
|
weight_kg=weight,
|
|
height_cm=height,
|
|
age_years=age,
|
|
is_male=is_male,
|
|
)
|
|
return bio, activity, deficit
|
|
|
|
|
|
def cmd_init(
|
|
emit: Callable[[str], None],
|
|
ask: Callable[[str], str],
|
|
) -> int:
|
|
"""Compute the starting budget from biometrics and write it."""
|
|
inputs = read_init_inputs(emit, ask)
|
|
if inputs is None:
|
|
return 2
|
|
bio, activity, deficit = inputs
|
|
budget = compute_target_budget(
|
|
bio,
|
|
activity_factor=activity,
|
|
deficit_kcal=deficit,
|
|
)
|
|
write_budget(budget, weight_kg=bio.weight_kg)
|
|
emit(f"budget computed from your biometrics: {budget:g} kcal/day.")
|
|
emit("edit it any time from the gate's calendar tab or the phone app.")
|
|
return 0
|