mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-11 20:33:54 +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
93 lines
4.0 KiB
Python
93 lines
4.0 KiB
Python
"""CLI handler for the ``gate`` subcommand.
|
|
|
|
Split out from :mod:`diet_guard._cli` to keep that module under the repo's
|
|
500-line cap (see ``CLAUDE.md``'s "feat: split oversized modules" history).
|
|
The gate's actual window logic already lives in ``_gatelock*.py``; this is
|
|
just the thin CLI glue, same as ``_cli_sync.py`` is for ``sync``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
from diet_guard._gate import gate_is_due
|
|
from diet_guard._gatelock import MealGate, acquire_gate_lock, release_gate_lock
|
|
from diet_guard._gatelock_support import wait_for_display
|
|
from diet_guard._sync import pull_shared_log
|
|
from diet_guard._sync_events import publish_after_log
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable
|
|
|
|
|
|
def _should_lock(emit: Callable[[str], None]) -> bool:
|
|
"""Decide whether to lock, pulling from sync first if a lock looks due.
|
|
|
|
This wraps the pure, local :func:`~diet_guard._gate.gate_is_due` predicate
|
|
with one network step: the cheap local check runs first, and only when it
|
|
says a lock is due do we pull the shared log (via :func:`pull_shared_log`,
|
|
which fails closed) and re-read the freshly written log. So a meal just
|
|
logged on the phone can clear the lock, while a not-due tick never touches
|
|
the network at all.
|
|
"""
|
|
if not gate_is_due():
|
|
return False
|
|
reason = pull_shared_log() # only pay the network cost when about to lock
|
|
if reason is not None:
|
|
emit(f"{reason}; using local log.")
|
|
return gate_is_due()
|
|
|
|
|
|
def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
|
|
"""Run the log-to-unlock gate.
|
|
|
|
Three modes: ``--check`` is a headless decision (no window) whose exit code
|
|
a timer reads; ``--demo`` always shows a safe demo window; bare ``gate``
|
|
shows the real lock only when one is due. Both real modes route through
|
|
:func:`_should_lock`, which -- only when a lock is otherwise due -- pulls
|
|
the shared log first (via :func:`pull_shared_log`) so a meal just logged on
|
|
the phone unlocks without a manual re-entry. A flock guard stops a second
|
|
window from stacking on top of the first, and a window-opening mode first
|
|
waits for the X display so a session-start launch never crashes unshown.
|
|
|
|
Args:
|
|
emit: A one-line output sink (``_cli._emit``, passed in rather than
|
|
imported -- see ``_cli_sync.cmd_sync`` for why).
|
|
check: Headless mode -- print and return an exit code, open no window.
|
|
demo: Use safe demo mode (local grab + close button) for the window.
|
|
|
|
Returns:
|
|
For ``--check``: 0 if not due, 1 if a lock is due. Otherwise 0.
|
|
"""
|
|
if check:
|
|
due = _should_lock(emit)
|
|
emit("due (a lock is warranted)" if due else "ok (no lock needed)")
|
|
return 1 if due else 0
|
|
if not demo and not _should_lock(emit):
|
|
emit("ok - no lock needed right now.")
|
|
return 0
|
|
handle = acquire_gate_lock()
|
|
if handle is None:
|
|
emit("the gate is already running.")
|
|
return 0
|
|
try:
|
|
# At session start the timer can fire before the X display/auth cookie
|
|
# is ready; wait it out so the window opens instead of crashing on a
|
|
# "couldn't connect to display" TclError (see _gatelock.wait_for_display).
|
|
if not wait_for_display():
|
|
emit("display not ready yet; will retry on the next timer tick.")
|
|
return 0
|
|
MealGate(demo_mode=demo).run()
|
|
finally:
|
|
release_gate_lock(handle)
|
|
# Publish only once ``run()`` has returned -- i.e. the mainloop has ended and
|
|
# the window is gone. Deliberately NOT inside the unlock handler: that runs
|
|
# on the Tk thread with the lock still up, so a slow or hanging network call
|
|
# would keep the user locked in behind a successful log. Here the worst case
|
|
# is a late publish. One call site covers every unlock reason, including the
|
|
# "Synced from another device" path, which hooking the log itself would miss.
|
|
reason = publish_after_log()
|
|
if reason is not None:
|
|
emit(f"logged locally, not yet published ({reason}).")
|
|
return 0
|