Compare commits

...

7 Commits

Author SHA1 Message Date
a7696c4143 Re-pin crdt-sync to v0.8.0 for connection pooling
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
v0.8.0 pools HTTP connections in the shared library, which is worth ~95ms per
GitHub request and ~52ms per Realtime Database request on this machine.

This jumps two tags, not one: the pin was still v0.6.0, so it also picks up
v0.7.0's "let a mirror read survive the primary being down". Full suite
re-run after the bump rather than assuming only the pooling change landed --
830 passing at 100% branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCucBhUkHBBHHbsY7bSdGV
2026-08-21 13:55:52 +02:00
d59b7ea183 docs: add the crdt_sync connection-pooling session prompt
The remaining item from the sync-latency work is cross-repo (library at
~/utils/crdt-sync, tag bump, re-pin here), so it belongs in its own session
rather than at the tail of a 600-turn one.

Carries the measurements a fresh session would otherwise have to rediscover:
82ms/req saved on GitHub and 51ms on Firebase, against a tick that now makes
27 requests in 7.6s, so ~1.7s (~22%) is the target to hold the work to.

The load-bearing constraint is written down explicitly: 16 tests across three
files patch the *module attribute* (`patch.object(fb.requests, "get", ...)`),
so an implementation that forces a mass test rewrite is the wrong one. Also
corrects a claim I made earlier in the session -- only diet-guard is on 0.6.0;
screen-locker is already on 0.7.0 and the other three are on 0.5.1, and none of
them should be touched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:47:24 +02:00
d75ed9c083 docs: track AGENTS.md and split the sync-latency rules into docs/
The previous commit turned tracked `CLAUDE.md` into a symlink to an *untracked*
`AGENTS.md`, deleting 237 lines of documentation from the repo -- the content
survived only in my working tree, and a fresh clone would have got a dangling
symlink. The symlink predates this session (it was already a type-change in the
working tree at the start); committing it without tracking its target is what
broke it.

Tracking `AGENTS.md` then tripped the 250-line cap, so the sync-latency
material moves to `docs/sync-latency.md` behind a pointer -- the same shape the
repo already uses for `docs/meal-schedule.md` and the Flutter rules. That file
carries the measurements, the three narrow-pull state invariants, the Tk
threading rules, why the gate's publish must stay synchronous under
`Type=oneshot`, the timeout asymmetry, and the `revs/` marker trap.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:42:11 +02:00
0c1bd03f41 docs: record the narrow-pull split and the interactive-path rules
CLAUDE.md still described the gate as pulling a full tick before a lock, which
is exactly what changed. Documents the narrow vs full split, why the gate's
publish must stay synchronous while the CLI's must not (`Type=oneshot` reaps
the unit), the interactive timeout and why `SYNC_TIMEOUT_SECONDS` never
covered Firebase, and `prune-peers` -- including the revs-marker trap, since
that one made things measurably worse before it was caught.

Also extends the test-isolation note: the seam now has four patch targets, and
a new network entry point missing from it reaches the real remote from the
suite.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:39:24 +02:00
0b658f55f6 fix(sync): prune the revision marker too, not just the device directory
Pruning 20 dead devices made the narrow pull *slower* -- ~90ms to ~15s --
which is the opposite of the point, and I caught it only because I measured
after running rather than assuming the win.

`_device_paths` listed the four data files a device publishes but not its
entry under `revs/`. `_sync_refresh._candidate_peers` deliberately enumerates
peers from the revision map instead of calling `list_directory` (that call is
~445ms mirrored), so every orphaned marker resurrected a deleted device as a
candidate and bought a round trip to discover it was gone. 19 orphans, 19
wasted probes, every tick.

The marker is now part of the device's path set, so it is backed up and
deleted with everything else, and a regression test pins it by name rather
than by count. The 19 already-orphaned markers on the remote were cleaned up
separately.

Verified after the cleanup: narrow pull ~84ms, full tick 8.9s (was ~27s),
gate --check ~105ms, and the log is untouched at 441 entries / 117 foods with
peer_revs correctly down to 3.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:38:34 +02:00
3a9db8a3ab feat(sync): add prune-peers to remove device dirs nothing writes to
Every install mints a uuid and pushes under it, and nothing ever cleans those
directories up. This remote holds 25: two live devices and 23 that stopped
writing. Each dead one still costs a round trip in the log pull and in each of
the three bank syncs -- roughly 400ms per peer per tick -- so they dominate
what is left of the background tick.

Diagnosis first, since the obvious theory was wrong. These are not the residue
of phone reinstalls: seventeen of them are frozen at the *same* instant
(2026-08-13T16:45:04) holding near-identical ~400-record copies of one log,
which is the signature of repeated fresh-install runs, not organic use. That
also means `adb install -r` preserving SharedPreferences was never the issue,
so no Android backup change is warranted on this evidence.

Dry-run by default, and the safety rails are the point:

* `plan_prune` only reads; it is what the default run prints.
* A device is prunable only when every record it holds is already held by a
  device being kept. Against the live remote that is 20 devices and **zero**
  records lost -- verified before writing the command, not after.
* `pc`/`phone`/`desktop` are never proposed: they carry pre-migration history
  and `SYNC_LEGACY_DEVICE_ID` still names one as this device's own former path.
* `--apply` refuses without `--backup-dir`, and every peer's raw bytes are
  written to disk before a single delete.

Nothing has been deleted; this commit only adds the tool.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:28:04 +02:00
8871408b5b perf(cli): publish off-thread so logging a meal returns immediately
`diet-guard log ...` blocked for ~15.5s after every meal. The publish itself
has to happen -- until it lands the phone still believes the slot is unlogged
and nags for it -- but only ~2.5s of that is the 293KB push the phone needs;
the rest is pulling peers' banks, which publishing does not require.

The local write is already durable before the publish starts, so the worst
case is a late publish, which is the trade `_sync_events` already documents
for the event-driven model. Moving it to a worker thread lets the caller
print and return at once. Measured: 15.5s -> 2ms before the prompt comes back.

The thread is deliberately non-daemon: the CLI's output is already flushed,
so the process lingers only as long as the push, and the publish is never
killed halfway. A failure still surfaces, via a callback the caller supplies,
just after its own output rather than in the middle of it.

Deliberately NOT applied to the gate. `diet-guard-gate.service` is
`Type=oneshot`, so systemd reaps the unit the moment the main thread exits
and a background publish would be killed mid-push. The gate keeps calling
`publish_after_log` and waiting, which is correct there -- its publish
already runs after the window is gone, where nobody is waiting on it.

`conftest._isolate_state` follows the rename to
`publish_after_log_detached`; without that every meal-logging test would
reach the network through a newly unpatched seam. Verified with
`scripts/check_patch_targets.py` and by timing the real command against a
temporary data dir, never the live log.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:22:26 +02:00
17 changed files with 1066 additions and 248 deletions

246
AGENTS.md Normal file
View File

@ -0,0 +1,246 @@
# 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 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
(`_gatelock_calendar.py`) and the phone's Calendar screen show adherence,
streaks, a YTD tally and weekly/monthly averages, all derived from
`_daystatus.py` / `day_status_service.dart` and `_averages.py` /
`average_service.dart`.
`docs/design.md` holds the original spec (slot timing, the Tue/Wed/Thu
catch-up rule).
## Commands
- Tests: `python -m pytest diet_guard/tests/ --cov=diet_guard --cov-branch --cov-fail-under=100`
- Lint: `pre-commit run --all-files`
- Test the lock (safe, closeable): `python -m diet_guard gate --demo`
- One sync tick: `python -m diet_guard sync`
- Averages: `python -m diet_guard averages`
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
- Install for production: `bash install.sh`
- App tests: `cd app && flutter test`
- Desktop app: `cd app && bash run.sh`
- Install desktop app: `cd app && bash install_arch.sh`
- Phone build: `cd app && flutter build apk --release`
## Scheduling
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/30:00`,
`Persistent=true`), not boot-relative — a boot-relative timer collided with
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
and exits 0 immediately when no lock is due. It needs `DISPLAY`/`XAUTHORITY`;
see the unit file's comments and `wait_for_display()`.
## Cross-device sync
A sync tick pulls every other device's log from `kuhyx/syncs`
(`diet-guard-sync/`, dumb file storage via the REST Contents API), merges
(`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
bank, pushes back.
**On the PC, sync is event-driven — there is no periodic timer.** The old
`diet-guard-sync.timer` (~15 min) was deleted: it paid a network round-trip on
every idle tick to approximate the two moments state actually changes here.
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
meal just logged on the phone clears the lock and a not-due tick never
touches the network. That pull is the **narrow** one
(`_sync_refresh.pull_peer_logs`): peer logs only — no budget, no banks, no
push. Only they answer "has a peer logged this slot?". ~84ms vs ~27s for a
full tick, which must never sit in front of a fullscreen lock.
- **After a meal is logged** — `_sync_events.publish_after_log`, called from
all three write paths (`_cli`, `_cli_gate`, `_mcp`). This is what stops the
*phone* nagging for a slot already logged on the PC.
- The gate's publish lives in `cmd_gate` **after `MealGate.run()` returns**,
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.
- **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
[docs/sync-latency.md](docs/sync-latency.md) — read it before touching
`_sync_refresh.py`, the fetch button, or the publish paths.
- Every test that logs a meal would otherwise hit the network through these new
call sites; `conftest._isolate_state` patches each one
(`_cli_log.publish_after_log_detached`, `_cli_gate.publish_after_log`,
`_mcp.publish_after_log`, `_cli_gate.pull_peer_logs`) — not on
`_sync_events`, so a direct test still exercises the real helper. A new
network entry point missing from that list reaches the real remote.
- **Re-sign on every merge, not just phone-origin entries.** `_entry_is_valid()`
drops unsigned entries once a machine has the HMAC key, and the phone never
holds that key — skipping the re-sign loses every phone-logged meal on the
next read.
- **The phone's periodic tick syncs unconditionally.** Do not re-gate it on
`due.isNotEmpty` (`due_slot_check.dart`); logging promptly means nothing is
ever due, so the phone never publishes and the PC nags for logged slots.
Publish first, then compute due slots from the merged result.
- **WorkManager background isolates must call `initSyncDeviceId()` themselves.**
A fresh isolate has its own static state; without it `currentSyncDeviceId`
falls back to the compile-time role constant and publishes to
`devices/phone/`. Guarded by `background_sync_service_test.dart`.
- **Catch `RemoteSyncError`, never `GitHubSyncError`.** `FirebaseSyncError`/
`FirebaseAuthError` are siblings, not subclasses. `ConfigError` subclasses
`Exception` directly and is covered by neither — `_client_for_run` translates
it to `SyncError`.
- Needs **one** backend, not both: `~/.config/crdt-sync/` (Firebase, primary)
or a PAT at `~/.config/diet_guard/sync_token`, mode 600. Neither → the tick
logs `sync not configured` and no-ops.
- **Both halves of the food bank sync.** The derived bank (`food_bank.json`)
merges by **`count`** (max-count-wins, idempotent — the right merge for a
derived counter). The curated bank (`food_bank_manual.json`) is one CRDT
record per normalized name, LWW by `editedAt`.
## Production dependency installation
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new
non-stdlib dependency must go into system Python's user site-packages:
```bash
/usr/bin/python3 -m pip install --user --break-system-packages -e .
```
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv.
Installing only into `.venv` caused a 3-day production outage (2026-06-19).
Run `install.sh` from a **durable** clone (`~/diet-guard`), never a scratch
dir — it does `pip install -e`, so the clone must persist for `git pull` to
reach the running service.
## Operational gotchas
- **The budget is a plain, freely-editable synced file.** No seal, no signing —
this deliberately replaced a `chattr +i` mechanism so the value is editable
from either device. Do not reintroduce the seal as a "fix"; the removal is
the feature. Every write stamps an edit timestamp; `budget.json` resolves
concurrent edits LWW.
- **Past days are judged against the budget that applied then.**
`_budget_history.py` / `budget_schedule.dart` is a forward-only list of
`(effective_from, kcal)`. `write_budget` / `saveDailyKcalGoal` must seed the
pre-write value to `1970-01-01` **before** recording today's — reversing that
makes every past day adopt the new budget. Covered by
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
existing `budget` record, so devices predating the feature relay them
untouched.
- **Biometrics are used once and discarded** — only the computed budget is
persisted.
- **PC and phone share one source of truth for everything**: food log, budget,
budget history, body weight (`w`), curated food bank. If you add a stored
field, sync it or comment why it physically cannot be.
- **State lives entirely under `~/.local/share/diet_guard/`** — no cross-repo
file coupling. Exception: the sync timer touches `kuhyx/syncs` and
`~/.config/diet_guard/sync_token`.
- **Every device pushes under a persisted per-install uuid**, not a role
constant. `_device.py` / `sync_device_id.dart` (`crdt.nodeId`). The old role
constant survives as the legacy id so `devices/<legacy>/` is skipped as this
device's own — dropping it makes every tick re-merge our own pre-migration
log. The app resolves it asynchronously in `main.dart` before
`LogStorageService.init()`; don't move that call later. Tests must redirect
`_device.SYNC_DEVICE_ID_FILE` (conftest does).
## The companion app's desktop target is a web build
`app/` builds for **Android** and **web** only. There is no `app/linux/` —
Flutter's GTK embedder manages ~20fps at 3840x2160 where the same Dart in
Chrome sustains ~144fps (`~/todo/docs/desktop-performance-findings.md`). The
desktop app is the web build served by `bin/diet_guard_desktop.dart` in a
Chrome `--app` window.
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io`
only in `*_io.dart` seams and `lib/desktop/`, port 8732 and the
`diet-guard-desktop` Chrome profile pinned (IndexedDB is keyed by origin, so
changing either hides the entire local food log).
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
is a blank white window, not a build error.
- The wrapper holds the GitHub token, not the browser, and proxies
`api.github.com` plus the CORS-less device flow (`lib/desktop/github_proxy.dart`).
- Desktop reminders only exist while the window is open; the PC's real backstop
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"
means:
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
zero-kcal day.
- **The yardstick is the mean of the per-day budgets over those same logged
days**, resolved through `BudgetSchedule` — never `daily_budget()`.
- **Today is excluded**; every period ends at `last_complete_day()`. "This
week" is empty on a Monday, and reports `no logged days yet` rather than a
fake average.
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` /
`kOverBudgetYellowCeiling` **by import, not by copy**. The MCP `get_averages`
tool drops `avg_budget` (budget secrecy on the network only); the CLI, gate and
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 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
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
means syncing image blobs too.
- Don't strip the `components` field: nothing writes it, but historical
composite entries and the food bank read it, and it is part of the sync wire
format.
- Don't add a dependency without the production install-path check above.
- Don't reintroduce a seal/`chattr +i` on the budget file.
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
Chrome profile path.
- Don't exceed **250 lines** in any file. Enforced by the `file-length`
pre-commit hook and `.github/workflows/file-length.yml`; the cap and its
exemptions live in `~/utils/file_length/config.py`.
## Flutter/Dart AI rules
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
via `~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically.
Split across five files to stay under the 250-line cap._
- [Language, style and architecture](docs/flutter-rules-language.md)
- [Architecture, lint rules, state and data](docs/flutter-rules-state-and-data.md)
- [Code generation, testing and theming](docs/flutter-rules-testing-and-assets.md)
- [UI: theming, layout and overlays](docs/flutter-rules-ui.md)
- [Colour, type, documentation and accessibility](docs/flutter-rules-design.md)

236
CLAUDE.md
View File

@ -1,236 +0,0 @@
# 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 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
(`_gatelock_calendar.py`) and the phone's Calendar screen show adherence,
streaks, a YTD tally and weekly/monthly averages, all derived from
`_daystatus.py` / `day_status_service.dart` and `_averages.py` /
`average_service.dart`.
`docs/design.md` holds the original spec (slot timing, the Tue/Wed/Thu
catch-up rule).
## Commands
- Tests: `python -m pytest diet_guard/tests/ --cov=diet_guard --cov-branch --cov-fail-under=100`
- Lint: `pre-commit run --all-files`
- Test the lock (safe, closeable): `python -m diet_guard gate --demo`
- One sync tick: `python -m diet_guard sync`
- Averages: `python -m diet_guard averages`
- Install for production: `bash install.sh`
- App tests: `cd app && flutter test`
- Desktop app: `cd app && bash run.sh`
- Install desktop app: `cd app && bash install_arch.sh`
- Phone build: `cd app && flutter build apk --release`
## Scheduling
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/30:00`,
`Persistent=true`), not boot-relative — a boot-relative timer collided with
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
and exits 0 immediately when no lock is due. It needs `DISPLAY`/`XAUTHORITY`;
see the unit file's comments and `wait_for_display()`.
## Cross-device sync
A sync tick pulls every other device's log from `kuhyx/syncs`
(`diet-guard-sync/`, dumb file storage via the REST Contents API), merges
(`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
bank, pushes back.
**On the PC, sync is event-driven — there is no periodic timer.** The old
`diet-guard-sync.timer` (~15 min) was deleted: it paid a network round-trip on
every idle tick to approximate the two moments state actually changes here.
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
meal just logged on the phone clears the lock and a not-due tick never
touches the network.
- **After a meal is logged** — `_sync_events.publish_after_log`, called from
all three write paths (`_cli`, `_cli_gate`, `_mcp`). This is what stops the
*phone* nagging for a slot already logged on the PC.
- The gate's publish lives 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 does not
pull, 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.
- **`gate --demo` publishes too.** The call sits after the `finally`, so it
runs in demo as well. "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), so publishing them is consistent
rather than a new leak.
- `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.
- Every test that logs a meal would otherwise hit the network through these new
call sites; `conftest._isolate_state` patches `publish_after_log` at each of
the three call sites (not on `_sync_events`, so a direct test still exercises
the real helper).
- **Re-sign on every merge, not just phone-origin entries.** `_entry_is_valid()`
drops unsigned entries once a machine has the HMAC key, and the phone never
holds that key — skipping the re-sign loses every phone-logged meal on the
next read.
- **The phone's periodic tick syncs unconditionally.** Do not re-gate it on
`due.isNotEmpty` (`due_slot_check.dart`); logging promptly means nothing is
ever due, so the phone never publishes and the PC nags for logged slots.
Publish first, then compute due slots from the merged result.
- **WorkManager background isolates must call `initSyncDeviceId()` themselves.**
A fresh isolate has its own static state; without it `currentSyncDeviceId`
falls back to the compile-time role constant and publishes to
`devices/phone/`. Guarded by `background_sync_service_test.dart`.
- **Catch `RemoteSyncError`, never `GitHubSyncError`.** `FirebaseSyncError`/
`FirebaseAuthError` are siblings, not subclasses. `ConfigError` subclasses
`Exception` directly and is covered by neither — `_client_for_run` translates
it to `SyncError`.
- Needs **one** backend, not both: `~/.config/crdt-sync/` (Firebase, primary)
or a PAT at `~/.config/diet_guard/sync_token`, mode 600. Neither → the tick
logs `sync not configured` and no-ops.
- **Both halves of the food bank sync.** The derived bank (`food_bank.json`)
merges by **`count`** (max-count-wins, idempotent — the right merge for a
derived counter). The curated bank (`food_bank_manual.json`) is one CRDT
record per normalized name, LWW by `editedAt`.
## Production dependency installation
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new
non-stdlib dependency must go into system Python's user site-packages:
```bash
/usr/bin/python3 -m pip install --user --break-system-packages -e .
```
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv.
Installing only into `.venv` caused a 3-day production outage (2026-06-19).
Run `install.sh` from a **durable** clone (`~/diet-guard`), never a scratch
dir — it does `pip install -e`, so the clone must persist for `git pull` to
reach the running service.
## Operational gotchas
- **The budget is a plain, freely-editable synced file.** No seal, no signing —
this deliberately replaced a `chattr +i` mechanism so the value is editable
from either device. Do not reintroduce the seal as a "fix"; the removal is
the feature. Every write stamps an edit timestamp; `budget.json` resolves
concurrent edits LWW.
- **Past days are judged against the budget that applied then.**
`_budget_history.py` / `budget_schedule.dart` is a forward-only list of
`(effective_from, kcal)`. `write_budget` / `saveDailyKcalGoal` must seed the
pre-write value to `1970-01-01` **before** recording today's — reversing that
makes every past day adopt the new budget. Covered by
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
existing `budget` record, so devices predating the feature relay them
untouched.
- **Biometrics are used once and discarded** — only the computed budget is
persisted.
- **PC and phone share one source of truth for everything**: food log, budget,
budget history, body weight (`w`), curated food bank. If you add a stored
field, sync it or comment why it physically cannot be.
- **State lives entirely under `~/.local/share/diet_guard/`** — no cross-repo
file coupling. Exception: the sync timer touches `kuhyx/syncs` and
`~/.config/diet_guard/sync_token`.
- **Every device pushes under a persisted per-install uuid**, not a role
constant. `_device.py` / `sync_device_id.dart` (`crdt.nodeId`). The old role
constant survives as the legacy id so `devices/<legacy>/` is skipped as this
device's own — dropping it makes every tick re-merge our own pre-migration
log. The app resolves it asynchronously in `main.dart` before
`LogStorageService.init()`; don't move that call later. Tests must redirect
`_device.SYNC_DEVICE_ID_FILE` (conftest does).
## The companion app's desktop target is a web build
`app/` builds for **Android** and **web** only. There is no `app/linux/` —
Flutter's GTK embedder manages ~20fps at 3840x2160 where the same Dart in
Chrome sustains ~144fps (`~/todo/docs/desktop-performance-findings.md`). The
desktop app is the web build served by `bin/diet_guard_desktop.dart` in a
Chrome `--app` window.
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io`
only in `*_io.dart` seams and `lib/desktop/`, port 8732 and the
`diet-guard-desktop` Chrome profile pinned (IndexedDB is keyed by origin, so
changing either hides the entire local food log).
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
is a blank white window, not a build error.
- The wrapper holds the GitHub token, not the browser, and proxies
`api.github.com` plus the CORS-less device flow (`lib/desktop/github_proxy.dart`).
- Desktop reminders only exist while the window is open; the PC's real backstop
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"
means:
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
zero-kcal day.
- **The yardstick is the mean of the per-day budgets over those same logged
days**, resolved through `BudgetSchedule` — never `daily_budget()`.
- **Today is excluded**; every period ends at `last_complete_day()`. "This
week" is empty on a Monday, and reports `no logged days yet` rather than a
fake average.
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` /
`kOverBudgetYellowCeiling` **by import, not by copy**. The MCP `get_averages`
tool drops `avg_budget` (budget secrecy on the network only); the CLI, gate and
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 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
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
means syncing image blobs too.
- Don't strip the `components` field: nothing writes it, but historical
composite entries and the food bank read it, and it is part of the sync wire
format.
- Don't add a dependency without the production install-path check above.
- Don't reintroduce a seal/`chattr +i` on the budget file.
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
Chrome profile path.
- Don't exceed **250 lines** in any file. Enforced by the `file-length`
pre-commit hook and `.github/workflows/file-length.yml`; the cap and its
exemptions live in `~/utils/file_length/config.py`.
## Flutter/Dart AI rules
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
via `~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically.
Split across five files to stay under the 250-line cap._
- [Language, style and architecture](docs/flutter-rules-language.md)
- [Architecture, lint rules, state and data](docs/flutter-rules-state-and-data.md)
- [Code generation, testing and theming](docs/flutter-rules-testing-and-assets.md)
- [UI: theming, layout and overlays](docs/flutter-rules-ui.md)
- [Colour, type, documentation and accessibility](docs/flutter-rules-design.md)

1
CLAUDE.md Symbolic link
View File

@ -0,0 +1 @@
AGENTS.md

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

View File

@ -30,6 +30,7 @@ from diet_guard._cli_averages import cmd_averages
from diet_guard._cli_gate import cmd_gate
from diet_guard._cli_init import cmd_init
from diet_guard._cli_log import ManualMacroArgs, Portion, cmd_ate
from diet_guard._cli_prune import cmd_prune_peers
from diet_guard._cli_sync import cmd_sync
from diet_guard._gate import due_slots
from diet_guard._meal_schedule_store import current_schedule
@ -186,12 +187,23 @@ def _dispatch_gate(args: argparse.Namespace) -> int:
# A table rather than an if-chain: the chain grew a return per subcommand and
# tripped ruff's return-count limit at the seventh, and a table also has no
# unreachable trailing branch for the 100%-coverage gate to chase.
def _dispatch_prune(args: argparse.Namespace) -> int:
"""Unpack the prune-peers flags for :func:`cmd_prune_peers`."""
return cmd_prune_peers(
_emit,
keep=args.keep,
backup_dir=args.backup_dir,
apply=args.apply,
)
_COMMANDS: dict[str, Callable[[argparse.Namespace], int]] = {
"init": lambda _args: cmd_init(_emit, _ask),
"ate": _dispatch_ate,
"status": lambda _args: _cmd_status(),
"averages": lambda _args: cmd_averages(_emit),
"sync": lambda _args: cmd_sync(_emit),
"prune-peers": _dispatch_prune,
"gate": _dispatch_gate,
"undo": lambda _args: _cmd_undo(),
}

View File

@ -15,6 +15,7 @@ from __future__ import annotations
import argparse
from diet_guard._cli_averages import register_averages_subparser
from diet_guard._cli_prune import register_prune_subparser
from diet_guard._cli_sync import register_sync_subparser
@ -81,6 +82,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
sub.add_parser("status", help="Show today's calories and budget band.")
sub.add_parser("undo", help="Remove today's most recent entry.")
register_averages_subparser(sub)
register_prune_subparser(sub)
register_sync_subparser(sub)
gate = sub.add_parser(

View File

@ -22,7 +22,7 @@ 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
from diet_guard._state import log_meal, now_local
from diet_guard._sync_events import publish_after_log
from diet_guard._sync_events import publish_after_log_detached
if TYPE_CHECKING:
from collections.abc import Callable
@ -156,8 +156,15 @@ def cmd_ate(
)
# Publish straight away rather than waiting for a periodic tick: until this
# lands, the phone still believes this slot is unlogged and will nag for it.
reason = publish_after_log()
if reason is not None:
emit(f"logged locally, not yet published ({reason}).")
#
# On a background thread, though: the full tick measures ~15.5s and this is
# an interactive command, so blocking the terminal on it after every meal
# is the whole complaint. The local write above is already durable, so the
# worst case is a late publish -- the trade `_sync_events` documents. The
# thread is non-daemon, so the process waits for the push at exit even
# though the user already has their output.
publish_after_log_detached(
lambda reason: emit(f"logged locally, not yet published ({reason})."),
)
print_summary()
return 0

98
diet_guard/_cli_prune.py Normal file
View File

@ -0,0 +1,98 @@
"""CLI handler for the ``prune-peers`` subcommand.
Removes device directories no longer written by any live device. Dry-run by
default -- see :mod:`diet_guard._prune_peers` for why every safety rail is
there.
"""
from __future__ import annotations
from importlib import import_module
from pathlib import Path
import sys
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import argparse
from collections.abc import Callable
# ``_prune_peers`` reaches ``crdt_sync`` -> ``requests``; registering this
# subparser must not drag an HTTP stack into every other command.
_LAZY_ATTRS = ("plan_prune", "backup_peers", "apply_prune", "open_client")
def __getattr__(name: str) -> object:
"""Resolve the deferred prune helpers on first attribute access."""
if name not in _LAZY_ATTRS:
msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg)
return getattr(import_module("diet_guard._prune_peers"), name)
def register_prune_subparser(sub: argparse._SubParsersAction) -> None:
"""Register the ``prune-peers`` subcommand on ``sub``."""
prune = sub.add_parser(
"prune-peers",
help="Remove sync device directories nothing writes to any more.",
)
prune.add_argument(
"--keep",
action="append",
default=[],
metavar="DEVICE_ID",
help="A peer to treat as live (repeatable). This device is implicit.",
)
prune.add_argument(
"--backup-dir",
default=None,
help="Where to back up peer data before deleting (needed with --apply).",
)
prune.add_argument(
"--apply",
action="store_true",
help="Actually delete. Without this the command only reports.",
)
def cmd_prune_peers(
emit: Callable[[str], None],
*,
keep: list[str],
backup_dir: str | None,
apply: bool,
) -> int:
"""Report -- and with ``--apply``, remove -- devices nothing writes to.
Returns:
0 on success, 1 when the plan is unsafe or a backup path is missing.
"""
module = sys.modules[__name__]
client = module.open_client()
plan = module.plan_prune(client, set(keep))
emit(f"{len(plan.keeps)} device(s) kept, {len(plan.prunes)} prunable.")
emit(f"records held by kept devices: {plan.covered}")
for device_id in plan.prunes:
emit(f" prunable: {device_id}")
if plan.unique_lost:
emit(
f"refusing to prune: {plan.unique_lost} record(s) exist only on "
"peers that would be removed.",
)
return 1
if not plan.prunes:
emit("nothing to prune.")
return 0
if not apply:
emit("dry run -- pass --apply (with --backup-dir) to delete.")
return 0
if backup_dir is None:
emit("--apply requires --backup-dir; refusing to delete without a backup.")
return 1
written = module.backup_peers(client, plan.prunes, Path(backup_dir))
emit(f"backed up {written} file(s) to {backup_dir}")
for device_id in module.apply_prune(client, plan.prunes):
emit(f" pruned: {device_id}")
emit(f"pruned {len(plan.prunes)} device(s).")
return 0

160
diet_guard/_prune_peers.py Normal file
View File

@ -0,0 +1,160 @@
"""Removing device directories no longer written by any live device.
Every install mints its own uuid and pushes under it, and nothing ever cleans
those directories up. On this machine that grew to 25: two live devices plus
23 that stopped writing, seventeen of them frozen at the *same* instant, which
is the signature of repeated fresh-install runs rather than organic use.
That is not free. Each peer costs a round trip in the log pull and in each of
the three bank syncs -- roughly 400ms per peer per tick -- so the dead ones
dominate the background tick.
**Safety, because this deletes data on a shared remote:**
* :func:`plan_prune` only ever *reads*. It is what ``--dry-run`` (the default)
prints.
* A device is prunable only when every record it holds is already held by a
device being kept. A peer with even one unique record is reported as
``keeps`` and never proposed.
* :data:`PROTECTED_IDS` are never proposed at all: the legacy role ids carry
pre-migration history and are named by ``SYNC_LEGACY_DEVICE_ID``, and
dropping one makes every tick re-merge this device's own old log.
* :func:`backup_peers` writes every peer's raw pushed bytes to disk before any
deletion, so a mistake is recoverable from the local copy.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import json
import logging
from typing import TYPE_CHECKING
from diet_guard._device import device_identity
from diet_guard._sync_client import _client_for_run
from diet_guard._sync_paths import (
_DEVICES_DIR,
_REVS_DIR,
_device_budget_path,
_device_food_bank_path,
_device_log_path,
_device_manual_bank_path,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
from crdt_sync import RemoteStore
_logger = logging.getLogger(__name__)
#: Never proposed for deletion, whatever their contents.
#:
#: The pre-migration role ids. ``SYNC_LEGACY_DEVICE_ID`` still names one of
#: them as this device's own former path, and CLAUDE.md is explicit that
#: dropping it makes every tick re-merge our own history as if it were a peer's.
PROTECTED_IDS = frozenset({"pc", "phone", "desktop"})
@dataclass
class PrunePlan:
"""What a prune would do, without having done any of it."""
keeps: list[str] = field(default_factory=list)
prunes: list[str] = field(default_factory=list)
#: Records held by the kept devices; the yardstick for "already covered".
covered: int = 0
#: Records that would be lost. Must be 0 for a plan to be safe to apply.
unique_lost: int = 0
def _device_paths(device_id: str) -> tuple[str, ...]:
"""Return every path a device publishes under.
The revision marker is one of them, and forgetting it is not cosmetic:
``_sync_refresh._candidate_peers`` enumerates peers from the revision map,
so a marker left behind for a deleted device makes every tick propose a
peer that no longer exists and pay a round trip discovering that. Pruning
without this made the narrow pull *slower* (~90ms -> ~15s) rather than
faster.
"""
return (
_device_log_path(device_id),
_device_food_bank_path(device_id),
_device_manual_bank_path(device_id),
_device_budget_path(device_id),
f"{_REVS_DIR}/{device_id}",
)
def _record_ids(client: RemoteStore, device_id: str) -> set[str]:
"""Return the record ids in ``device_id``'s pushed log, or an empty set."""
text = client.get_file_text(_device_log_path(device_id))
if text is None:
return set()
try:
parsed = json.loads(text)
except (ValueError, TypeError):
return set()
return set(parsed) if isinstance(parsed, dict) else set()
def plan_prune(client: RemoteStore, keep: set[str]) -> PrunePlan:
"""Return which devices could be removed without losing a single record.
Read-only. ``keep`` names the devices whose data is the yardstick -- this
device and any peer still actively writing.
"""
identity = device_identity()
covered: set[str] = set()
for device_id in keep:
covered |= _record_ids(client, device_id)
plan = PrunePlan(covered=len(covered))
for device_id in client.list_directory(_DEVICES_DIR):
if device_id in keep or identity.is_own(device_id):
plan.keeps.append(device_id)
continue
if device_id in PROTECTED_IDS:
plan.keeps.append(device_id)
continue
unique = _record_ids(client, device_id) - covered
if unique:
plan.unique_lost += len(unique)
plan.keeps.append(device_id)
continue
plan.prunes.append(device_id)
return plan
def backup_peers(client: RemoteStore, device_ids: list[str], target: Path) -> int:
"""Write every named device's pushed bytes under ``target``; return file count.
Runs before any deletion so a wrong call is recoverable locally.
"""
target.mkdir(parents=True, exist_ok=True)
written = 0
for device_id in device_ids:
for path in _device_paths(device_id):
text = client.get_file_text(path)
if text is None:
continue
out = target / device_id / path.rsplit("/", 1)[-1]
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(text)
written += 1
return written
def apply_prune(client: RemoteStore, device_ids: list[str]) -> Iterator[str]:
"""Delete every path the named devices published, yielding each as it goes."""
for device_id in device_ids:
for path in _device_paths(device_id):
client.delete_file(path, message="diet_guard: prune stale device")
yield device_id
def open_client() -> RemoteStore:
"""Return a sync client for the prune commands."""
return _client_for_run()

View File

@ -28,6 +28,11 @@ from __future__ import annotations
from importlib import import_module
import logging
import sys
import threading
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
@ -62,3 +67,35 @@ def publish_after_log() -> str | None:
if reason is not None:
_logger.info("post-log sync skipped: %s", reason)
return reason
def publish_after_log_detached(on_failure: Callable[[str], None]) -> None:
"""Publish on a background thread, returning immediately.
For the *interactive* CLI, where blocking the terminal is the problem: the
full tick measures ~15.5s, of which only ~2.5s is the push the phone
actually needs. The local write is already durable by the time this is
called, so the worst case is a late publish -- exactly the trade
:func:`publish_after_log` already documents.
**Not for the gate.** ``diet-guard-gate.service`` is ``Type=oneshot``, so
systemd reaps the unit as soon as the main thread exits and a daemon
thread would be killed mid-push. The gate keeps calling
:func:`publish_after_log` and waiting for it.
The thread is non-daemon precisely so the interpreter waits for it at exit:
the CLI's output is already flushed, so the user sees their result at once
while the process lingers only as long as the push takes.
Args:
on_failure: Called with a reason if the publish could not complete.
Runs on the worker thread, after the caller has printed and
returned, so it must not touch the caller's output ordering.
"""
def _publish() -> None:
reason = publish_after_log()
if reason is not None:
on_failure(reason)
threading.Thread(target=_publish, daemon=False).start()

View File

@ -152,7 +152,7 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]:
# path that has nothing to do with what it is asserting. Patched at the
# *call sites* rather than on `_sync_events`, so a test that imports
# `publish_after_log` directly still exercises the real helper.
patch("diet_guard._cli_log.publish_after_log", return_value=None),
patch("diet_guard._cli_log.publish_after_log_detached", return_value=None),
patch("diet_guard._cli_gate.publish_after_log", return_value=None),
patch("diet_guard._mcp.publish_after_log", return_value=None),
# The gate's pre-lock refresh is a *second*, independent network

View File

@ -117,23 +117,24 @@ class TestAte:
assert "logged:" in capsys.readouterr().out
def test_publishes_after_logging(self) -> None:
"""The meal is published immediately, not left for a periodic tick."""
"""Publishing starts immediately; off-thread, so it is not awaited."""
write_budget(2000)
with (
patch.object(_cli_log, "resolve_nutrition", return_value=_NUT),
patch.object(_cli_log, "publish_after_log", return_value=None) as publish,
patch.object(_cli_log, "publish_after_log_detached") as publish,
):
assert main(["ate", "big mac"]) == 0
publish.assert_called_once_with()
publish.assert_called_once()
def test_sync_outage_still_logs_locally(
self, capsys: pytest.CaptureFixture[str]
) -> None:
"""A failed publish reports itself without failing the local log."""
write_budget(2000)
fail = {"side_effect": lambda cb: cb("no token")}
with (
patch.object(_cli_log, "resolve_nutrition", return_value=_NUT),
patch.object(_cli_log, "publish_after_log", return_value="no token"),
patch.object(_cli_log, "publish_after_log_detached", **fail),
):
assert main(["ate", "big mac"]) == 0
out = capsys.readouterr().out

View File

@ -0,0 +1,214 @@
"""Tests for pruning device directories nothing writes to any more.
This is the one command that *deletes* data on a shared remote, so the tests
lean on the refusals rather than the happy path: a protected id, a peer with a
record no one else has, and ``--apply`` without a backup must each stop it.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
from diet_guard import _cli, _cli_prune, _prune_peers
from diet_guard._device import device_id
if TYPE_CHECKING:
from pathlib import Path
import pytest
def _client(logs: dict[str, dict[str, object]]) -> MagicMock:
"""Return a client whose devices publish the given record-id maps."""
client = MagicMock()
client.list_directory.return_value = list(logs)
files = {
f"diet-guard-sync/devices/{dev}/food_log.json": json.dumps(recs)
for dev, recs in logs.items()
}
client.get_file_text.side_effect = files.get
return client
class TestPlanPrune:
"""Deciding what may go, without touching anything."""
def test_a_covered_peer_is_prunable(self) -> None:
"""Every record already held by a kept device -> nothing is lost."""
client = _client({"live": {"r1": {}, "r2": {}}, "dead": {"r1": {}}})
plan = _prune_peers.plan_prune(client, {"live"})
assert plan.prunes == ["dead"]
assert plan.unique_lost == 0
def test_a_peer_with_a_unique_record_is_kept(self) -> None:
"""One unheld record is enough to disqualify a peer from deletion."""
client = _client({"live": {"r1": {}}, "hoarder": {"r1": {}, "r9": {}}})
plan = _prune_peers.plan_prune(client, {"live"})
assert plan.prunes == []
assert plan.unique_lost == 1
def test_legacy_role_ids_are_never_proposed(self) -> None:
"""Dropping one makes every tick re-merge our own pre-migration log."""
client = _client({"live": {"r1": {}}, "pc": {}, "phone": {}, "desktop": {}})
plan = _prune_peers.plan_prune(client, {"live"})
assert plan.prunes == []
assert set(plan.keeps) >= {"pc", "phone", "desktop"}
def test_this_device_is_never_proposed(self) -> None:
client = _client({device_id(): {"r1": {}}, "live": {"r1": {}}})
plan = _prune_peers.plan_prune(client, {"live"})
assert device_id() not in plan.prunes
def test_an_unreadable_peer_log_counts_as_empty(self) -> None:
"""Unparsable is not "unique" -- it must not block an otherwise safe plan."""
client = _client({"live": {"r1": {}}})
client.list_directory.return_value = ["live", "broken"]
client.get_file_text.side_effect = lambda p: (
"{not json" if "broken" in p else json.dumps({"r1": {}})
)
plan = _prune_peers.plan_prune(client, {"live"})
assert plan.prunes == ["broken"]
def test_a_peer_that_never_pushed_is_prunable(self) -> None:
client = _client({"live": {"r1": {}}})
client.list_directory.return_value = ["live", "empty"]
client.get_file_text.side_effect = lambda p: (
None if "empty" in p else json.dumps({"r1": {}})
)
plan = _prune_peers.plan_prune(client, {"live"})
assert plan.prunes == ["empty"]
class TestApply:
"""The destructive half."""
def test_backup_writes_every_published_path(self, tmp_path: Path) -> None:
client = MagicMock()
client.get_file_text.return_value = "{}"
written = _prune_peers.backup_peers(client, ["dead"], tmp_path)
assert written == 5 # log, food bank, curated bank, budget, rev
assert (tmp_path / "dead" / "food_log.json").read_text() == "{}"
def test_backup_skips_paths_a_device_never_published(self, tmp_path: Path) -> None:
client = MagicMock()
client.get_file_text.return_value = None
assert _prune_peers.backup_peers(client, ["dead"], tmp_path) == 0
def test_apply_deletes_the_revision_marker_too(self) -> None:
"""Leaving it behind makes the narrow pull slower, not faster.
``_sync_refresh._candidate_peers`` enumerates peers from the revision
map, so an orphaned marker resurrects a deleted device as a candidate
and costs a round trip every tick. Observed for real: pruning without
this took the narrow pull from ~90ms to ~15s.
"""
client = MagicMock()
list(_prune_peers.apply_prune(client, ["dead"]))
deleted = [call.args[0] for call in client.delete_file.call_args_list]
assert "diet-guard-sync/revs/dead" in deleted
def test_apply_deletes_all_four_paths(self) -> None:
client = MagicMock()
assert list(_prune_peers.apply_prune(client, ["dead"])) == ["dead"]
assert client.delete_file.call_count == 5
class TestCommand:
"""The CLI wrapper, whose defaults are the real safety rail."""
def _run(
self,
monkeypatch: pytest.MonkeyPatch,
client: MagicMock,
**kwargs: object,
) -> tuple[int, list[str]]:
monkeypatch.setattr(_prune_peers, "_client_for_run", lambda: client)
out: list[str] = []
opts = {"keep": ["live"], "backup_dir": None, "apply": False, **kwargs}
code = _cli_prune.cmd_prune_peers(out.append, **opts)
return code, out
def test_dry_run_deletes_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:
client = _client({"live": {"r1": {}}, "dead": {"r1": {}}})
code, out = self._run(monkeypatch, client)
assert code == 0
client.delete_file.assert_not_called()
assert any("dry run" in line for line in out)
def test_apply_without_a_backup_dir_refuses(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
client = _client({"live": {"r1": {}}, "dead": {"r1": {}}})
code, out = self._run(monkeypatch, client, apply=True)
assert code == 1
client.delete_file.assert_not_called()
assert any("refusing to delete" in line for line in out)
def test_an_unsafe_plan_refuses(self, monkeypatch: pytest.MonkeyPatch) -> None:
client = _client({"live": {"r1": {}}, "hoarder": {"r1": {}, "r9": {}}})
code, out = self._run(monkeypatch, client, apply=True)
assert code == 1
client.delete_file.assert_not_called()
assert any("exist only on" in line for line in out)
def test_nothing_to_prune_is_reported(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
client = _client({"live": {"r1": {}}})
code, out = self._run(monkeypatch, client)
assert code == 0
assert any("nothing to prune" in line for line in out)
def test_apply_backs_up_then_deletes(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
client = _client({"live": {"r1": {}}, "dead": {"r1": {}}})
code, out = self._run(monkeypatch, client, apply=True, backup_dir=str(tmp_path))
assert code == 0
assert client.delete_file.call_count == 5
assert any("pruned 1 device" in line for line in out)
def test_main_dispatches_the_subcommand(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The argparse flags reach the handler unpacked."""
seen: dict[str, object] = {}
def _fake(_emit: object, **kwargs: object) -> int:
seen.update(kwargs)
return 0
monkeypatch.setattr(_cli, "cmd_prune_peers", _fake)
assert _cli.main(["prune-peers", "--keep", "abc"]) == 0
assert seen == {"keep": ["abc"], "backup_dir": None, "apply": False}

View File

@ -8,6 +8,7 @@ reaches the genuine helper (see ``conftest._isolate_state``).
from __future__ import annotations
import logging
import threading
from typing import TYPE_CHECKING
from unittest.mock import patch
@ -52,3 +53,44 @@ class TestPublishAfterLog:
):
publish_after_log()
assert "boom" in caplog.text
class TestPublishAfterLogDetached:
"""The CLI's non-blocking publish."""
def test_runs_the_publish_off_thread(self) -> None:
"""The caller must not wait ~15.5s for the tick to finish."""
done = threading.Event()
def _publish() -> None:
done.set()
with patch.object(_sync_events, "publish_after_log", side_effect=_publish):
_sync_events.publish_after_log_detached(lambda _reason: None)
assert done.wait(timeout=5), "publish never ran"
def test_reports_a_failure_through_the_callback(self) -> None:
"""A publish outage still surfaces, just after the caller returned."""
seen: list[str] = []
finished = threading.Event()
def _record(reason: str) -> None:
seen.append(reason)
finished.set()
with patch.object(_sync_events, "publish_after_log", return_value="no token"):
_sync_events.publish_after_log_detached(_record)
assert finished.wait(timeout=5), "callback never fired"
assert seen == ["no token"]
def test_stays_quiet_on_success(self) -> None:
"""Nothing to report means the callback is never called."""
calls: list[str] = []
with patch.object(_sync_events, "publish_after_log", return_value=None):
_sync_events.publish_after_log_detached(calls.append)
for thread in threading.enumerate():
if thread is not threading.current_thread():
thread.join(timeout=5)
assert calls == []

98
docs/sync-latency.md Normal file
View File

@ -0,0 +1,98 @@
# Sync latency: what must never block the user
Measured 2026-08-21 against the live remote. Before this work the gate ran a
*full* sync tick before deciding whether to lock: ~27s, and the lock screen's
"Fetch from sync" button ran the same tick inline on the Tk thread.
| Path | Before | After |
|---|---|---|
| `gate --check` (nothing due) | 216ms | ~105ms |
| "Fetch from sync" button | 18-27s | ~84ms |
| `diet-guard log ...` | 15.5s | ~2ms |
| Background full tick | ~27s | ~8.9s |
## The narrow pull
`_sync_refresh.pull_peer_logs()` answers one question — *"has a peer already
logged this slot?"* — and only the peer **logs** can answer it. No budget, no
food banks, no `rebuild_food_bank`, and **no push**.
Three state invariants, each with a regression test, because each is silent
when broken:
* **`pushed_rev` survives verbatim.** This pass never pushes; overwriting it
convinces the next full tick it has already published, and the device goes
invisible to every peer, permanently.
* **`peer_revs` is merged, not replaced.** Only changed peers are visited, so a
wholesale replace drops every untouched entry and re-downloads them next tick.
* **The log is written before the state.** The other order records a peer as
merged while its records are absent — silent data loss.
Peer enumeration deliberately avoids `list_directory` (~445ms mirrored, because
the GitHub half alone is ~360ms) and unions the revision map with `peer_revs`
instead. Membership is tested with `in`, never `.get(...) is not None`:
`peer_revs` legitimately holds explicit nulls, and treating those as "never
seen" re-downloads them forever.
## Threading
The fetch button runs the pull on a **daemon** worker and marshals the result
back through a `queue.Queue` polled by `root.after`. The worker touches **no
widget** — Tcl is not thread-safe, and that includes `after`. Polling also
makes the completion path testable with no thread at all: put a result on the
queue, call the poll, assert.
A second click while a fetch is in flight is ignored. That is the reentrancy
guard *and* the write-race fix: the pull persists its merge, so two workers
would race two `write_raw_log` calls and orphan one result.
`diet-guard log` publishes through `publish_after_log_detached` (non-daemon, so
the process waits for the push at exit while the user already has their
output). **The gate does not**: `diet-guard-gate.service` is `Type=oneshot`, so
systemd reaps the unit the moment the main thread exits and a background push
would be killed halfway.
## Timeouts
`INTERACTIVE_TIMEOUT_SECONDS` (2s) bounds anything a user waits on.
`SYNC_TIMEOUT_SECONDS` (10s) only ever reached GitHub: `firebase_client_for`
accepts no timeout in crdt_sync v0.6.0, so Firebase silently used its 15s
default and one hung session refresh stalled the lock window. The journal
recorded five such failures in five days, one of them a meal that logged
locally and never published.
`_apply_timeout` reaches for the private `_timeout_seconds` because the pinned
library exposes no other lever. The clean fix is a `timeout_seconds` kwarg
upstream; that is a cross-repo change (five consumers, tag bump).
## Stale peers
Every install mints a uuid and pushes under it, and nothing cleaned them up.
This remote reached 25 devices. Each dead one cost a round trip in the log pull
and in each of the three bank syncs — roughly 400ms per peer per tick.
They were not phone reinstalls: seventeen were frozen at the *same* instant
(2026-08-13T16:45:04) holding near-identical ~400-record copies of one log,
the signature of repeated fresh-install runs. 20 were pruned on 2026-08-21
after verifying zero records would be lost.
`prune-peers` is dry-run by default, refuses `--apply` without `--backup-dir`,
and never proposes `pc`/`phone`/`desktop` (they carry pre-migration history and
`SYNC_LEGACY_DEVICE_ID` names one as this device's own former path).
**It must delete each device's `revs/` marker along with its data.**
`_candidate_peers` enumerates peers from that map rather than from
`list_directory`, so an orphaned marker resurrects a deleted device as a
candidate and buys a round trip discovering it is gone. Pruning without this
took the narrow pull from ~90ms to ~15s — slower than before the prune.
## Import cost
`gate --check` used to import `requests` (~78ms) and tkinter for a window it
never opens. Both are now resolved through module-level `__getattr__`
(PEP 562) plus `import_module`, which keeps every existing `patch.object`
target working and needs no lint suppression. The chains were
`_cli_args` -> `_cli_sync` -> `crdt_sync` -> `requests`, and
`_cli_log` -> `_resolve` -> `_estimator_off` -> `requests`.
Verify with `python -X importtime -c "import diet_guard._cli_gate" | grep -c requests` (expect 0).

View File

@ -0,0 +1,136 @@
# Session prompt: connection pooling in crdt_sync
Paste everything below the line into a fresh Claude Code session started in
`~/utils` (that is where the library lives — **not** `~/diet-guard`).
---
Add HTTP connection pooling to the shared `crdt_sync` library at
`~/utils/crdt-sync`, then bump the tag and re-pin `~/diet-guard` to it.
## Why
Every HTTP call in `crdt_sync` goes through module-level `requests.get` /
`requests.put` / `requests.post` / `requests.delete`, so each one pays a fresh
DNS + TCP + TLS handshake. There is no `requests.Session` anywhere in the
package.
Measured on this machine, 2026-08-21, against the two real backends:
| Host | fresh conn | session reuse | saving |
|---|---|---|---|
| `api.github.com` | 108ms | 26ms | **82ms/req** |
| `kuhy-syncs-…firebasedatabase.app` | 82ms | 32ms | **51ms/req** |
A diet-guard full sync tick currently makes **27 requests** (12 GitHub, 15
Firebase) in **7.6s**, so pooling projects to **~1.7s saved, about 22%**.
Reproduce both numbers before you start and again at the end — the second run
is the acceptance check, and the first guards against the situation having
changed.
## Scope
**In scope**
1. Connection pooling in `~/utils/crdt-sync/crdt_sync/`, across exactly 9 call
sites in 3 files:
- `_github.py`: lines ~73, ~84 (get), ~163 (put), ~238 (delete)
- `_firebase.py`: ~189, ~319 (get), ~254 (put), ~300 (delete)
- `_firebase_auth.py`: ~290 (post)
2. A `timeout_seconds` keyword on `firebase_client_for` in `_config.py`
(see "Second fix" below).
3. Tag bump + re-pin `~/diet-guard/pyproject.toml` **and**
`~/diet-guard/requirements.txt` (both name the tag).
**Out of scope — do not touch**
- The other consumers. `~/screen-locker` is already on `crdt-sync-v0.7.0`;
`~/leetcode-guard`, `~/build_your_x` and `~/wake-alarm` are on
`crdt-sync-v0.5.1`. Leave every one of those pins alone and say so in your
final report.
- `~/diet-guard/diet_guard/_sync*.py` logic. That work is finished and
committed; this task only re-pins the dependency.
## The constraint that decides the design
**16 tests patch the module attribute**, e.g.
`patch.object(fb.requests, "get", return_value=...)`:
- `crdt_sync/tests/test_firebase.py` — 8
- `crdt_sync/tests/test_github.py` — 5
- `crdt_sync/tests/test_firebase_auth.py` — 3
A naive switch to `self._session.get(...)` breaks all 16. Do **not** mass-edit
the tests to preserve an implementation choice — pick an implementation that
keeps `<module>.requests.get` patchable, e.g. a module-level session object
exposed so the existing patch target still resolves, or a thin shim whose
`.get`/`.put`/`.post`/`.delete` the tests can patch unchanged.
Whatever you pick, the test diff should be near-zero. If you find yourself
rewriting many tests, that is the signal the design is wrong, not the tests.
## Second fix, same release
`firebase_client_for` (`_config.py`, ~line 140) accepts no timeout, so
`FirebaseSyncClient` silently uses its 15s per-request default while
`SYNC_TIMEOUT_SECONDS` reaches GitHub only. diet-guard currently works around
this by assigning the private `_timeout_seconds` post-construction, in
`diet_guard/_sync_client.py::_apply_timeout` — read that function, it documents
the whole problem.
Add a `timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS` keyword and thread it
through. **Leave the diet-guard workaround in place** in this task: it is
guarded by tests and must keep working for anyone still on an older pin. Just
note in your report that it can be simplified in a follow-up.
## Gates (both repos)
- `crdt_sync` requires **100% branch coverage** (`fail_under = 100`,
`--cov-branch` in its `pyproject.toml`) and lints with `select = ["ALL"]`.
- diet-guard: `python -m pytest diet_guard/tests/ --cov=diet_guard
--cov-branch --cov-fail-under=100` — currently **830 passing at 100%**.
- `pre-commit run --files <changed>` in whichever repo you touched.
- **The repo blocks `noqa` and `type: ignore` outright** (`no-noqa` hook). Fix
the underlying issue instead; do not add a suppression, and do not add one to
the ignore list without asking.
- 250-line cap per file, enforced by a hook.
- `~/diet-guard` has a `no local crdt_sync dependency_override` pre-commit hook
that exists to stop a local path override leaking into a commit. Do not
defeat it — re-pin to a real pushed tag.
## Production install path (this has caused a 3-day outage before)
`diet-guard-gate.service` runs `/usr/bin/python`, not a venv. After re-pinning:
```bash
/usr/bin/python3 -m pip install --user --break-system-packages -e ~/diet-guard
/usr/bin/python3 -c "import crdt_sync, sys; print(crdt_sync.__file__)"
```
Verify against `/usr/bin/python3`, **never** the dev venv.
## Watch out
- **Do not run diet-guard's CLI against real data.** State lives in
`~/.local/share/diet_guard/` (441 log entries, 117 foods). Use the test suite,
or a redirected data dir. A `_test_guard` will raise
`RealUserStateWriteError` if a test tries to write there — that is a feature.
- A sync tick **pushes to a shared remote** that the phone also reads. Timing a
real `run_sync()` is fine (it is idempotent), but do not add throwaway writes.
- `~/utils` is a monorepo holding several packages. Stage narrowly —
`crdt-sync/` only — and note that `crdt-sync/tool/seed_session.py` is already
modified and `crdt-sync/firebase-debug.log` is untracked; both predate this
task, so leave them out of your commit.
- Tag `crdt-sync-v0.7.0` already exists, so the new tag is **v0.8.0**. Note that
0.7.0 also carries "Let a mirror read survive the primary being down", which
diet-guard does not have yet — re-pinning picks that up too, so re-run
diet-guard's suite after the bump rather than assuming only your change landed.
## Done means
1. `crdt_sync` at 100% branch coverage, lint clean, with a near-zero test diff.
2. A pushed `crdt-sync-v0.8.0` tag.
3. `~/diet-guard` re-pinned in both `pyproject.toml` and `requirements.txt`,
830 tests still green at 100%.
4. Installed into `/usr/bin/python3`'s user site-packages and verified there.
5. A re-measured full tick, reported against the 7.6s / 27-request baseline
above. State the real number even if it undershoots the projected 1.7s.

View File

@ -5,7 +5,7 @@ description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget
requires-python = ">=3.10"
dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.8.0#subdirectory=crdt-sync",
"requests>=2.31.0",
]

View File

@ -3,7 +3,7 @@
bandit>=1.7.0
codespell>=2.2.0
coverage>=7.4.0
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.8.0#subdirectory=crdt-sync
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
mcp>=2,<3
mypy>=1.8.0