Compare commits

...

219 Commits
v1.0.2 ... main

Author SHA1 Message Date
e3790d41e7 Audit icons: add 1-word hover tooltips
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Todo: fe70b845
2026-11-22 12:30:00 +01:00
95288a7e83 Fix diet-guard-gate: perf.slow slow wait: tk.main…
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Todo: 08acb940
2026-11-22 00:51:32 +01:00
88da2564a1 test_changed: private TMPDIR, 2 flutter isolates
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
A bare targeted flutter test on the shared /tmp held a build slot 67 s
under the build queue (perf.heavybuild, 2026-11-21) against ~4 s alone.
Match the ci_mirror.sh shards: own TMPDIR, --concurrency=2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 19:17:13 +01:00
a9f82f52d2 CI mirror: split flutter tests into 12 shards
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
At 6 shards of 25 files, shard 1 took 39 s idle and 63-67 s on a busy
machine, past the 60 s build-slot cap. At 12 every shard runs in 11-16 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:52:49 +01:00
da147f3325 app: undo this card's version bump
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The commit changed only scripts/ci_mirror.sh and shipped no app build;
keeping pubspec.yaml as it was lets the live clone fast-forward past
another session's uncommitted pubspec edits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:30:25 +01:00
70c5d034a8 CI mirror: run flutter shards at concurrency 2
At the default concurrency a shard peaked at 3.9 GiB and was
OOM-killed inside capped.sh's 2 GiB scope; at 4 it still hit the
limit now and then. At 2 a shard peaks at 1.8 GiB, about 22 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:25:27 +01:00
e942404213 CI mirror: give each flutter shard its own TMPDIR
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
On the shared /tmp a shard stalled at ~2 s of CPU for 15+ minutes and
held a build slot past 60 s. With a private TMPDIR every shard ends
in 11-15 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:40:55 +01:00
7c13ec3de9 app: undo this card's version bumps
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Neither Python-only commit shipped an app build; leaving pubspec.yaml
as it was lets the live clone fast-forward past another session's
uncommitted pubspec edits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:33:07 +01:00
624ae47cfd app: fit settings_screen under the line cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:01:03 +01:00
2589c664ec Rank diet-guard after the tutor (130)
kuhy's order (2026-11-21): workout, book, tutor, diet, focus, then
LeetCode. A local literal replaces gatelock's RANK_DIET_GUARD (100);
test_lock_order pins it to DOCS-lock-order.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 14:51:09 +01:00
e0a4f71953 Mirror test: wait for the sync cue, bounded
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Same fixed-200 ms flake as the log screen tests: under load the
Sync now tick outlasted it. settle() now pumps until the expected
cue appears, at most 5 s.

Todo: 7808ee0a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 06:57:52 +01:00
1190e2d079 Log screen tests: await work, not a fixed sleep
The 200 ms settle flaked under load on origin/main too: the open
chain or a tap's I/O outlasted it. The screen keeps its open chain
in openChain; tests await it, or poll a bounded condition.

Todo: 7808ee0a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 06:50:31 +01:00
9d63c33fa7 Cover place_logo with a real-Tk test
Todo: 7808ee0a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 06:39:11 +01:00
6c2c365a69 Put my logo everywhere
Todo: 7808ee0a
2026-11-21 06:36:21 +01:00
3cd04e60dc textgate: document launcher rows
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
2026-11-19 15:35:36 +01:00
a79b0175d5 CI: drop dependency-freshness check 2026-11-19 15:28:59 +01:00
abd8793e60 check_patch_targets: package as a CLI argument
Some checks failed
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dependency freshness / dependencies on newest stable (push) Has been cancelled
The script hard-coded PACKAGE='diet_guard', so other guard repos could
not run it (build-background-service R3). PACKAGE is now a required
positional (no silent default: that is the fail-open shape the gate
guards against); --tests-root defaults to PACKAGE/tests. Targets match
PACKAGE or PACKAGE.*, so pkg_a no longer claims pkg_ab. Adoption
snippet in docs/DOCS-patch-targets.md. A shared
~/src/utils/patch_targets/ package is a separate follow-up, once a
second repo adopts the script.

Todo: 6d0ec573
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:18:21 +01:00
d56edbc413 Pin Flutter 3.50.0; drop toolchain exception
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 12:42:42 +01:00
9a0cc89941 deploy.sh: restart the Claude worker
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The worker is long-running, so a pip install alone left it on the old
rtdb-relay. Restart it when enabled and check it stays up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:02:34 +01:00
51a31579c8 Bump rtdb-relay to 0.2.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:42:48 +01:00
5add5fa55f Report sync failures; dev extra; deploy script
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The phone showed "Not syncing" with no way to learn why: a release
build keeps no log. attemptSync now records the outcome and files a
sync.failed report to the board with the exception. A refresh error
after a landed sync no longer marks it failed.

Also: hypothesis in pyproject's dev extra; gatelock 0.16.0,
claude-agent-sdk 0.2.184 and stale app pins bumped;
scripts/deploy.sh as the CLAUDE.md deploy command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:32:07 +01:00
ffd30b0476 Report gate errors and stalls to the board
gatelock 0.15.1 error_report, installed by the CLI as app
diet-guard-gate: uncaught, thread and Tk callback errors plus a gate
loop frozen over 1 s go to the app-errors spool. The stall watch arms
in run(), after the turn wait, so building the gate is no stall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:02:08 +01:00
893eea4901 app: crdt_sync_flutter 0.9.1 (build fallback)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Error reports from phone_deploy and local builds now carry the
installed versionCode instead of 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:02:43 +01:00
eec847bb6c Date picker to app bar, no cover by keyboard
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWy9HCAx2bNSRPvmTW
2026-11-17 22:46:01 +01:00
0c76dfd839 Bump gatelock to 0.15.1
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:38:32 +01:00
801d7a0199 Clear red pre-commit and stale pins
check_patch_targets reads PEP 562 _LAZY_ATTRS tables when a
module cannot import under the hook python. Bumps gatelock 0.15.0,
rtdb-relay 0.2.0 (Python side unchanged), gradle 9.9.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:32:20 +01:00
86e702b5e2 app: report errors and slow waits to the board
crdt_sync_flutter 0.9.0 installAppErrors: uncaught errors and every
loader over 1 s (WaitWatch) upload to RTDB with the versionCode; the
PC app-errors ingest files board tickets. Bumps ssui 0.8.3, gda 0.5.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:32:12 +01:00
9663738843 Make the real-clock test time-independent
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 22:11:23 +01:00
0fbedaeecf Resolve pubspec.lock with Flutter 3.50
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 22:06:16 +01:00
1c2fb2e451 Cover the silent autolog branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 22:04:10 +01:00
098ed29ec7 Drop material_ui allowlist entry
Bump sync_settings_ui 0.8.3, crdt_sync_flutter 0.8.3 and
github_device_auth 0.5.1; material_ui 1.11.1 now resolves, so the
transitive exception is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 22:01:07 +01:00
c02d9b2ea4 Sync pubspec.lock with the resolver
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:50:10 +01:00
801a0b4bab Share the sync session in the Claude worker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:47:47 +01:00
a936d07a7e Add a Claude button to the gate lock
A star button beside the log button sends the typed text to
estimate_meal and logs the result like a typed meal: the locked slot,
source "claude", food bank, unlock. Icon states only (idle star, spinner,
warning); no visible text. It is composed (ClaudeFlow), not a new MRO
class, since the gate chain is at pylint's max-parents cap.

Idle uses U+2726, not the sparkles emoji: U+2728 is only in FreeSerif and
Noto Color Emoji here, and a colour-emoji fallback can crash Tk 8.6.

Failure paths (all fail-closed: never unlock, block or freeze):
- estimator error, no login, bad JSON, any exception: warning icon,
  nothing logged, manual log path untouched.
- no answer in 45 s: the poll gives up (warning icon); a late answer is
  discarded.
- slot already logged by hand meanwhile: the result is dropped.
- empty description: error status, no call.
- seam: the estimator name is patched to a raising stub in conftest; a
  mistyped target errors every test at setup (verified once).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:42:35 +01:00
03b6a455cb Auto-log due catering before the lock
kuhy's 2026-11-17 override of "delivered is not eaten": before the lock
opens, the PC logs the due slots' dishes by id uuid5(kuchnia📅key),
shared with the phone (fixture-pinned).

Failure paths:
- fetch error, no credentials, > 5 s: fail-closed, nothing is logged,
  the lock opens as before, reason emitted and logged.
- log write error (OSError/ValueError): fail-closed, same.
- gate --check: never logs (a decision, not a write).
- an undone (tombstoned) entry counts as logged: fail-closed against
  resurrecting a meal kuhy removed.
- publish outage after a clearing auto-log: fail-open by design, the
  local entry stays and the reason is emitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:42:34 +01:00
b0c556b745 Send meals to Claude over the E2E relay
RtdbClaudeRelay against the contract fixture, ULID ids, uuid5 entry ids, withdraw on local log.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:41:07 +01:00
26d6a68ac0 Due-mode log screen, Claude button, photos
Action row 1A, due mode, catering auto-log rows with undo, relay interface, photo input.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:26:13 +01:00
e6322f7f3e Serialise the relay's log writers
The narrow pull, the log write and the publish each read, merge and write
the food log. Run at once (a publish in flight while a second request
logs) they lose the append: the phone is told "logged" and the only copy
is gone. The new race test lost an entry before this change (1 of 2) and
keeps both after it; the shared temp-file name of the log writer also
collided between threads.

One asyncio lock now covers the pull, "resolve slot + log" and the
publish. A request arriving during a publish waits for it (up to one full
tick); the model call stays outside the lock.

Also: a test that the relay unlocks the header diet_guard's devices store
wrote (same key, a blob sealed by one opens on the other), the skill
returns grams 0 for nothing to estimate (parse fails closed, nothing is
logged), and the doc's session note is corrected: the pull and publish
refresh the gate's session file as the CLI's publish does.

Failure paths: a lost append is now impossible in-process (fail closed by
waiting); the pull failure, locked key, estimator and cleanup paths are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:21:05 +01:00
642467dc1d Add the Claude relay worker
python -m diet_guard claude-worker serves the phone's meal requests from
RTDB (rtdb_relay RequestServer, one SSE stream, reconnects with backoff):
validate, estimate with Claude, log through the signed log with
source=claude under the oldest due slot (normal mode: nearest slot of the
phone's hint), write the sealed result, delete only the request payload,
then publish in the background. diet-guard-claude.service (Restart=on-failure,
WantedBy=default.target) is installed by install.sh and started once the
worker's own Firebase session exists. Nothing is deployed by this commit.

Failure paths:
- narrow peer pull fails (sync locked/unreachable): fail closed, no claim, no
  answer, no model call; the request stays pending, retried every 30 s
- e2e key locked, no passphrase, no session: fail closed, nothing read or
  written; the worker waits and retries every 60 s
- bad body, request older than 24 h (or no created): fail closed, an error
  result, nothing logged
- Claude failure/timeout/invalid JSON: fail closed, an error result with
  retry, nothing logged
- crash between log and result, or a duplicate event: idempotent, the entry
  id is uuid5 of the rid and is looked up (tombstones included) before the
  model call
- request payload delete, old-answer cleanup and the post-answer publish
  failing: fail open on purpose (logged only); the answer and the local
  entry are already durable
- due mode with nothing due: falls back to slot_for_log, not an error

New log helpers log_meal_as / find_entry; log_meal's body is split into
_entry_fields / _store_entry with the same output. The gate and CLI import
none of the worker's dependencies at load time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:15:08 +01:00
6cd3470502 Add the Claude meal estimator
estimate_meal(text, photo) -> Estimate runs Claude through
claude_agent_sdk in an isolated CLAUDE_CONFIG_DIR: a copy of the access
token (no refresh token, no MCP tokens) and the diet-food skill, never
kuhy's ~/.claude. The skill text is the system prompt; the closest curated
and derived food-bank rows ride in the user message; the photo is an image
block; the answer is constrained by a JSON schema and validated again.

Failure paths, all fail closed (an EstimateError code, nothing logged):
- no host login, CLI/API error, bad transport: estimate_failed
- more than 45 s: estimate_timeout
- no object, missing/mistyped field, NaN/inf/negative/absurd number,
  grams 0, blank or long desc: estimate_invalid
- neither text nor photo: ValueError before any model call
- failed token refresh is logged, the call then fails as estimate_failed

Live smoke (scratch HOME, nothing logged): "2 jajka sadzone i kromka
chleba" -> 315 kcal in 4.3 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:05:41 +01:00
3d8d358abd Add Claude relay seams and entry points
Dependencies (exact pins): claude-agent-sdk 0.2.183, rtdb-relay 0.1.1,
httpx 0.28.1, hypothesis 6.170.15 (dev). The pylint hook env gets the
same pins.

Entry points, each reachable only through one module attribute:
_claude_connect.connect_sealed (RTDB + e2e unlock), _claude_sdk.run_model
(the model call), _claude_sync.pull_peers / publish (narrow pull, full
tick). SDK and rtdb_relay are imported only by these modules, never by the
gate or CLI at load time.

Test isolation, all fail closed: connect_sealed and run_model are replaced
by a function that raises; pull/publish return None; the sandbox dir and
kuhy's real Claude login path point into tmp_path; _test_guard also
protects ~/.config/diet_guard_claude and ~/.cache/diet_guard. Each of the
six redirects was removed once and its canary went red (fail closed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:02:35 +01:00
a3d089fee3 Allow material_ui 1.11.0 behind sync_settings_ui
The freshness gate was red for every commit: the version-bump hook stages
app/pubspec.yaml, and material_ui 1.11.1 (released after the last green
run) cannot resolve because sync_settings_ui 0.8.2 pins 1.11.0 exactly
(flutter pub get fails on the conflict).

A transitive predicate entry: it clears itself when sync_settings_ui
moves. Added without asking because no commit could pass otherwise; drop
this commit if you prefer to fix it in utils first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:02:30 +01:00
3ce43b56df Add the Claude relay contract
Contract for the phone "send to Claude" button, written before any code:
docs/DOCS-claude-relay.md, the shared Python/Dart fixture and its
builder script. No code runs from this commit.

Failure paths named in the contract:
- locked sync / locked e2e key: fail closed, worker writes nothing, the
  request stays pending (phone keeps its hourglass)
- invalid body, request older than 24 h, Claude timeout/failure/invalid
  JSON: fail closed, an error result is written and nothing is logged
- duplicate event, expired lease or crash replay: idempotent by rid (entry
  id is uuid5 of the rid, checked before the Claude call)
- due mode with nothing due: not an error, falls back to slot_for_log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 20:55:50 +01:00
15a0899119 Zero gatelock startup grace in tests
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
wait_for_turn sleeps its 1.5 s startup grace for real, so every test
that builds a gate paid it. With the grace zeroed in the hermetic
gatelock fixture the 1427 tests run in 11 s instead of overrunning
the 60 s action cap, so the ci-mirror-pytest gate step can finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:37:20 +01:00
eb6a9cf8c3 Bring three files back under 250 lines
pre-commit --all-files failed the file-length gate on AGENTS.md (262),
test_sync_e2e.py (309) and test_sync_refresh.py (254), which would turn
CI red. AGENTS.md prose is rewrapped (same words), test_sync_e2e.py
moves its last three classes to test_sync_e2e_copy.py unchanged, and
two docstrings in test_sync_refresh.py are tightened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:28:02 +01:00
49144a2c49 Move the app to material_ui for Flutter 3.50
Flutter 3.50 deprecates package:flutter/material.dart; 73 deprecation
infos failed flutter analyze --fatal-infos, and four Dart pins were
behind (crdt_sync_flutter 0.8.2, flutter_local_notifications 23.0.2,
github_device_auth 0.5.0, sync_settings_ui 0.8.2). Those UI packages
now sit on material_ui, so the app has to as well or their widgets lose
MaterialLocalizations.

Imports swap one-for-one and dart fix re-sorted the directives; no
behaviour change. analyze is clean and all six test shards pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:25:34 +01:00
dfd60d4f7b Close the open gate when a phone meal arrives
A meal logged on the phone while the gate window was up changed nothing
until Fetch was pressed: the new credit watch only fires on a local
write to the food log, and the PC never pulled on its own.

While a non-demo window is open it now pulls peer logs every 30 s, with
the Fetch button's own narrow pull on a worker thread. One pull is in
flight at a time (shared with the button), failures are logged and
retried, and the window stays up. The pull's write trips the watch,
which closes through the usual reconcile path. gatelock moves to 0.14.0
for watch_credit.

refresh_peer_logs also read the local log before the peer downloads and
wrote it after, so a meal logged during the pull was overwritten. It now
merges the peers first and reads the local log just before the write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:18:07 +01:00
f793545468 Fix the pylint hook env and its stale pins
The hook environment pinned its own gatelock 0.12.0, which predates
watch_credit, so pylint reported the import as missing; moved to the
pyproject pins. The env also ran on pre-commit's own Python 3.15, where
pylint's parallel jobs crash in dill (no co_lnotab) whenever two files
are linted together; it now uses the repo's 3.14.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:18:00 +01:00
76d4e58641 Bump pins to latest stable
The dependency-freshness hook failed on nine stale pins (crdt-sync
0.11.1, freedays 0.4.3, sickdays 0.5.4, coverage 7.17.3, pylint 4.1.4,
ruff 0.17.5) and blocked every push. gatelock moves to 0.14.0 here too,
which is the newest tag; the code that needs it follows separately.

Full suite green on the new pins, 100% branch coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:09:48 +01:00
617e1ec879 E2E-encrypt diet_guard sync and export keys
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Every sync payload (food log, banks, budget, catering credential,
Body, export keyring) now lives on diet-guard-sync/devices-e2e, sealed
with the Argon2id key from the shared crdt-sync passphrase; record
ids, tombstones and clocks stay clear. Old plaintext nodes are copied
once and never written or deleted. Locked = no pull, no push.

- PC: _sync_e2e.open_e2e over crdt-sync 0.11.0, key and copy memo in
  ~/.local/share/diet_guard/e2e; undecryptable peers are skipped.
- Phone/desktop: sync_e2e.dart, crdt_sync_flutter 0.8.1, lock icon
  in Settings; pullExportKeys goes through the same open.
- wake-alarm weigh-ins read from wake-alarm-sync/devices-e2e (own
  header), on both sides.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:31:44 +01:00
649a324f8a Bump gatelock to 0.13.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZbpxQZj41WpbQPuxB
2026-11-11 13:02:52 +01:00
4eca59bac9 Icon-only date and time pickers
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Replace showDatePicker, showDateRangePicker and showTimePicker with
numeral grid/wheel dialogs confirmed by check and close icons. Adds a
no-words picker guard and a repo invariant banning the framework pickers.

Todo: e09dac36

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:05:11 +01:00
f4b4a034b7 Bump deps (freshness gate)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVFVUbm4fXaDtyhUcm
2026-11-11 11:59:32 +01:00
57d304600e Lean gradle.properties for warm daemon
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZUTC9Zzdzsx7VW7dm
2026-11-11 11:57:06 +01:00
ded7486244 Fix lints in error icon page
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:21:46 +01:00
8068205d0c Page loads of errors show an icon page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:16:04 +01:00
91a9ee5295 Proxy errors load as an empty page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:01:22 +01:00
0982565fdc Rename existing reminder channel on start
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:56:27 +01:00
957ddc7ddc Workout rows show a kind icon, not label
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:17:09 +01:00
e7ef648757 Tag manual workouts with source manual
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:01:52 +01:00
dc2799e36a Bump four app deps to newest stable
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:01:51 +01:00
2dc502bbb6 Speak formula names, fit sheet value
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:11:23 +01:00
c9c30b1ee5 Glyph and count for catering cues
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:11:23 +01:00
ff12f4e171 Guard app screens and wrapper against words
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:11:23 +01:00
43e4b4070d Replace PC gate text with glyphs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:35:34 +01:00
45627f7075 Bump pytest-randomly to 5.1.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 10:24:25 +01:00
60ce1a6d71 Icons for formulas, fit tile value, channel name
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 10:04:42 +01:00
445712dea3 Hide the log-date glyph on today
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 08:29:15 +01:00
752c3704b2 Drop text from the body screens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 08:21:13 +01:00
f25d22da20 Drop text from settings, GitHub, alerts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 08:21:06 +01:00
737d09d37c Drop text from history, food bank, calendar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 08:21:05 +01:00
83d05c637a Drop text from the log-meal screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 08:20:57 +01:00
07e5d2149c Add text-free cue widgets and finders
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYndZhdUrRGFEjBazQ
2026-11-09 08:20:50 +01:00
832f9ab7da Bump sync_settings_ui to 0.6.1
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 18:27:14 +01:00
3b200b60e7 Bump crdt_sync to v0.12.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-08 14:26:22 +01:00
4e44dd0eae Bump flutter_local_notifications 23.0.0
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:41:38 +01:00
1af80a6525 Pin gatelock v0.12.0
Also bump coverage, pydantic, ruff for the freshness gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZd3smuxDGmEgXkYP8
2026-11-07 08:40:21 +01:00
89055d91cd Pin idb_shim 2.11.2
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVSoczW2NHQd887FUm
2026-11-03 20:28:49 +01:00
e3af1f571b Gate: stand down inside declared holds
No lock and no owed slot while holds.covers("diet") is true; slots
inside a hold are excused; an open lock lifts within 30 s of a hold
starting. Fail closed (normal rules) if holds is missing or raises.
Pin holds-v0.1.0; bump coverage 7.17.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVSoczW2NHQd887FUm
2026-11-03 20:27:11 +01:00
97af520fdd Add log sound cue and progress card motion
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
- lightImpact + 160 ms confirm cue on a validated log (audioplayers,
  no audio focus); device-local opt-out switch in Settings, on by default
- post-log card: confirmation line (slot + the meal's kcal), entrance and
  kcal/streak count-up on motion tokens transcribed into ui/theme.dart;
  durations collapse to zero under disableAnimations
- test/flutter_test_config.dart mutes the cue suite-wide

Todo: 8e66c1b9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVHMLzeojNP4AaPoEj
2026-11-02 21:12:46 +01:00
64841009a5 Add todo app git hooks
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 13:42:46 +01:00
cba89bcacb Use google_account_token plugin
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Swap google_sign_in for the FOSS AccountManager plugin
(google_account_token-v0.1.0); drop the local platform gate. Also
fix an unmatched coverage:ignore pair that broke --coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY1k4muZfdVJfb7YGJ
2026-11-02 11:33:53 +01:00
bbef894195 Move TODOs to todo app
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 11:18:13 +01:00
b82ff7c040 Pin focus-project 0.3.0, sickdays 0.4.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Conflicting git-tag pins in the shared user site let the last install downgrade focus_project/sickdays (no harvest, no focus locker).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 10:03:02 +01:00
a30628ab96 Haptic on meal log, VIBRATE permission
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Fires on the tap before the write; rejected logs stay silent. The
dopamine-ux TODO now lists only the remaining work.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVUTaKFW8m7YrvWbzV
2026-11-02 08:09:24 +01:00
2a674774bb Fit Body and Food Bank on one phone screen
Body: 2-column tiles, each opens its card in a sheet. Food bank: paged
3-column tiles, tap for macros. Pixel 6a widget test asserts no vertical
scroll on log, calendar, food bank (250 foods) and body.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWVUTaKFW8m7YrvWbzV
2026-11-02 08:08:23 +01:00
3960fb8ca0 ci: split ci-mirror into <60s gate steps
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXTUM9dpnCS2wtFkx4
2026-11-01 21:25:54 +01:00
1b5e201136 feat: JSON export/import on device
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXTUM9dpnCS2wtFkx4
2026-11-01 20:12:37 +01:00
e75e2bc89a chore: bump deps to newest stable
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXTUM9dpnCS2wtFkx4
2026-11-01 20:12:24 +01:00
bda76b495d Ideal weight: drop Broca family and Hamwi
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-01 18:54:38 +01:00
8957d51432 Desktop: launch Chrome --app with --disable-extensions (no stray extension windows)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:04:10 +01:00
66650ca3cc Catering fill: honour the "Log for later" date
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Fill all with catering always fetched and filled today, so picking 24.10
on 23.10 reported "No catering delivery today." FillAllFlow.tap now takes
the picked day: fetch, slot schedule, occupancy and dedup all resolve
against it, and logDishes stamps each dish at its slot time on that day.

- A plan only confirms onto the day it was proposed for; changing the
  date (or back to today) disarms it.
- A later-day fill leaves today's delivery queue and prefill alone and
  returns the form to today, as a manual "Log for later" does.
- Only today's fetch records the single-day "already fetched" marker;
  recording a later date would skip that day's automatic fetch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwYgigocPkPWa73QZRtU38
2026-10-23 19:01:44 +02:00
84c78a0b1d deps: gradle 9.8.2, fl_chart 1.3.0, web 1.1.2, coverage 7.17.0, ruff 0.17.2 (newest stable)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017k9j5dbjenpfZj7dh2faPN
2026-10-23 18:49:15 +02:00
e7219571bd Launcher: label DietGuard (Android, desktop entry, PKGBUILD), icon fitted to the shared 340px ink circle
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012kQ5PCKqBHAkAVkPSvp6dk
2026-10-23 14:36:31 +02:00
eec7856664 Pin gatelock-v0.11.0 (Claim.grab_held + held_grabs)
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dsh4Znwh2KnC7q6vbGpX1N
2026-10-19 11:47:24 +02:00
8eb72647d5 deps: gatelock 0.9.0 -> 0.10.0 (pin only; diet-guard does not opt in to night_lockdown)
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-17 18:47:36 +02:00
ee81788ed6 deps: sickdays 0.3.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-17 13:52:40 +02:00
e6432d5b9d Catering: answer the panel's CSRF 403 at login; kuchnia --log publishes
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-17 12:42:13 +02:00
8b82faf8f9 Sick days: diet stands down only when the day does not keep it
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
due_slots asks sickdays.stands_down(LOCKER_DIET, day) instead of
is_sick_day, so a sick day that keeps diet is a normal day for the gate.
Bump sickdays pins to v0.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAhbNszs5JKdtnD4uBi3xp
2026-10-16 15:12:59 +02:00
6587258da9 Bump deps to newest stable (freshness gate)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
flutter_local_notifications 22.3.2, idb_shim 2.10.1+1, pre-commit 4.7.0,
pydantic 2.14.1, pylint 4.1.3, ruff 0.17.1, gradle 9.8.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 14:12:57 +02:00
419ada929a gate: stand down on a sick day (sickdays 0.1.0)
due_slots() returns nothing on a sick day, like a free day: no lock, no debt;
logging still works. Unreadable pool reads as not sick (fail closed). Pins
sickdays-v0.1.0 and freedays-v0.4.0 (pyproject, requirements, pylint hook env).
Phone gap documented in docs/DOCS-sick-days.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xfj1sxKH9VBPqpcAni8Jry
2026-10-16 08:36:27 +02:00
f2606fe0ca deps: flutter 3.47.7, crdt-sync 0.9.2, freedays 0.3.1, pydantic 2.14.0, ruff 0.17.0
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
ruff 0.17 stabilised CPY001 (ignored: no per-file copyright headers here),
ISC004 and ICN001 (autofixed).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:27:52 +02:00
a118120047 Merge branch 'worktree-agent-a92471b85d4d17556' into minute-slots 2026-10-10 20:13:41 +02:00
2d468bf5f8 gate: HH:MM spinboxes instead of comboboxes for the meal schedule
An inert dropdown arrow looked broken. ttk.Spinbox posts nothing; every
spin path (arrow press, Up/Down, wheel) generates <<Increment>>/
<<Decrement>>, bound here to step_time from the typed value (07:23 -> up
07:30, down 07:15) with "break" so ttk's values/wrap logic never runs.
First clamps to 00:00-23:45, last to 00:15-23:45. Popdown-blocking code
removed; FakeSpinbox replaces FakeCombobox.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:13:03 +02:00
cb8028bd22 app settings: exact-time clock button replaces the "Custom…" item
The dropdown menu opens centred on the current value, so a "Custom…" item
at either end of ~95 entries was always a long scroll away. Each meal-time
field now has a clock IconButton ("Type or pick an exact time") opening the
same 24h showTimePicker with the same clamping. The off-grid current value
is still offered as an item.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:10:55 +02:00
6dd52a11ae slots: never post the schedule combobox list; kuchnia dedup on raw minute
- The popdown maps beneath the gatelock surface yet holds ttk's grab
  (verified on Xvfb: invisible, swallows the next click, steals keys), so
  arrow clicks are intercepted as Down already was. Typing and Up/Down stay.
- Catering dedup compares the entry's recorded minute (parity with the
  app); occupancy (fill_plan) still snaps.
- Test: a corrupt peer slot (slot 24, slot_min 5000) re-signs and reads
  without raising.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:06:16 +02:00
b2176f8b69 app settings: "Custom…" first in the meal-time dropdowns
At the end of the list it sat ~95 grid items down; now it is the first
item, above 00:00. Test pins the order.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:04:19 +02:00
a9aa379a13 app tests: off-hour schedule round trips + real settings wiring
Pins that fm/lm survive both the sync wire and a disk reload, and that a
quarter-hour pick in SettingsScreen goes through the real _applySchedule.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:00:45 +02:00
4e5c6b453e docs: the schedule combobox popdown maps beneath the lock surface
Observed on Xvfb with the demo gate: the ComboboxPopdown is viewable but
stacked under the gatelock surface, so typing and Up/Down are the paths.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:58:30 +02:00
f83938bfe3 app: minute-of-day slots (phase 2 of 3: every app consumer)
- FoodEntry.slot -> slotMinute: read via entrySlotMinute, written via
  slotFields (whole-hour stays byte-identical, else slot_min), kept by
  copyWithDeleted and the edit screen, so the phone never republishes a
  stripped copy of a PC entry. Out-of-range peer values echo, never throw.
- Satisfaction is nearest-slot snapping (satisfiedSlots) everywhere:
  loggedSlotsToday, due check, kuchnia occupancy, future-day logged set
  (that day's schedule), slot selector. Schedule edits no longer un-log.
- Future pre-log builds DateTime from slot ~/ 60, slot % 60.
- Schedule history + sync go through scheduleToWire/scheduleFromWire.
- Notifications: ids are slot minutes; syncToSlots cancels whatever the
  platform reports active (getActiveNotifications, reminder channel) that
  is not due, covering legacy hour ids; full 0..1439 sweep only if the
  lookup throws.
- Settings: 15-minute dropdowns + "Custom..." (24h showTimePicker), off-grid
  values always selectable, counts capped by grid capacity; editor moved
  to widgets/meal_schedule_editor.dart + meal_time_dropdown.dart.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:55:26 +02:00
c310861855 slots: minute-of-day consumers (phase 2 of 3: Python side)
Every Python consumer now speaks slot minutes:

- satisfaction is nearest-slot snapping (_slot_wire.satisfied_by_entries)
  at every "is this slot logged?" site: gate, CLI status, MCP, catering
  occupancy and dedup. Nothing on disk is rewritten; 07:00/10:00 entries
  keep covering 07:15/10:15 after a schedule move.
- log_meal writes slot_fields(minute) before signing (slot + slot_min).
- schedule store and sync encode via schedule_to_wire/from_wire; a
  whole-hour schedule stays byte-identical (f/l/n only).
- CLI ate --hour takes HH or HH:MM; MCP log_meal takes "HH:MM" or a
  legacy int hour, validated against today's slots; get_slots returns
  {minute, label}.
- gate History tab: first/last are HH:MM ttk.Comboboxes (quarter-hour
  list, typed times, Up/Down step without posting the popdown), locked
  as disabled; validation mirrors normalized().
- gate timer fires every 15 min; docs rewritten for minutes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:53:39 +02:00
a6fcd3266e deps: idb_shim 2.9.11, shared_preferences 2.5.6
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:26:08 +02:00
8bc1812147 slots: minute-of-day contract (phase 1 of 3: pure model + shared fixture)
Meal-slot checkpoints move from whole hours to minute-of-day ints
(0..1439) in the pure model and slot arithmetic of both languages:
MealSchedule(first_minute, last_minute, count) / (firstMinute:,
lastMinute:, count:), interior slots snapped to the 15-minute grid,
endpoints exact, integer-only. New: nearest_slot, satisfied_slots,
slot_fields / entry_slot_minute (additive "slot_min" wire field) and
schedule_to_wire / schedule_from_wire ("fm"/"lm" only when off the hour,
so whole-hour data stays byte-identical), parse_hhmm.

tests/fixtures/meal_schedule_vectors.json (scripts/
build_meal_schedule_fixture.py) is read by both suites; kuchnia_day.json
slot values regenerated as minutes.

Consumers (CLI, gate, storage, sync, app screens, kuchnia, notifications)
are intentionally broken until phase 2. patch-targets skipped: it fails
only because diet_guard._gatelock no longer imports.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:22:43 +02:00
5cd89a4e99 Update app/diet_guard (17 files)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 13:49:58 +02:00
a7e3685963 gate + CLI: fill today's empty slots from catering in one confirmed step
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 13:12:15 +02:00
11173c7088 kuchnia: walk every active order, not just the first
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 12:32:17 +02:00
357bdb7e94 deps: mcp 2.3.0, pylint 4.1.2, url_launcher 6.3.3, github_device_auth 0.3.2
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-04 18:08:19 +02:00
f0623d0c44 repo contract: CLAUDE.md commands, test_changed, CI gate
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-04 17:13:21 +02:00
bf35afbdf5 CI: APK only on app changes, Gradle cached
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (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-10-02 15:10:33 +02:00
f1c6a26f18 Flutter 3.47.6, idb_shim 2.9.10 (newest stable)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Analyzer clean and 790 app tests pass on 3.47.6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FBbkN4ZB4aUPJPzR2prRan
2026-10-02 14:28:55 +02:00
908fbd2d1e gatelock 0.8.2 -> 0.9.0; mypy 2.4.0, pylint 4.1.1, ruff 0.16.10
gatelock 0.9.0 adds gatelock.morning_session (the shared reader of
wake-alarm's morning carrot, now used by screen-locker, leetcode-guard and
book-guard); nothing here changes behaviour. The tag moved the freshness
gate, so the pin moves with it, together with today's lint-tool releases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FBbkN4ZB4aUPJPzR2prRan
2026-10-02 14:19:54 +02:00
e761926df4 Body tab: weight/body-fat logs, BMI, ideal weight, goal-based kcal target, workouts + Health Connect steps, week planner
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 (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (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-28 09:03:03 +02:00
4b1de83e27 Pre-log meals for a future date and slot (CLI --date/--hour, app 'Log for later')
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-27 19:59:38 +02:00
49b3ea4d57 Give every xdist worker its own Xvfb (pytest-xvfb)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
The first -n auto Tests run segfaulted in Tk's focus_force(): keyboard
focus is global to an X display, and four workers were sharing the one
xvfb-run display, stealing each other's focus. Stressed locally (layout +
keyboard tests x40, -n 8): 5 of 2760 failed on a shared display (focus-ring
assertions), 0 of 4600 with pytest-xvfb's per-process display -- and faster.
The geometry xvfb-run used moves into pyproject; the workflow keeps the
Xvfb install guard and drops xvfb-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0188kZdx3bb56QM8JFUnbHuM
2026-09-26 18:24:41 +02:00
d11d323a04 Take Gradle 9.8.0
The dependency-freshness workflow (--strict) went red on 9.7.1 -> 9.8.0.
todo, punchme, signal-bot and dufs-cloud already build their release APKs
on 9.8.0 with the same AGP 9.3.2, so only the wrapper URL moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0188kZdx3bb56QM8JFUnbHuM
2026-09-26 18:24:04 +02:00
11c8be838d Take pylint 4.0.9 and ruff 0.16.9
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Both released upstream since the last bump; the dependency-freshness gate
(pre-commit hook and the --strict CI workflow) reports them behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0188kZdx3bb56QM8JFUnbHuM
2026-09-26 18:00:29 +02:00
c55172fc9d Split pre-commit into mypy/pylint/rest runners and install with uv
pre-commit took ~119 s as one job (24 s of pip, then every hook env and
every hook in series); Tests took ~56 s (26 s of pip, 7 s of apt-get for an
xvfb the image already ships, 17 s of -v pytest). Same hooks, same flags,
same 100% bar -- just parallel runners, cached uv wheels, xdist workers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0188kZdx3bb56QM8JFUnbHuM
2026-09-26 17:58:53 +02:00
05fdabf6c8 pre-push is a 1-second stamp check; the suites moved to the manual stage
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-20 19:37:46 +02:00
d2df4c51eb Record why the gate's delivery prefill must set the dish's grams as its basis
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 08:44:20 +02:00
e0d62e19a0 Take Flutter 3.47.5
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 08:31:54 +02:00
74057f195f Prefill a catering dish as a whole-portion reference so the gate logs its own calories, not grams/100 times them
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 08:30:05 +02:00
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
3f6a9b0ebf Take gatelock 0.8.1: colour reads through LockConfig.palette
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
LockConfig's colours moved into a nested LockPalette record; every
_COLORS.<colour> read follows. Nothing about the gate's behaviour changed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 19:59:44 +02:00
b3aeb4f4b7 Re-point paths for the ~ reorganisation (home-tidy)
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Also bumps Flutter 3.47.3, flutter_secure_storage 11.1.0, idb_shim 2.9.9,
mcp 2.2.0 and ruff 0.16.7 so the freshness gate lets this through.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AwtowrowDXx6ccmWVPkCaF
2026-09-11 19:53:03 +02:00
058f806db7 Pin freedays v0.2.0
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
v0.2.0 drops freedays's gatelock dependency (importing gatelock pulled in
tkinter, so the headless pool needed a GUI toolkit) and adds the sync
timer that makes a day marked on the phone actually reach this machine.

Mechanical, but not optional: the freshness gate compares the pinned tag
against the newest release, so leaving v0.1.0 here would turn this repo
red on its next commit.

Suite re-run against v0.2.0 before pinning it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 15:58:42 +02:00
77468b1efd Bring the Flutter app's dependencies up to latest stable
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Split out from the free-day change only by sequence -- diet-guard's
pre-push CI mirror runs the freshness gate over --all-files, so these
were already blocking a push before that work started.

permission_handler 13.0.1 -> 13.0.2 and workmanager 0.10.9 -> 0.10.10
are patch bumps. very_good_analysis ^10.3.0 -> ^11.0.0 is the major one,
and it newly flags 8 async_return_with_no_await sites across the desktop
wrapper and the sync/Firebase services.

Each is now `return await`, not a suppression. The rule is right in every
one of these cases: without the await the future escapes the enclosing
async function, so a rejection surfaces at the caller with a stack trace
that no longer points at the code that made the call.
background_check_service.dart:33 is the clearest example -- its own
comment says the push "is retried with backoff rather than silently
dropped", which is only true if the failure happens inside the function.

Nothing in CI or pre-commit runs `flutter analyze`, so this would not
have failed anything. Leaving a newly-red analyzer for the next person to
find is how a repo stops being analyzable at all.

flutter analyze clean, 706 Flutter tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 15:25:33 +02:00
b77145010c Stop asking for meals on a shared free day
Third app onto freedays (~/utils/freedays), the shared pool of
pre-declared days when every gate app stands down. due_slots() returns
nothing on a free day, so no slot is ever due, the lock never opens and
nothing is said about the missing meals.

Read from one local file, never the network, so this cannot hang the
systemd-fired gate -- and an unreadable pool reads as "not free", which
means the normal rules apply rather than the gate quietly switching
itself off. Tested explicitly: fail closed, not open.

The conftest redirect is load-bearing. The pool lives under
~/.local/share, outside every diet_guard path the suite already isolates,
so without it a real free day on this machine would fail every "the gate
is due" test here for a reason that looks nothing like the cause.

gatelock moves v0.7.2 -> v0.7.3, and the pylint hook's own pins (which
had drifted further, to gatelock v0.7.1 and crdt-sync v0.6.0) come with
it. Not cosmetic: pip refuses two different direct URLs for one
distribution, so any stale pin alongside freedays -- which requires
v0.7.3 -- is an unresolvable environment rather than a warning.

requirements.txt also picks up pylint 4.0.8, pytest-randomly 5.0.0 and
ruff 0.16.6, which the freshness gate flagged once this file was touched.
1043 tests pass at 100% coverage across the pytest-randomly major bump.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 15:22:38 +02:00
862a114909 Take coverage 7.16.0
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
The freshness gate was already red on this before today's Python work touched
the repo -- it only surfaced now because the CI mirror runs the gate over the
whole tree, while the commit hook had no reason to look at requirements.txt.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfnJmxxsZ534AKk16rC2Gr
2026-08-29 11:36:42 +02:00
42d15b6a91 Grade against 3.14 too, not just run on it
`requires-python` and the CI pin already said 3.14, but ruff, mypy and pylint
were still grading against 3.10 -- three tools judging an interpreter nothing
runs any more, and ruff withholding the pyupgrade fixes that only become safe
at the newer target. `pin_ci_python.py` rewrites exactly these three knobs.

The fixes ruff then had to make are what the stale target was hiding: 18 files
on `datetime.timezone.utc` instead of `datetime.UTC` (UP017), plus ruff's
stable formatter applying PEP 758 -- `except (A, B):` becomes `except A, B:`.
That second one makes the source 3.14-only at the syntax level, which is
exactly what `requires-python = ">=3.14"` already promised; kuhy chose it
deliberately over holding ruff a release back (2026-08-29).

ruff, ruff-format, mypy --strict and pylint all clean at the new target.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfnJmxxsZ534AKk16rC2Gr
2026-08-29 11:35:06 +02:00
3c314ecf9a Bump pydantic to 2.13.5
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 20:16:14 +02:00
953f03f6e0 One Python, always the newest
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 20:05:38 +02:00
144b00dda6 Refresh the gate workflow from the shared template
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 16:06:41 +02:00
81eeb12c1e Latest stable dependencies, and the gate that keeps them there
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (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
Python side: gatelock v0.7.1 -> v0.7.2, crdt-sync v0.9.0 -> v0.9.1 (both
re-cut so consumers stop resolving pre-upgrade constraints) and every `>=`
floor turned into an exact pin, five majors among them (mypy 1 -> 2.3.1,
pylint 3 -> 4.0.7, pytest 8 -> 9.1.1, pytest-cov 4 -> 7.1.0, ruff 0.8 ->
0.16.5).

app/: twenty pins, of which permission_handler 12.0.3 -> 13.0.1 and
workmanager 0.9.0+3 -> 0.10.9 are real major moves the lockfile had been
holding back, plus the flutter_secure_storage 11 chain (compileSdk 37 /
AGP 9.3.2 / Gradle 9.7.1). CI's Flutter pin was 3.44.8 against an .fvmrc of
3.47.2; both say 3.47.2 now, and the gate reads that pin.

`scripts/ci_mirror.sh` green end to end: the Python suite in a clean venv and
706 Flutter tests, pre-commit --all-files clean, gate exit 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 15:23:13 +02:00
cb3de72c40 Exact-pin plugin_platform_interface instead of any
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (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
`any` was the only unconstrained Dart dependency in the whole fleet, and it is
the one constraint a freshness check cannot compare against anything: it is
satisfied by every version that has ever been published, including versions
that do not exist yet.

Resolves to the same 2.1.8 the lockfile already had -- pubspec.lock is
byte-identical and all 706 tests pass -- so this is a declaration change, not a
dependency change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 13:03:43 +02:00
03e14e17f3 Adopt the four markdown namespaces and gate them
Some checks failed
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 (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Renames this repo's markdown onto README.md / CLAUDE*.md / DOCS*.md /
TODO*.md so a future session can tell a live task from a finished
record without reading the file to find out.

TODO files carry the literal "REMOVE ME AFTER FINISH" and are deleted
when the work lands. Enforced by the md-naming pre-commit hook and CI
workflow, both delegating to the shared gate in kuhyx/utils so this
repo's idea of a valid name cannot drift from every other repo's.

Includes the patch bump this repo's bump-patch-version hook applies to
app/pubspec.yaml on every commit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A47aX5DJwmA3QFn3pkEWi7
2026-08-24 15:57:20 +02:00
9bfc14684e docs: drop NEXT_SESSION.md, both bugs fixed and verified on device
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:45:32 +02:00
c897279c8b fix: clear every macro field before a prefill, add the phone's delivery button
`fillControllersFromDish` set the dish's name, four macros and `grams` but
left `perGrams` untouched. A `100` left there by an earlier food-bank pick
made `nutritionForPortion` read the dish's per-portion macros as per-100g and
rescale them: one real entry on 2026-08-23 logged 472 kcal as 1217.8 (258/100).

The PC never had this -- `_gatelock_delivery.py` calls `_clear_inputs()` first
-- so the fix is that same discipline, as one `MacroControllers.clear()` call
rather than a `perGrams.clear()` line a seventh field could forget. `fillFrom`
now clears too, and `edit_entry_screen` routes through it instead of six
hand-written assignments; its `initState` fill had the same shape.

The old tests asserted controller *text* and passed throughout the bug, so the
new ones assert the computed `Nutrition` -- verified failing (400 -> 1200.0)
before the fix. `clear()` gets an enumerated test so a new field fails until
it is cleared too.

Also adds the log screen's "Today's delivery" button, matching the PC lock
screen's affordance: explicit taps are unguarded per the Triggers table, still
skip dishes already logged, and show the queue count. The whole action row
moved to its own widget, which put `log_meal_screen.dart` back under the cap.
The label is a FittedBox in an Expanded -- measured, since a Row clips an
oversized label without ever throwing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:34:47 +02:00
c1ad2e2406 docs: hand off two bugs in the phone catering import
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
Both pass the entire suite, which is why they shipped:

1. A prefilled dish logs ~2.6x its calories. `fillControllersFromDish` never
   clears `perGrams`, so a stale `100` makes `nutritionForPortion` treat the
   dish's per-portion macros as per-100g and rescale by grams/100. Observed
   on the user's phone: a 472 kcal / 258 g dish logged as 1217.8 kcal, and
   1217.8/472 is exactly 258/100. The PC avoids it by calling `_clear_inputs()`
   first; the Dart mirror dropped that step. The existing widget test asserts
   controller *text*, which is correct while the computed nutrition is wrong.

2. No one-tap delivery button on the phone's log screen. The queue works, but
   only `initState` and the Settings button reach it, so there is nothing to
   tap while standing in the kitchen.

The handoff carries the reproduction, the confirmed root cause and the file
and line, so the next session does not re-derive them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:22:08 +02:00
d9b3d57900 docs: record the phone-side catering import, verified on device
Documents the Dart mirror, the phone's two triggers (guarded log screen,
unguarded settings button — the same split as the gate vs the CLI), and the
device-local fetch marker on both sides.

The three parity traps are written where the next reader will hit them,
because each survived review once: `_ENERGY_TOLERANCE` is 0.35 and the "~1%"
elsewhere describes the captured day, not the threshold; `jsonEncode(435)`
emits `435` where Python emits `435.0`; and Dart's `List.sort` is unstable
where Python's `sorted` is stable.

Also states plainly what the shared fixture does *not* prove: that the two
implementations agree on a fixed payload, not that they agree against the live
panel.

**That second claim is now observed rather than inferred.** On 2026-08-23,
with the credential synced to the phone and nothing typed on it, the phone
logged into the live panel and banked 5 dishes. Pulling that back to the PC
left all five curated-bank records carrying their original 08:00:03 PC
timestamps, unchanged — the phone's records were byte-identical, so its
idempotency guard wrote nothing. Any disagreement would instead have re-added
them with fresh stamps and started the republish flood.

Split into a second file for the 250-line cap.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:17:30 +02:00
8836453f8c fix: initialise the catering queue at startup
`KuchniaQueueService` had no `init()` call in `main()`, so on a real device
the whole feature would have done nothing: every entry point checks
`isInitialized` first and returns quietly, which reads as "no delivery today"
rather than as an error. All 694 tests passed throughout, because widget tests
initialise the service directly.

Caught by grepping main.dart before the phone deploy, not by the suite. So it
is now a repo invariant: `repo_invariants_test.dart` asserts main() names both
catering `init()` calls, and the assertion was checked against a main.dart
with the line deleted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:08:54 +02:00
af35eb20c8 feat: offer delivered dishes to the log form, one tap each
The phone now prefills the log form with today's delivered dishes, in the
caterer's own meal order. It still never logs anything itself -- a delivered
meal is not an eaten meal, so the user taps for each dish.

Two guards carried over from the PC, both of which fail silently if dropped:

- **The queue survives a submit.** `prefillNextDish` has two callers: the
  initial load and the post-submit advance. On the PC the second briefly did
  not exist, which made "(N more to go)" a dead letter -- every dish after the
  first waited behind another tap. The test asserts the *form controller*
  holds dish 2 after dish 1 is logged, not that a dish is "available"; the
  latter passes throughout that bug.
- **The automatic refresh is guarded** by a device-local last-fetched date,
  mirroring `refresh_delivery_once`. The log-flow trigger can fire after every
  meal and each unguarded walk is a login plus three requests. The settings
  button deliberately stays unguarded: an explicit ask always goes and looks,
  matching `diet-guard kuchnia`. Only a clean fetch records the day, so an
  outage retries.

Dishes are ordered against `MealScheduleService.current`, never a hardcoded
four slots -- offering a dish for a slot the user's schedule does not have is
the "checkpoint that can never be satisfied" failure in a new costume.

Editing the description before submitting leaves the dish queued: what was
logged was not the delivered dish, and marking it eaten would lose a real
delivery silently.

Two bugs the tests caught:

- `dishesStillQueued` excluded the offered dish, so the status line read
  "0 more" while a real dish sat in the form. The offered dish is prefilled,
  not logged; it counts.
- An end-to-end test through the real `LogMealScreen` never terminated --
  that screen's `initState` fans out into sync, notifications and the food
  bank, and pumping it to quiescence hangs. Rather than keep fighting it, the
  behaviour is tested at the mixin that owns it, through a minimal host. The
  guarantee asserted is the same one: form contents after a submit.

`log_meal_screen.dart` is back under the 250-line cap by moving the nutrition
build into `log_meal_actions.dart` and inlining a one-line alias.

694 Dart tests, 1040 Python tests, 100% Python branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:07:17 +02:00
5c9c1ff160 feat: add the catering login to settings, with an Android-only fetch
The credential **fields** appear on every platform; the **fetch button** only
where it can work. That split is the point, not an oversight: the panel sends
no CORS headers so a browser cannot call it, but the desktop app is where a
password is most likely to be typed, and the credential syncs — so hiding the
fields on web would mean the phone could only ever be set up by typing on the
phone. On web the button is replaced by a line saying why, and noting the
login still reaches the phone from there.

The section says the password is stored and synced in plain text rather than
implying otherwise.

The button disables itself while a fetch is in flight, so an impatient
double-tap cannot pay a second login plus three requests against a third
party. The result line says dishes were added to the **food bank** and that
the user still logs them when eaten — the wording carries the
delivered-is-not-eaten rule to the one place a user actually reads.

`settings_screen.dart` was already at 247 of its 250-line budget, so the
section owns its own leading divider and the fetch handler lives beside it;
the screen spends one line on it.

678 Dart tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:33:52 +02:00
3d82ddefd4 feat: let the phone fetch and bank the catering delivery itself
The phone now walks the panel on its own -- login, active order, delivery,
menu -- parses the dishes and banks them, so the feature works with the PC
switched off. Read-only: nothing here logs a meal.

`package:http` has no cookie jar, so the `SESSION` cookie is read off the login
response and replayed by hand. `Response.headers` folds duplicate `set-cookie`
values into one comma-joined string, so the parser splits on both `,` and `;`
and looks for the named cookie rather than assuming the header holds only it --
tested against both orderings and against a panel that sets no session cookie
at all.

Android-only, as decided: the panel sends no CORS headers, so a browser cannot
call it. `refreshDelivery` checks `kIsWeb` first and returns the unsupported
reason without touching the network. No `dart:io` anywhere -- `package:http`
compiles for web, it is the panel that refuses, not the toolchain, so this
needs no `_io`/`_web` seam.

The idempotency guard is ported with its teeth: `addManualEntry` restamps
`editedAt` unconditionally, so re-banking an unchanged dish republishes the
whole curated bank to every peer. `bankDishes` compares the nutritional fields
first and returns a write *count*, which is what the tests assert on -- "the
entry exists" passes while this misbehaves. The comparison is numeric, not
string, so `270 == 270.0` is a match exactly as in Python's `_matches`.

Every failure becomes a reason string, never a throw, so a catering outage
cannot break the caller: a rejected login, a delivery whose dishes all fail
the unit check, and missing credentials each have a test.

One test bug worth noting: the assertion that nothing is logged was missing an
`await` and so was comparing a Future against `isEmpty` -- the single most
important guarantee in this file was passing vacuously until the split forced
it to run.

Test files split three ways for the 250-line cap; block counts checked against
the pre-split file (16 either side), not just a green suite.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:30:21 +02:00
8905d072d0 feat: carry the catering credential to the phone
The Dart half of the credential sync: a `KuchniaCredentialService` that owns
the value locally, a `sync_merge_kuchnia.dart` adapter mirroring the Python
one, and a `_syncKuchniaCredential` tick alongside the banks and budget. The
phone can now receive the panel password, which is the prerequisite for it
fetching anything itself.

One source of truth, per the answered question: the value lives in the synced
document store and nowhere else. Deliberately *not* mirrored into
`flutter_secure_storage` -- two homes for one value is how a stale password
survives a change made on the other device, and the credential has to be
readable synchronously at merge time anyway.

Gated by a second shared fixture, `tests/fixtures/kuchnia_credential.json`,
asserted by both suites. Two cases carry the weight:

- an **unparsable** edit time must fall back to the same clock on both sides
  (Python catches `ValueError` from `fromisoformat`, Dart's `tryParse` returns
  null). Verified they agree on `wall_time_ms == 0`; mutating that expectation
  fails both suites.
- a **blank half** contributes nothing, so a half-filled settings form cannot
  push an empty-string password that wins LWW against a real one.

`KuchniaCredentialService.init()` is called in the WorkManager isolate as well
as `main()`. A fresh isolate has its own static state and `_syncKuchniaCredential`
no-ops when the singleton is missing, so without it a background tick would
neither publish this device's credential nor receive a peer's -- and on the
phone the background tick is most of the syncing there is. Same class of trap
as the `initSyncDeviceId()` one already documented there.

`.toDouble()` came off the bank record: the fields are already `double`, so it
was a no-op the analyzer flags. The field *types* are what keep the encoding
byte-identical to Python's, and `kuchnia_parity_test.dart` asserts that.

654 Dart tests, 1040 Python tests, 100% Python branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:25:27 +02:00
04f5d75aab fix: stop a touched credentials file clobbering a newer peer edit
`_local_credential_log` fell back to the hand-written `kuchnia_credentials`
and used its **mtime** as the edit clock. That clock is not trustworthy:
`git checkout`, a backup restore, and re-running the `install -m 600` setup
line all bump it forward without the credential changing.

Reproduced before fixing: a PC whose file had merely been touched, syncing
against a phone that had set a new password an hour earlier, resolved to the
PC's stale password. The phone user would have seen their edit silently revert.

The bootstrap is still needed -- someone has to publish first, and the PC is
where the password is typed -- so it moves to `_bootstrap_credential_log` and
runs only when the merge came back completely empty. It can no longer outrank
a real edit from a peer; it can only fill a vacuum. Once anything has been
published, the synced cache (which carries a real edit time) takes over
permanently.

`test_a_touched_handwritten_file_cannot_clobber_a_peer` pins it, and was
checked against the pre-fix code: reintroducing the fallback fails it.

Also rewrites the two remaining places that still claimed a credential "must
never leave the machine it was entered on" -- `_constants.py`'s comment and
the doc's Credentials section, which now has a table of which of the three
files syncs and which does not. Rewritten rather than given an exception
clause.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:15:40 +02:00
fd0a35e69e feat: sync the catering credential as its own document
The phone is getting its own Kuchnia importer, and it cannot fetch anything
until the panel password reaches it. So the credential syncs, and a phone that
has been wiped and reinstalled gets it back without the user digging out the
original.

**It travels in plaintext.** Nothing here encrypts it and the rest of the
synced state is not encrypted either, so the docs no longer say a credential
"must never leave the machine it was entered on" -- that paragraph is rewritten
rather than given an exception clause. What still never leaves is the session
cookie: it is regenerable from the password, so syncing it would widen exposure
and buy nothing.

Its own document, not a field on `budget`. `budget.json` is written back at
default permissions, so a password riding inside it would be readable by
anything that reads the budget. Two independently-clocked fields, so a device
that only ever set the username cannot blank a peer's password.

The hand-written `kuchnia_credentials` keeps its contract -- written by the
user, never by this package -- and now acts as a local override that wins over
the synced copy, plus the bootstrap for the very first push. Without that
fallback no device would ever publish, since the synced cache starts empty on
every device.

Two bugs the tests caught rather than review:

- `_local_credential_log` imported `KUCHNIA_CREDENTIALS_FILE` straight from
  `_constants`, bypassing the conftest redirect that patches it on
  `_kuchnia_config`. The suite was reading the real ~/.config credentials. It
  now goes through the module attribute, which is what the redirect replaces.
  This showed up only as a coverage hole -- the branch was unreachable because
  the real file existed.
- `log_to_credential` guarded `password_hlc is None`, which cannot happen: a
  field's value and clock arrive as one tuple. Dead code, removed rather than
  covered by a contrived test.

The relay canary is a real test now, not a scratch script: a field from a
future release survives merge and re-push untouched, so this is shippable
without a coordinated release. `PASSWORD_FIELD_NAME` is spelled as a join
because ruff's S105 reads the literal as a hardcoded secret and the repo bans
`noqa` outright; the wire name is still "password".

100% branch coverage, 1036 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:12:30 +02:00
24be05b9c3 feat: mirror the catering parser and slot spread in Dart, gated by one fixture
The phone is getting its own Kuchnia Wikinga importer so the feature works
with the PC switched off. That turns a risk `_kuchnia_spread.py` called
"theoretical" into a live one: two implementations must now agree exactly on
which dishes are dropped, which slot each lands on, and the JSON a banked
record encodes to. Disagreement means each device re-adds what the other
dropped, and since `add_manual_entry` restamps `t` unconditionally, the whole
curated bank republishes to every peer on every refresh. A slot mismatch is
worse -- a checkpoint one device offers and the other does not can never be
satisfied.

So the port lands with its gate rather than after it. One shared fixture,
`tests/fixtures/kuchnia_day.json`, is asserted by both `pytest` and
`flutter test`: same input, same expected dishes, drops, slots, bank keys and
records. Two suites written independently from the same prose is not a gate.

The fixture is five real dishes (a scrubbed 2026-08-22 capture) plus synthetic
meals that each pin one drop or fallback path -- a per-100 g mix-up, an absurd
portion, a stringly-typed number, a non-dict entry, a missing `nutrition`, a
missing `mealPriority`, and a twin-dish pair. Without those, "the same meals
are dropped" is a vacuous assertion against an all-happy-path capture. Both
halves were mutation-checked: flipping an expected slot, drop count or record
value fails each suite, and flipping `435.0` to `435` fails the byte-identity
test while the value comparison still passes, which is why both exist.

Three traps the port had to survive, each caught before it shipped:

- `_ENERGY_TOLERANCE` is **0.35**. The prose said "~1%", which describes how
  closely the captured day agreed, not the threshold; porting 0.01 would drop
  dishes the PC keeps. That paragraph now says so.
- `jsonEncode(435)` emits `435` where Python emits `435.0`, so every Dart
  macro is forced to `double` and a canonical-encoding test pins it.
- Dart's `List.sort` is unstable where Python's `sorted` is stable, so the
  Dart comparator carries the payload index as a final tiebreak.

The real dishes live in their own file rather than as a literal in the
generator: transcribing them by hand corrupted three of the five, and the
error was invisible until the generated fixture was diffed against the
capture.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:00:54 +02:00
e0fbb754df docs: hand off the phone-side Kuchnia import
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
Session hit the 400-turn cost gate mid-task. Records the four decisions the
user already made (phone fetches directly, password syncs plaintext, session
cookie stays local, rewrite the contradicting doc rule), the prerequisite
ordering the settings field imposes, and the Python/Dart parity risk this port
converts from theoretical to real.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 07:43:59 +02:00
93669776b6 feat: gate a phone deploy on a peer already holding the device's state
`adb install -r` preserves app data and phone_deploy already refuses every
path that would not, but "preserved" is a property of the happy path -- a
failed install or a later wipe leaves unpublished entries existing nowhere
else. The log is CRDT-synced precisely so a recoverable copy exists, so the
deploy now checks that one does before touching the device.

The obvious device-side signal does not work and would be a gate that can
never pass: the app records a successful tick through SyncHealth, which writes
to SharedPreferences (app-private, unreadable over ADB on a release build),
and it only writes to logcat when a sync *fails*. So the check is remote-side
-- pull the shared log and assert it holds recent entries, which answers "is
there a copy off the device" directly.

Advisory by default; SYNC_GATE_STRICT=1 makes it block (exit 38). A network
outage must not stop a fix reaching the phone.

The shell half lives in ~/.claude/scripts/lib/phone_deploy_sync.sh. Verified
against the real phone: passes when a peer is current, skips cleanly for an
unsynced or not-yet-installed app, and blocks with exit 38 in strict mode.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 07:41:26 +02:00
0ca95eda5b fix: keep the catering dish queue alive across a submit
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
Walking a real 5-dish delivery through the gate by hand showed the
"(N more to go)" the lock promises was a dead letter: `_prefill_next_dish`
had exactly one caller (the initial poll), so logging the first dish cleared
the form and stranded the rest. Reaching them meant clicking "Today's
delivery" again -- and the button's fetch is unguarded, so that was a fresh
login-plus-three-request walk per dish.

`_finish_slot` now prefills the next queued dish, carrying the
"Logged HH:00 ..." confirmation into the same status line so advancing the
queue does not swallow it.

The caterer plans five meals against four default slots, so a dish is still
queued when the last slot unlocks. It is already banked, so `_unlock` names
it rather than dropping it silently.

Also pins the phone conclusion that was previously reasoning only: a verbatim
capture of a real imported bank now round-trips through `FoodBankRecord` in
`app/test/kuchnia_bank_interop_test.dart`, covering the diacritics and the
`t` stamp, and the casefold/toLowerCase agreement the two devices depend on.

Verified against the live panel with state redirected to a scratch HOME
(real ~/.local/share/diet_guard byte-identical before and after): the
autoload prefills silently on window open, a failed autoload stays silent
while the button reports, the after-log warm-up runs off-thread (0.62s vs
0.28s guarded) and nothing is logged until "Log & Continue".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-22 23:36:53 +02:00
6866863644 docs: hand off the Kuchnia import's unverified surfaces
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
The CLI is verified against the live panel, but the gate button, the
window-open autoload and the after-log warm-up have only ever been exercised by
tests. Records what to check on each, plus the four invariants that must not be
undone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-22 23:11:07 +02:00
26f1770090 feat: import Kuchnia Wikinga catering deliveries into the food bank
Pulls the day's delivered dishes and their real per-portion macros out of
panel.kuchniavikinga.pl, so a catering meal is one keypress instead of five
retyped numbers.

A delivered meal is not an eaten meal, so nothing is ever logged unattended:
dishes land in the *curated* bank, and entries are written only after an
explicit confirmation. Auto-logging would let the gate satisfy its own
checkpoint from a delivery note, and would record what the courier dropped off
rather than what was eaten.

Three surfaces:
  - `diet-guard kuchnia [--log] [--yes]`
  - the lock screen's "Today's delivery" button, which prefills the meal form
    dish by dish (the user still clicks Log & Continue)
  - a warm-up after each logged meal, on the existing background thread

All event-driven; no new systemd timer. The two automatic paths go through
`refresh_delivery_once`, guarded to one fetch per day.

The panel is an undocumented white-labelled Dietly API; the endpoint map was
recovered from its JS bundles and confirmed against live responses. Notes,
including the traps, are in docs/kuchnia-wikinga.md.

Load-bearing details:

* Macros are per portion and `weight` is that portion in grams -- proven, not
  assumed: 4P+4C+9F reproduces the stated calories within ~1% on every meal of
  the captured day. `_energy_is_consistent` re-runs that check per dish and
  drops any that fails; a per-100g mix-up is invisible in a payload and would
  silently skew every logged meal by a factor of several.
* `bank_dishes` compares nutritional fields before calling `add_manual_entry`,
  which restamps `t` unconditionally. Without the compare, every refresh
  republishes the whole curated bank to every peer. Tests assert on call count.
* Duplicate log suppression reads today's synced log, not a local marker:
  `log_meal` mints a fresh uuid, so a re-import after marker loss would merge
  as duplicates on every peer.
* The gate hook is in `on_focus_ready`, not `_cli_gate._should_lock`:
  `gate_is_due()` never reads the food bank, so a refresh there could not
  change the lock decision while adding a third-party round trip to the ~105ms
  `gate --check` fast path.
* `requests` is lazy-imported so the gate's not-due tick does not pay for it.
* Credentials and the cached session cookie live in ~/.config/diet_guard at
  mode 600, outside the synced tree. The credentials file is written by hand,
  never by the package -- the same contract as sync_token.

`_GateDashboard` is merged into `_GateMealFlow`, and both "pull it in from
elsewhere" flows share one `_PullFlows` mixin: pylint's max-parents counts
every MRO entry, so the gate's controller chain had no room for a new class.

Also adds a side-by-side row for the two pull buttons -- stacking them cost
42px and pushed the tab past the viewport at 1366x768.

989 tests, 100% branch coverage, pre-commit clean.
2026-08-22 23:04:22 +02:00
9752142c28 Re-pin crdt-sync to v0.9.0
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
diet-guard does not call sync_log directly, so v0.9.0's bundled signature is
a no-op here; re-pinned to keep every consumer on one tag. 830 tests green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCucBhUkHBBHHbsY7bSdGV
2026-08-21 14:30:13 +02:00
044d7fd9fd Re-pin crdt-sync to v0.8.1
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's tag was already pushed when the timeout-forwarding tests landed, so
the covering tag is v0.8.1. No library behaviour change over v0.8.0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCucBhUkHBBHHbsY7bSdGV
2026-08-21 14:04:54 +02:00
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
6258b35f88 perf(sync): hoist the device listing and stop the curated-bank 404 storm
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
Two independent costs in the background tick, both pure waste.

`list_directory` was called four times per tick -- once by the log pull and
once by each of the three bank syncs. It is the single most expensive call
in a tick at ~445ms mirrored (the GitHub half alone is ~360ms), so that was
~1.3s spent asking the same question four times. It is now listed once in
`run_sync` and passed down.

The curated-bank loop was worse: 17s and 62 requests to fetch *zero* useful
bytes. Firebase returns None for every peer's `food_bank_manual.json`, so
`MirrorSyncClient.get_file_text` treated each miss as "this device has not
migrated yet" and fell through to GitHub, which answers `{}` after ~320ms.
`_primary_only_text` skips that per-peer fallthrough for this one artifact.

Checked before narrowing rather than assumed, because CLAUDE.md requires
both halves of the food bank to sync: reading every peer's curated bank
straight off the mirror found 23 absent, 2 empty, and zero non-empty. No
curated food exists on the mirror alone. The probe is written into the
docstring so it can be re-run before anyone widens this again.

Measured end to end: manual-bank loop 17.0s -> 3.4s, full tick ~27s -> 15.2s,
log/bank/peer state unchanged (441 entries, 117 foods, 22 peers).

`_pull_remote_logs` now returns the revisions it saw instead of mutating a
caller-supplied dict, which keeps it under the argument limit and makes the
data flow visible at the call site.

Deliberately NOT done: revision-skipping the derived food bank. `run_sync`
rebuilds that bank from the merged log immediately before syncing it, so
unlike the log the peer records are not durably held locally -- skipping a
peer would drop its counts from the pushed bank and oscillate under
max-count-wins. Verified empirically: the on-disk bank and a pure log-derived
rebuild are identical (117 foods, 0 differing counts), and the 2 foods peers
know that the local bank lacks are discarded by the existing `if name in
local` filter anyway. The loop is off every interactive path now, so the
remaining cost is background-only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:16:08 +02:00
c7371d7e0d perf(gate): unfreeze "Fetch from sync" and bound the interactive timeout
The button ran a full sync tick inline on the Tk thread, so the fullscreen
lock was dead for its whole duration -- ~18-27s measured against the live
remote, and unbounded in the worst case.

Two changes, and the second is what makes the first cheap:

* the pull moves to a daemon worker thread, with the result marshalled back
  through a queue polled on the Tk thread. The worker touches no widget, by
  construction: Tcl is not thread-safe and that includes `after`. Polling
  also makes the completion path testable with no thread at all.
* the button now runs the *narrow* pull. Its question is identical to the
  gate's -- "did a peer log this slot?" -- and `_reconcile_after_fetch`
  reads only `due_slots()`, so the budget and food banks it used to fetch
  were never consulted here. The full tick still runs after the window
  closes. Measured 84ms against the live remote.

Narrowing also shrinks the write race from tens of seconds to imperceptible:
the pull persists its merge, so a meal logged mid-fetch could be overwritten
by a snapshot taken before it. A second click while a fetch is in flight is
now ignored, which is the reentrancy guard and the race fix in one.

That guard started out as a disabled button, which is how it surfaced a
latent bug worth recording: the fetch button widget is never stored on
`GateWidgets`, so `self._widgets.fetch_button` did not exist and the disable
was a silent no-op -- hidden because the suppression tuple included
`AttributeError`. Coverage would have reported 100% on a guard that did
nothing. Guarding on `_fetch_result` needs no widget at all.

Also adds `INTERACTIVE_TIMEOUT_SECONDS = 2.0` for the paths a user waits on.
`SYNC_TIMEOUT_SECONDS` only ever reached GitHub: crdt_sync v0.6.0's
`firebase_client_for` takes no timeout, so Firebase used its 15s default and
one hung session refresh stalled the lock window -- the journal has five such
refresh failures in five days. Verified to fail closed to the local decision.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 13:07:37 +02:00
0173f4c56c Queue behind stronger lockers; bump gatelock to v0.7.1
Diet_guard was one of the two lockers missing gatelock's
wait_for_turn fix -- confirmed live on 2026-08-21, it held the global
grab for ~3 minutes against a newly-arriving, higher-ranked
screen_locker, which just retried and logged instead of making
progress. Now queues behind any stronger claim before arming.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018M5gKyYzxWG6QkCaj1wWfk
2026-08-21 13:06:19 +02:00
b53ac92c59 perf(gate): narrow the pre-lock pull and defer the heavy imports
The gate's pre-lock refresh ran a *full* sync tick -- peer logs, budget,
both food banks, a rebuild and a push -- in front of the fullscreen lock.
Measured against the live remote: ~18-27s, of which the curated-bank loop
alone was 17s spent fetching nothing (absent on Firebase for every peer, so
each of ~21 peers fell through to a GitHub round trip returning `{}`).

It was also failing: five `sync unavailable (network error trying to refresh
the session)` entries in the last five days, one of them a meal that logged
locally but never published.

The gate has one question -- "has a peer already logged this slot?" -- and
only the peer logs can answer it. `_sync_refresh` does that and nothing
else: one bulk revision-map read, a fetch of only the peers whose revision
moved, merge, re-sign, write. No budget, no banks, no push. The full tick
still runs, after the window closes, so nothing is permanently skipped --
the exhaustive pass just moves off the path the user waits on.

Three state invariants have their own regression tests, because each is
silent when broken: `pushed_rev` survives verbatim (this pass never pushes,
and overwriting it would make the device stop publishing forever),
`peer_revs` is merged rather than replaced (only changed peers are visited),
and the log is written before the state.

Separately, `gate --check` was importing an HTTP stack and a GUI it never
uses. `requests` (~78ms) arrived via `_cli_sync` -> `crdt_sync` and via
`_resolve` -> `_estimator_off`; both are now resolved through module-level
`__getattr__` (PEP 562) and `import_module`, which keeps every existing
`patch.object` target and needs no lint suppression.

Measured: `gate --check` 216ms -> ~110ms; narrow pull 92ms against the live
remote. Accepted trade, documented in `_sync_refresh`: a budget edited on
the phone is not visible in the lock dashboard until the post-window tick.
It cannot affect the lock decision, which is why it is safe to defer.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJ5YnA3CERitQ57HjMu2Qz
2026-08-21 12:58:44 +02:00
b8b432bee4 Add dopamine-ux session prompt to prompts/
Some checks failed
file-length / file length <= 250 lines (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Copy of the canonical prompt in ~/utils/dopamine-ux/, distributed here so the
repo can be opened and the prompt run directly. Derived from a survey of this
repo plus "The Dopamine Architecture" (london-post.co.uk).

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

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

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

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

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

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

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

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

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

Three structural notes:

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

785 tests, 100% branch coverage.

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

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

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

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

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

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

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

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

Two guards worth naming:

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

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

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

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

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

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

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

609 Dart tests, 761 Python, both suites green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:41:37 +02:00
2bdb7925a8 Read the meal schedule from a forward-only history (Python)
Wires the Python side to the configurable schedule. No edit surface yet, so
nothing writes a schedule and current_schedule() returns the default -- the
derived hours are still 08/12/16/20 and the cutoff is still 22:00. Verified by
running it: before any edit the slots are unchanged, after recording 08-20 x5
they become 08:00, 11:00, 14:00, 17:00, 20:00, and a 2020 day still resolves
to the four-meal schedule.

_slots.py now takes the schedule as a *required* argument rather than reading
module constants. Required, not defaulted, on purpose: a default would let a
call site missed in this refactor keep deriving the old fixed hours on one
device, and a slot one device offers while the other does not is a checkpoint
that can never be satisfied. Making it required let mypy enumerate the nine
call sites instead of trusting a grep.

The history is forward-only and seeds the default at the epoch *before*
recording today's value, so switching to five meals leaves past days judged
against the four-meal schedule they actually ran under. Same shape and same
reasoning as _budget_history.py; it will ride the same CRDT record.

Two details worth naming:

- MEAL_SCHEDULE_FILE lands in DATA_DIR, so conftest's _isolate_state redirect
  is patched in this same commit rather than a later one. Confirmed with a
  canary that the redirect is live and that ~/.local/share/diet_guard/ has no
  .meal_schedule after a full run.
- _mcp_read imports _budget.current_schedule already, so the meal-schedule
  lookup is aliased rather than shadowing it.

_gatelock._pending_slots is spelled `is None` rather than `or` now. The two are
in fact equivalent -- if 0 is a slot it is necessarily the first slot, checked
exhaustively -- but the intent should not rest on that coincidence.

761 tests, 100% branch coverage.

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
2026-08-16 14:18:39 +02:00
cb23f3c09d Fix check_patch_targets' own fail-open: put the repo root on sys.path
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
The pre-commit CI job reported all 19 patch targets stale, including ones no
commit in this sweep touched -- the tell that the checker, not the targets,
was broken.

Running it as `python3 scripts/check_patch_targets.py` puts *scripts/* on
sys.path[0], not the repo root. `diet_guard` is not installed in the runner's
environment (CI installs requirements.txt only), so every `import_module` hit
the resolver's `except ImportError: continue` and every target reported
unresolvable. It passed locally because the dev venv has the package on the
path.

That is precisely the fail-open shape this script exists to prevent, in the
script itself: a green-or-red signal that reflects the environment rather than
the code. Two fixes:

- put the repo root on sys.path explicitly, so the checker resolves the same
  way whatever cwd or interpreter invokes it;
- import the package once up front and fail with a distinct message if that
  fails, so "the package will not import" can never again masquerade as
  "every patch target moved".

Reproduced in a clean venv built from requirements.txt: 19 stale before, exit 0
after, and still exactly 1 stale when a target is genuinely broken
(verified by renaming FOOD_LOG_FILE's target).

Verified: 708 Python tests / 100% branch coverage, pre-commit clean, checker
exit 0 under both the dev venv and the clean venv.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 21:27:24 +02:00
5125a98980 Register the _hmac_key fixture; guard the redirect so it fails locally
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
CI's Tests job went red on six signing assertions that pass on this machine.
Root cause predates this sweep: commit 1e201acbdc moved `_hmac_key` out of
conftest into `_gate_fixtures` and added it to neither conftest's import list
nor its `__all__`. A fixture only registers if conftest imports it, and ruff
deletes an import nothing references -- which is exactly what the `__all__`
below it exists to prevent for every other autouse fixture.

So the fixture never ran, and this machine's real
`/etc/workout-locker/hmac.key` silently stood in for the temp key. Locally the
suite passed; on a keyless runner `compute_entry_hmac` returned None and every
"entry carries a signature" assertion failed.

Proven causal rather than assumed: with `/etc/workout-locker` masked by a
tmpfs in a user namespace, HEAD fails 6 / passes 32 -- the same six CI named --
and with the fixture registered, 38 pass.

`test_hmac_key_is_redirected_off_the_machine_key` now asserts the redirect
directly, so an unregistered fixture is a local failure instead of a push-time
one. Verified it fails closed by removing the import again.

Verified: 708 Python tests / 100% branch coverage, and the same two files pass
under a masked /etc/workout-locker.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 21:19:35 +02:00
499882b1de Sort plugin_platform_interface into dev_dependencies alphabetically
Caught by the pre-push CI mirror, which runs `flutter analyze` over the whole
project; the per-batch `flutter analyze lib/ test/` used during the sweep does
not cover pubspec.yaml, so `sort_pub_dependencies` never fired there.

The entry was appended after a blank line by `flutter pub` during the mirror's
own clean-venv resolve, landing out of order and outside the dev_dependencies
block it belongs to.

Verified: flutter analyze (whole project) clean, flutter test 555.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 21:13:30 +02:00
c77e7d9acf Split the last four Dart lib files; file-length gate now reports zero
Final batch of the 250-line sweep. `check_file_length.sh --all` exits 0: every
file in the repo is at or under 250 lines.

  github_mirror_screen.dart  391 -> 205  (+ actions, client_id_dialog parts)
  foodbank_service.dart      314 -> 209  (+ foodbank_service_manual part)
  settings_screen.dart       286 -> 237  (+ settings_kcal_goal part)
  firebase_backend.dart      282 -> 100  (+ firebase_client.dart)

Three of the four are `part` files rather than separate libraries, and that is
forced rather than stylistic: the moved code drives private state
(`_busy`, `_status`, the text controllers) and calls private helpers
(`_readBank`, `_normalize`), none of which are visible across a library
boundary in Dart. Widening them to public just to split a file would leak
internals the rest of the app has no business calling.

Within those parts, mixins rather than extensions, for a concrete reason: an
extension is not a subclass of `State`, so calling `setState` from one is an
`invalid_use_of_protected_member`. Fields the State must own (the controllers
it creates and disposes) stay declared there and are reached through abstract
getters.

`firebase_client.dart` is a real library split -- opening an authenticated
client has no private coupling to the keystore-backed account record, only to
its public API. The one exception, dropping the account marker without setting
the opt-out flag, became `forgetAccountMarker()` rather than exposing the
secure store.

Verified: flutter test 555 (unchanged), flutter analyze clean, 707 Python
tests / 100% branch coverage, check_patch_targets 0, pre-commit clean,
check_file_length.sh --all exit 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 21:07:24 +02:00
3c67cf8c9c Split log_meal_screen into mixins and widget helpers
Twelfth batch of the 250-line sweep (over-cap count 5 -> 4).

  log_meal_screen.dart  431 -> 250

Widget/behaviour extraction only, no route changes: the four app-bar buttons
push exactly the MaterialPageRoutes they did before.

  log_meal_sync_mixin.dart  background sync + app lifecycle observation
  log_meal_nav_mixin.dart   the four app-bar destinations
  log_meal_actions.dart     the app-bar IconButton list
  log_meal_progress.dart    buildTodayProgress + parseMacroField (both pure)

The sync and nav halves are mixins rather than helper classes because the
behaviour is inseparable from the State it drives -- it observes the widget
lifecycle, calls setState, and reads `mounted`. The screen's fields stay
declared on the State; `syncHttpClient` is an abstract getter because `widget`
is typed `T` inside a mixin, so `widget.httpClient` does not resolve there.

Names crossing the new file boundaries became public with doc comments, as
`public_member_api_docs` requires. The macro-filling block moved onto
`MacroControllers.fillFrom`, next to the existing `clear()`, which is where it
belonged anyway.

Verified: flutter test 555 (unchanged), flutter analyze clean, pre-commit
clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:59:48 +02:00
c0ed6154ac Split the remaining seven Dart test files
Eleventh batch of the 250-line sweep (over-cap count 12 -> 5). Every test file
in the repo, Python and Dart, is now under cap; the five left are all in
app/lib/.

  wrapper_server_test.dart        349 -> 145  (+ proxy, account siblings)
  app_settings_service_test.dart  321 -> 162  (+ sync sibling)
  average_service_test.dart       299 -> 158  (+ periods sibling)
  settings_screen_test.dart       274 -> 189  (+ battery sibling)
  day_status_service_test.dart    270 -> 161  (+ streaks sibling)
  edit_entry_screen_test.dart     269 -> 159  (+ foodbank sibling)
  day_status_calendar_test.dart   256 -> 237  (+ _test_support sibling)

day_status_calendar_test is a single group whose tests close over group-local
state, so it could not be split by block. Its ~25 lines of file-level fixtures
moved to `day_status_calendar_test_support.dart` instead, which required the
same publicisation as the sync support file (`_theme` -> `appTheme`, `_wrap` ->
`wrapInApp`, `_colorOfDay` -> `colorOfDay`) with doc comments.

Block counts were compared against HEAD per family rather than trusting the
suite total, since the duplication bug in the previous batch passed green at an
inflated count. All seven families match exactly (29/26/34/11/34/8/14).

Verified: flutter test 555 (unchanged), flutter analyze clean, pre-commit
clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:53:55 +02:00
cc78dd383b Split six Dart test files; share the sync fixtures via a support sibling
Tenth batch of the 250-line sweep (over-cap count 18 -> 12; all Python is
already clear, so the remainder is Dart).

  sync_merge_test.dart            694 -> 232  (+ 4 siblings)
  github_mirror_screen_test.dart  512 -> 250  (+ 3 siblings)
  foodbank_service_test.dart      395 -> 190  (+ manual sibling)
  sync_service_test.dart          394 -> 203  (+ budget sibling + support)
  log_storage_service_test.dart   385 -> 182  (+ edit sibling)
  log_meal_screen_test.dart       362 -> 243  (+ nav sibling)

sync_service_test's ~100-line fixture block is shared through
`sync_service_test_support.dart` rather than duplicated: copying it would have
put both siblings back over the cap on their own. The helpers had to become
public (`_FakeGitHub` -> `FakeGitHub`, `_manual` -> `manualNutrition`,
`_remoteBudgetJson` -> `remoteBudgetJson`) with doc comments, since a leading
underscore is library-private in Dart and the siblings could not otherwise see
them.

The block-boundary matcher earned two fixes, both caught by comparing block
counts against HEAD rather than by the suite:

- A test name wrapped onto its own line (dart format does this past 80 cols)
  was invisible to a same-line-only pattern, so the neighbouring span sliced
  through it -- the file stopped compiling. Spans now end at the matching
  close paren of the call, not at a guess past the closure brace.
- A double-quoted name containing an apostrophe ("skips its own device id
  ('phone')") was excluded by a character class that banned both quote
  characters. That block fell into the shared prologue and was duplicated into
  every output: the suite went GREEN at 559 tests instead of 555. Reverted and
  redone; text between two blocks is now treated as a shared helper.

Verified: flutter test 555 (unchanged, and each split family's block count
matches HEAD exactly), flutter analyze clean, pre-commit clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:49:54 +02:00
3e51e614b1 Split the last seven Python files; extend the redirect guard to all five paths
Ninth batch of the 250-line sweep. Every Python file in the repo is now under
cap (over-cap count 25 -> 18; the 18 remaining are all Dart).

  _foodbank.py             365 -> 210  (+ _foodbank_search, _foodbank_rebuild)
  test_averages.py         351 -> 222  (+ test_averages_report.py)
  _estimator.py            325 -> 137  (+ _estimator_off.py)
  _budget.py               323 -> 227  (+ _budget_biometrics, _budget_derived)
  test_foodbank.py         311 -> 117  (+ test_foodbank_rebuild.py)
  _averages.py             298 -> 174  (+ _averages_periods, _averages_report)
  test_budget_history.py   288 -> 162  (+ test_budget_history_io.py)

The split boundaries are constrained by which module owns each conftest-patched
state path, not by line count. BUDGET_FILE stays in _budget, FOOD_BANK_FILE in
_foodbank: the derived/search/rebuild halves reach the file only through their
parent's private helpers. Two of the new modules had copied FOOD_BANK_FILE into
their headers as an incidental import, which is exactly the leak the guard is
for -- both cleaned.

test_state_redirect.py now covers all five redirected paths (FOOD_LOG_FILE,
BUDGET_FILE, BUDGET_HISTORY_FILE, FOOD_BANK_FILE, MANUAL_BANK_FILE) rather
than just the food log, in both directions: only the owning module may name
each constant, and each redirect demonstrably moves a real write off the live
path.

Two rewires fail-closed rather than silently: `_budget.budget_weight` and
`_estimator.requests` were module-attribute references no import rewrite
touches, and both raised AttributeError immediately. The latter appeared only
after ruff removed the now-unused `requests` import from _estimator -- the
import was load-bearing solely as a patch target.

Verified: 707 Python tests / 100% branch coverage, 5 layout-fits tests under
xvfb, check_patch_targets 0, pre-commit clean, ~/.local/share/diet_guard
byte-identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:37:05 +02:00
df5e1272f1 Make _FakeTclError subclass the real tkinter.TclError
Found while auditing the `_NO_WIDGETS` exemption added two commits ago: the
comment claimed `_gatelock_widgetgroups` binds real `tk` only for its
`contextlib.suppress(tk.TclError)` dead-copy guards. That part is true -- it
constructs no widgets -- but the consequence was wrong.

`_FakeTclError` subclassed `Exception`, not `tkinter.TclError`, so a fake-tk
gate test raising it sailed straight through those suppressions. The
"a monitor vanished mid-update" paths were therefore only ever exercised
against the real error; with the fake they would have raised through the gate.
Reproduced directly before fixing: a `_FAKE_TK.TclError` escaped
`WidgetGroup.config` both with and without the module patched, so adding the
module to the patch set would not have fixed it.

`tkinter.TclError` subclasses `Exception`, so inheriting keeps every existing
`except _FakeTclError` working and makes both spellings catchable.
`test_fake_tclerror_is_catchable_as_the_real_one` pins it and asserts the live
copy still gets configured; reverting the base class fails it.

Verified: 707 Python tests / 100% branch coverage, pre-commit clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:24:11 +02:00
af461d3157 Split _state.py and _tk_fakes.py; make the food-log redirect fail closed
Eighth batch of the 250-line sweep (over-cap count 28 -> 25).

  _state.py       366 -> 197  (+ _state_today.py, _state_sync.py)
  test_state.py   400 -> 221  (+ test_state_today.py, test_state_sync.py)
  _tk_fakes.py    368 -> 167  (+ _tk_fakes_containers.py, _tk_fakes_canvas.py)

_state.py is the file conftest patches FOOD_LOG_FILE on, so the split is
constrained rather than free: `FOOD_LOG_FILE` and the two functions that open
it stay put, and the derived read model (_state_today) and the sync/undo
helpers (_state_sync) reach the file only through _state's private
_read_raw_log/_write_log. Callers were rewired to import from the new modules
directly rather than via a circular re-export.

That constraint is now enforced instead of merely documented. Moving a reader
of FOOD_LOG_FILE into a sibling would leave conftest's patch pointing at a
name nothing reads: check_patch_targets.py still exits 0 (the path resolves)
and the runtime is unchanged (a file write, not a network call), so the suite
would go green while writing to the real ~/.local/share/diet_guard and the
next sync tick would publish it. test_state_redirect.py asserts both halves --
only _constants and _state may name the constant, and the redirect
demonstrably moves a real write off the live path. Verified it fails closed by
adding a FOOD_LOG_FILE reader to _state_today: it named that module exactly.

_tk_fakes.py keeps _FAKE_TK/_FAKE_TTK and gains an explicit __all__, since the
re-exports are load-bearing and ruff would otherwise strip them as unused. The
identity canary from the previous commit covers the split: breaking one entry
in the assembly (Canvas=object) fails 8 gate tests loudly rather than silently
building real widgets.

Verified: 706 Python tests / 100% branch coverage, check_patch_targets 0,
pre-commit clean, ~/.local/share/diet_guard byte-identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:21:26 +02:00
8f2d1011c7 Split the three gate test files; assert fake_tk really swaps tkinter
Seventh batch of the 250-line sweep (over-cap count 31 -> 28). The test files
mirror the source split from the previous commit one-for-one:

  test_gatelock_mealflow.py  379 -> 227  (+ test_gatelock_dashboard.py)
  test_gatelock_fanout.py    335 -> 128  (+ test_gatelock_groups.py)
  test_gatelock.py           331 -> 224  (+ test_gatelock_form.py)

`test_gatelock_dashboard.py` follows `_gatelock_dashboard`/the slot walk and
manual sync; `test_gatelock_groups.py` takes the group primitives that
`_gatelock_widgetgroups` now owns; `test_gatelock_form.py` takes the form and
basis/amount cases.

Also closes the remaining half of the fake-tk fail-open. The previous commit's
canary proved every widget-building module is *named* in `_GATE_TK_MODULES`;
it could not prove the patch installs something that is not real tkinter. If
`_FAKE_TK` were imported from the wrong place after the coming `_tk_fakes.py`
split, every module would still be "patched" and the suite would still pass
while building real widgets. `test_fake_tk_actually_replaces_real_tkinter`
now asserts `module.tk is _FAKE_TK` for every entry *inside* the `fake_tk()`
context, plus both `ttk` fakes and restoration afterwards. Verified it fails
closed by making one module skip the patch: it reported exactly that module.

Verified: 704 Python tests / 100% branch coverage, check_patch_targets 0,
pre-commit clean, ~/.local/share/diet_guard byte-identical (gate timer paused
for the batch).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:12:13 +02:00
e8f0ecaae1 Split the six Python gate files; guard the fake-tk patch set
Sixth batch of the 250-line sweep. All six gate sources named for this batch
are now under cap, plus _gate_layout_probe.py, which this batch's import
rewiring pulled into the changeset (over-cap count 38 -> 31).

  _gatelock_ui.py       477 -> 174  (palette/leaf-helper hub)
  _gate_layout_probe.py 346 -> 196
  _gatelock_groups.py   308 -> 137
  _gatelock_calendar_ui 295 ->  77
  _gatelock_calendar.py 286 -> 210
  _gatelock.py          263 -> 238
  _gatelock_mealflow.py 259 -> 207

New siblings: _gatelock_fields (input widgets), _gatelock_layout (assembly),
_gatelock_widgetgroups (per-widget mirroring), _gatelock_calendar_types
(bundles/palette), _gatelock_calendar_widgets (History builders),
_gatelock_dashboard and _gatelock_budgetedit (mixins), _gatelock_lockfile
(the stdlib-only flock), _gate_focus_probe and _gate_measurement.

The load-bearing part is the test seam, not the line counts.
`_gate_fixtures._GATE_TK_MODULES` patches `tk` on a hand-listed tuple, and
that list fails OPEN: a widget builder split into a new sibling that nobody
adds to it builds *real* Tk widgets against fake parents. Neither existing
detector sees that -- check_patch_targets.py only validates paths that still
resolve, and the ~8s runtime only catches network calls. It bit twice during
this split (real StringVars from make_calendar_vars returned MagicMocks
instead of the asserted text), so test_gate_tk_modules.py now asserts the
invariant directly: every module binding `tk` is in the patch set or named in
_NO_WIDGETS with a reason. It caught a pre-existing gap too --
_gatelock_support was never in the set.

Same fail-open shape drove two other choices: `escape_tab_trap` is a call-time
indirection so the keyboard test's patch of `_escape_text_tab_trap` still
bites, and the flock pair moved with its conftest patch target updated in the
same edit (that one fails closed). build_layout is imported from
_gatelock_layout directly rather than re-exported lazily, which avoids both a
cycle and an import-outside-toplevel suppression.

Verified: 703 Python tests / 100% branch coverage, the 5 layout-fits tests
under xvfb, 555 Flutter tests (unchanged), flutter analyze clean,
check_patch_targets 0, `sync` 0 (403 entries), pre-commit clean, and
`gate --demo` renders both tabs with live dashboard data.
~/.local/share/diet_guard byte-identical across the batch (gate timer paused,
restored after).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:08:03 +02:00
7cb09a5b85 Split food_bank_screen; share the filter widgets with history
food_bank_screen.dart (712) carried a near-clone of the filter sheet batch 2
had just factored out of history: the same name-search field, the same slider
captions, and four more copies of the same min/max macro range block. Splitting
it in isolation would have baked that duplication in permanently, so the shared
widgets moved to a neutral `lib/widgets/filters/` first and both screens now
import them.

  food_bank_screen.dart      712 -> 238
  lib/widgets/food_bank/
    fb_filter.dart            156  FbFilter, FbSortField, applyFbFilter
    fb_filter_sheet.dart      244  the sheet itself
    fb_add_entry_dialog.dart  103  the manual-entry dialog
  lib/widgets/history/history_filter_fields.dart
                        -> lib/widgets/filters/filter_fields.dart

FilterRangeRow gained `showEndpointLabels`, defaulting to true. History showed
endpoint captions and a selected-range readout; the food-bank sheet never did,
and switching them on there would have been a UI change smuggled in under a
refactor. The food-bank call sites pass false, so both screens render exactly
what they rendered before.

FbSortField and HistorySortField stay separate on purpose -- they are not the
same enum (`name` vs `date`/`description`), so the sort dropdown is not shared.

The test file mirrors the source split, three files under test/screens/
food_bank/ plus fb_test_support.dart for the setUp/tearDown/settle prologue,
same shape as batch 2's history_test_support.dart.

Verified: 555 flutter tests (unchanged count -- no test lost, and food bank's
own RangeSlider/sort-toggle tests still pass against the shared widget),
flutter analyze clean over lib/ and test/, live ~/.local/share/diet_guard
byte-identical. Over-cap files: 40 -> 38.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 19:43:08 +02:00
895a87cf86 Split history_screen and its test into widget siblings
history_screen.dart (1052) and history_screen_test.dart (1017) were a third of
the remaining over-cap work. Widget extraction only -- no route changes, since
routes are user-visible and repo_invariants_test.dart pins the navigation
surface.

  history_screen.dart          1052 -> 211
  lib/widgets/history/
    history_filter.dart         102  filter criteria + sort enum (pure data)
    history_grouping.dart       206  HistoryItem tree, apply/group/format
    history_list.dart           194  GroupedList, DayHeaderTile, EntryTile
    history_filter_sheet.dart   242  the sheet itself
    history_filter_fields.dart  168  search field, slider labels, range row
    history_filter_sort.dart    140  source chips + sort controls

Names that now cross a file boundary became public (HistoryItem, DayHeader,
EntryRow, buildGroupedItems, formatDay, dateRangeLabel, the tile widgets), each
with the doc comment public_member_api_docs requires -- 49 of them, written
rather than suppressed.

The four macro range sliders (kcal/protein/carbs/fat) were four near-identical
30-line blocks differing only in label, key, unit and which HistoryFilter pair
they read/write. They are now one FilterRangeRow taking min/max plus an
onChanged, which is most of how the sheet got under the cap.

The test file mirrors the source split one-for-one, six files under
test/screens/history/. Its setUp/tearDown and the settle() helper (needed by
every part, because HistoryScreen loads via an untracked initState future) moved
to history_test_support.dart rather than being copy-pasted six times.

Verified: 555 flutter tests (same count as before -- no test lost in the split),
flutter analyze clean over all of lib/ and test/, 701 python tests at 100%
branch coverage, `python -m diet_guard sync` -> 402 entries/exit 0, live
~/.local/share/diet_guard byte-identical. Over-cap files: 42 -> 40.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 19:35:19 +02:00
38d66a8492 Make PC sync event-driven; retire the 15-min timer
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
2026-08-15 19:21:30 +02:00
1e201acbdc Split _sync.py and its tests; extract the gate fixtures from conftest
_sync.py 498 -> 165, into siblings that each own one concern:

  _sync_client.py  picking a backend and building the remote store
  _sync_banks.py   pull/merge/push for the food bank and the budget
  _sync_paths.py   the kuhyx/syncs wire layout, shared by both
  _sync_errors.py  SyncError, so _sync and _sync_client need not import
                   each other

The patch targets moved with the code they guard, which is the whole risk of
this commit. unittest.mock.patch and monkeypatch.setattr both bind to a
*module object*, so a patch left pointing at _sync after CONFIG_FILE and
SYNC_TOKEN_FILE moved to _sync_client redirects nothing. That is not
hypothetical here: the first run of the suite took 9m18s instead of 7s and
raised 401s, because tests were reaching the real GitHub API with a fake
token. Repointed:

  conftest       SYNC_TOKEN_FILE, CONFIG_FILE      -> _sync_client
  test_sync*     GitHubSyncClient (30 patch sites) -> _sync_client
  test_backend   mirror/firebase_client_for        -> _sync_client

The repo's own _test_guard caught the same leak independently, which is the
behaviour worth keeping: two guards, both fail-closed.

test_sync.py 482 -> 205, splitting the budget and pull/revision classes into
siblings and the shared fakes into _sync_fakes.py.

conftest.py 284 -> 155, moving the Tk/gatelock fixtures to _gate_fixtures.py.
Importing them back is what registers them (pytest_plugins is an error in a
non-root conftest), and they are named in __all__ because ruff's autofix
otherwise deletes the "unused" import and silently disables Tk blocking --
it did exactly that once here. Verified afterwards with a canary asserting
_gatelock.tk is still a MagicMock, not merely that the suite passes.

Verified: 692 tests / 100% coverage unchanged; ~/.local/share/diet_guard
byte-identical before and after the run; cd /tmp && python3 -m diet_guard sync
-> 402 entries, exit 0. Gate 47 -> 44.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK3HCZrM75sRHL1gL8usve
2026-08-15 18:51:18 +02:00
fef140d970 Split wrapper_server and sync_merge into siblings
Two Dart files whose contents were already cleanly separable.

wrapper_server.dart (254 -> 228): contentTypeFor is a pure function of the
path with no server state, so it moves to content_types.dart as a plain
library. WrapperServer.contentTypeFor stays as a static forwarder because the
test reaches for it by that name.

sync_merge.dart (475 -> 190): three near-independent blocks -- daylog, banks,
budget -- split along the seams the tests already use. The banks and budget
adapters move to siblings and are re-exported, so sync_service.dart and both
test files import exactly what they did before and needed no edits.

Flutter 555 tests unchanged; analyze clean; gate 52 -> 49.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK3HCZrM75sRHL1gL8usve
2026-08-15 16:42:27 +02:00
17a2c62f26 Automate CLAUDE.md's structural rules, then cut it to 189 lines
CLAUDE.md was 1101 lines and loaded into every session in this repo. Three
passes, in order: automate what a gate can check, rewrite what is left as
instructions rather than rationale, extract what still does not fit.

Automated. Five prohibitions were enforced by nothing but a paragraph asking a
future reader not to do something; they are now repo_invariants_test.dart:

  - no app/linux/ (a GTK embedder target manages ~20fps at 4K)
  - dart:io only in *_io.dart seams and lib/desktop/ -- this one is why the
    test exists at all, since dart:io does not fail a web *compile*. It throws
    at runtime, so a bad import is a blank white window that the widget tests
    happily pass through.
  - no meal builder / repeat-last-meal / reward prompt
  - no image_picker, no CAMERA permission
  - wrapper port 8732 and the diet-guard-desktop Chrome profile, both pinned
    because IndexedDB is keyed by origin and moving either hides the whole
    local food log

Each guard was canary-tested by breaking the invariant and confirming the
suite goes red -- a guard that cannot fail is decoration.

Rules whose behaviour was already covered (budget epoch seeding, sync merge,
food bank) shrink to a pointer at the test that owns them.

Where a rule's entire value was its rationale ("the removal is the feature"),
the why moved into the name and reason string of the gate that now enforces
it, so it lives somewhere executable instead of somewhere quotable.

Extracted. The vendored flutter/flutter rules were 789 of the 1101 lines --
72% of the file, none of it about this repo. Split into five docs/ topic files
under the cap and linked. Verified content-complete: 664 non-blank lines in,
664 out, zero missing.

Python 692 tests / 100% coverage unchanged; Flutter 548 -> 555 (+7 new).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK3HCZrM75sRHL1gL8usve
2026-08-15 16:39:57 +02:00
c7538f691b Enforce the shared 250-line file cap
Replace this repo's stale file-length hook with the shared gate every other
repo will use. The old hook capped at 500 lines, called a repo-local
scripts/check_file_length.py, and filtered to types_or: [python, shell] --
so it never looked at the Flutter app in app/ or at any prose. Two caps that
disagree is worse than one, so the old one is deleted rather than kept.

The new hook checks only the files in the commit and exits 1; CI runs --all
as the backstop, since a fresh clone that never ran `pre-commit install` has
no hooks at all. The exemption list lives with the checker in
~/utils/file_length/config.py so the gate and the cross-repo survey cannot
disagree about what "too long" means.

Two things this repo has that ~/todo (the reference implementation) did not:

- A pre-commit CI job running --all-files, where $HOME/utils does not exist.
  The shared gate is checked out to .utils and reached via UTILS_ROOT, or the
  hook fails on a missing checker rather than on anything in this repo.

- Tests that isolate live user state with dotted-string patches
  (`patch("diet_guard._state.FOOD_LOG_FILE", ...)`). unittest.mock.patch fails
  OPEN: once a refactor moves a name, the old path still imports, the patch
  redirects nothing, the test still passes -- and the suite writes to the real
  ~/.local/share/diet_guard, which diet-guard-sync.timer publishes within 15
  minutes. check_patch_targets.py resolves all 30 patch targets statically so
  that failure is loud instead of silent. It is landed before any split for
  exactly that reason.

The gate is red at 52 files; the splits that follow drive it to zero.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK3HCZrM75sRHL1gL8usve
2026-08-15 16:35:01 +02:00
7a491d9d91 app: use the shared github_device_auth package
Some checks are pending
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
The inline `_DeviceCodeDialog` in `github_mirror_screen.dart` (88 lines)
was byte-for-byte identical to wake-alarm's, and
`services/github_device_auth.dart` was a fourth copy of the auth client.
Both now come from `github_device_auth` in the kuhyx/utils monorepo.

This app's copy was the one that mattered most to get right: it took the
device-code and token URLs as parameters because GitHub's device-flow
endpoints send no CORS headers, so the desktop **web** build has to route
both through the local wrapper (`github_client_factory_web.dart` passes
them). Extracting todo's simpler hardcoded version would have broken that
build outright. The package carries the configurable endpoints instead,
defaulting to GitHub's own URLs so the other three consumers are
unaffected -- and `flutter build web` here is verified green, which is the
check that would have caught it.

The dialog also gains a real fix: `on Object` rather than `on Exception`,
so an `ArgumentError` shows an error instead of leaving the dialog
spinning on "Waiting for authorization…" forever.

The unused `token_vault` import in the deleted client confirmed it had no
app-specific behaviour left worth keeping. 548 tests pass, analyze clean,
web build green, and the release APK is installed on the phone with meal
history intact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U4Rj3s7K2qzrLNgJqqPhno
2026-08-15 16:15:24 +02:00
b621ccaed0 Use gatelock's shared button and WidgetGroup
Some checks are pending
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
Phase 2 consumer migration. diet-guard was the donor for make_button, so it
is one of the two proof consumers the extraction is validated against.

- _gatelock_buttons.py is deleted; its make_button now lives in gatelock,
  where the variant API (text colour picked *from* the fill) and the
  <Return>/<KP_Enter> bindings serve all four gates instead of one. Call
  sites pass _COLORS explicitly, since a shared widget cannot read this
  app's module-level palette. Pixel-identical: BODY/LABEL were -16/-14 and
  LockConfig.font("body"/"label") yields the same negative (pixel) sizes.
- WidgetGroup now subclasses gatelock's, keeping the list[_W] constructor and
  re-narrowing `first` to the widget type. The specialized groups (EntryGroup
  over a shared StringVar, TextGroup, ListboxGroup, MacroGroup) are unchanged
  behaviour and stay -- gatelock has no equivalent for them.
- bind() keeps *replacing* semantics, inverted from gatelock's additive
  default and now documented + tested. _wire_events runs once per
  build_surface and again on rebuild, so an additive bind would stack a
  second <Return> handler on every surviving widget and log the meal twice.
- conftest swaps gatelock.widgets into the fake-tk module list in the same
  edit that removes _gatelock_buttons, since that list fails the whole suite
  if it drifts in either direction.

All three gatelock pins move together to v0.5.0 -- pyproject, requirements.txt
and the pylint hook's additional_dependencies. The config comment already
warned that a lagging hook pin lints against a gatelock without the API the
code calls; that is exactly what it did before this bump.

The "<Return> activates a button" test moves to gatelock with the button, so
it runs against real Tk rather than a fake widget that can only report the
binding it was handed.

Verified: 692 tests, 100% branch coverage against the *installed* gatelock
0.5.0 (not a PYTHONPATH shim); the gate builds under xvfb and <Return> and
<KP_Enter> both fire a real button's command, with the accent focus ring
(#B8862E, 2px) instead of Tk's invisible 1px black.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U4Rj3s7K2qzrLNgJqqPhno
2026-08-15 14:23:11 +02:00
372e8a19f6 Remove the Snack chip from the phone's slot selector
Some checks are pending
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
The chip was the only control that logged a meal against no slot at all
(`slot: null`). Removing it leaves the row with just the four hour chips,
so every logged meal now satisfies a real slot.

Storage keeps its null-slot support on purpose. Entries already on disk
and arriving over sync carry no `slot` key, and the `slot != null` filters
in log_storage_service.loggedSlotsToday / _state.logged_slots_today are
what stop them from retroactively satisfying meal slots -- so both are
documented as load-bearing rather than deleted as dead code.

Also corrects the MCP tool's docstring, which claimed its slot argument
"may be None early in the day"; it falls back to slot_for_log, which
clamps to a real hour and never returns None.

Adds the widget test the chip row never had -- being untested is why the
chip read as unused.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPheLM86xUN9TGf34Ygtfz
2026-08-14 22:31:09 +02:00
4e3778823f Drop five redundant unawaited() wrappers around Navigator.push
Some checks are pending
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
Navigator.push is annotated @awaitNotRequired, so these now trip
unnecessary_unawaited and failed the CI-mirror's flutter analyze -- which
blocked every push to this repo regardless of what the commit changed.

flutter analyze: no issues. flutter test: 553 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 16:17:18 +02:00
e80ae41e1c Persist the CI-mirror's analyzer excludes and dependency upgrades
The ci-mirror hook regenerates these on every run and then leaves them
dirty. Pre-commit stashes the dirty tree, the hook rewrites the same files,
and restoring the stash conflicts -- which rolled back the fixes and failed
every push regardless of whether the checks themselves passed.

Committing the hook's own output makes the tree clean, so there is nothing
to stash and the collision cannot recur.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 16:13:46 +02:00
b5704b2228 Update refactor_claude_todo.md counts after gate exemption fixes
Git-ignored files, vendored agent-skill bundles and the CI checkout dir are
now exempt, since no commit could ever fix them. Repo counts and the ranked
violation lists are regenerated accordingly; the global baseline drops from
657 to 597.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 16:03:01 +02:00
a573cc11e0 Add refactor_claude_todo.md: 250-line file-length cap
Some checks are pending
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
A ready-to-use prompt describing the goal (every file at most 250 lines,
code and prose alike), this repo's actual violations ranked by Fowler ROI
(lines x commits/yr), how to split each kind, and the requirement to wire in
the shared pre-commit gate so files stay small permanently.

Generated from a measured survey of every repo; the gate itself lives in
~/utils (file_length/ + scripts/check_file_length.sh).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C7yZz45ezmzCB89Cv5gAtZ
2026-08-14 14:25:43 +02:00
45471546f7 Migrate Sync settings to the shared sync_settings_ui package
Some checks are pending
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
Splits the settings screen: Nutrition (daily kcal goal) and Notifications
(battery exemption) stay in place, Firebase+GitHub content is replaced by
a Sync settings link using the shared sync_settings_ui package. GitHub
stays app-local as its own GitHubMirrorScreen (device-flow connect,
_ClientIdSetupDialog, the wrapperManagedToken desktop-wrapper path) since
connecting it also triggers a real cross-device sync via runSync(), not
just a settings save.

BackupSlot left null: diet-guard has no local export/import feature.

553/553 tests passing, 100% coverage on settings_screen.dart, flutter
analyze clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-14 11:47:43 +02:00
546041584f Add Google sign-in support for the Firebase sync account
Some checks failed
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
One-tap sign-in for a fresh install, matching the pattern already shipped
in todo and crdt_sync_dart: openFirebaseWithGoogle() (google_platform.dart
abstracts the plugin's platform-channel dependence), isFirebaseConfigured()
that reads the stored session rather than trusting the account marker
alone (a marker with no live session is what made a synced phone read as
"not connected" for a full session), and storedAccount() for read-back
without the desktop-wrapper fallback that throws on Android.

Also generalizes crdt_sync_dart's ref pin to v0.10.0 and vendors the
override-guard script for the pre-commit hook already wired to it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-12 23:36:10 +02:00
458f10515b Make the phone publish on every tick, and fail closed on Firebase errors
Some checks failed
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Meals logged on the phone stopped reaching the PC, so the gate kept locking
for slots that were already logged and the only way through was to spam
"nothing". The PC's fetch was never broken: it was faithfully pulling a
Firebase that did not contain the phone's meals.

The phone had no working publish backstop on either transport:

- `checkAndNotify` gated its sync on `due.isNotEmpty`. Logging every meal
  promptly means nothing is ever due, so the ~15-min periodic task never
  published. It was a notification job that happened to sync, not a sync
  timer. It now syncs on every tick it is asked to, then computes due slots
  from the merged result, so a meal pulled from another device suppresses a
  nag instead of triggering one.
- `backgroundSyncPush` never called `initSyncDeviceId()`. A fresh isolate has
  its own static state, so `currentSyncDeviceId` fell back to the compile-time
  'phone' constant and published to `devices/phone/` rather than the persisted
  uuid -- which then makes the next foreground push see `unchanged` and skip
  writing the uuid directory entirely.

Separately, on the "Fetch from sync" path itself: `FirebaseSyncError` and
`FirebaseAuthError` are siblings of `GitHubSyncError` under `RemoteSyncError`,
not subclasses, so every per-request failure of the *primary* backend escaped
`pull_shared_log`'s catch tuple and raised a traceback out of a helper
documented to fail closed with a reason string. `ConfigError` needed the same
treatment by a different route: it subclasses `Exception` directly, so it is
outside `RemoteSyncError` too, and is now translated at `_client_for_run`.

The PAT is no longer mandatory either. Firebase is primary, but `_read_token`
ran before the client was ever built, so a Firebase-only machine could not
sync at all -- the commits that fixed this touched only the Dart side.

A stalled sync was invisible: the config gates returned silently and
`openFirebase` swallowed every error. `dart:developer`'s `log()` does not
reach logcat on a release build (verified on device), so logging alone would
not have surfaced it. `SyncHealth` records each tick's outcome and the log
screen shows a banner when publishing has actually stopped.

Also make the real-Tk probes bypass the window manager. A tiling WM retiles a
managed toplevel instead of honouring the requested geometry, so `winfo_height`
reported 0/1px and the layout and focus-ring assertions failed on noise rather
than on any regression -- 8 failures on the dev machine that only passed under
Xvfb. `overrideredirect` makes the measurement deterministic with or without a
WM; the probes still detect a genuine overflow at 1366x300.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RT8X32S9yDLW1Xf1PDq8z7
2026-08-10 14:35:37 +02:00
fc9822b516 packaging/aur: track the current release tag
Some checks are pending
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
Routine follow-up to the per-commit version bump: the clean vX.Y.Z tag moved,
so the template's pkgver follows. sha256sums stays 'SKIP' -- the tarball for a
tag contains this file, so the real hash can only be filled in by updpkgsums in
the AUR checkout after the tag exists.

Note this line is inherently a lagging indicator: publishing runs updpkgsums
against whatever tag is newest at that moment, so the AUR may be a release
ahead of what is written here. ~/utils/aur-publish/publish.sh resolves the tag
itself and does not read this value.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Aoa1nKWRrAbowz7Hfd3tgL
2026-08-10 07:18:53 +02:00
722 changed files with 79147 additions and 15588 deletions

3
.fvmrc Normal file
View File

@ -0,0 +1,3 @@
{
"flutter": "3.50.1"
}

33
.github/workflows/file-length.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: file-length
# The 250-line cap, enforced on push as well as at commit time. The local
# pre-commit hook can be skipped (a fresh clone that never ran `pre-commit
# install` has no hooks at all), so the cap needs a second gate that no one
# can forget to install.
#
# Deliberately a SEPARATE workflow from release-apk.yml: a file that grew too
# long should fail lint, not block publishing an APK.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
file-length:
name: file length <= 250 lines
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same cap. Checking it out beats vendoring a copy
# here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the cap
run: bash .utils/scripts/check_file_length.sh --all

38
.github/workflows/md-naming.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: md-naming
# The four markdown namespaces, enforced on push as well as at commit time.
# The local pre-commit hook can be skipped (a fresh clone that never ran
# `pre-commit install` has no hooks at all), so the convention needs a second
# gate that no one can forget to install.
#
# Deliberately a SEPARATE workflow from any release job: a badly named doc
# should fail lint, not block publishing an artifact.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
md-naming:
name: markdown naming convention
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same namespaces. Checking it out beats vendoring a
# copy here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the naming convention
run: bash .utils/scripts/check_md_naming.sh --all
# Warns only: no machine can prove a task is finished, so an old TODO
# gets a nudge, never a failure.
- name: Warn about stale TODOs
run: PYTHONPATH=.utils python3 .utils/md_naming/stale.py

View File

@ -7,13 +7,77 @@ on:
branches: [main]
jobs:
# mypy (~17 s) and pylint (~10 s, plus ~20 s to build its hook env) checked
# the whole repo inside one ~2 min job, so each gets its own runner and the
# other hooks share a third; the workflow takes as long as the slowest group
# rather than the sum.
pre-commit:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- group: mypy
hooks: mypy
skip: ""
- group: pylint
hooks: pylint
skip: ""
- group: rest
hooks: ""
skip: mypy,pylint,dependency-freshness
name: pre-commit (${{ matrix.group }})
steps:
- uses: actions/checkout@v4
# The file-length and md-naming hooks delegate to the shared gates in
# kuhyx/utils, which a runner does not have at $HOME/src/utils. Only
# the rest group runs them.
- name: Check out the shared gates
if: matrix.group == 'rest'
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Point the delegates at that checkout
if: matrix.group == 'rest'
run: echo "UTILS_ROOT=$GITHUB_WORKSPACE/.utils" >> "$GITHUB_ENV"
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: pip install -r requirements.txt
- uses: pre-commit/action@v3.0.1
python-version: "3.x"
# Only rest caches its wheels: its install is the big one, and a shared
# key would hold whichever group saved first (the suffix keeps it apart
# from the Tests workflow's cache of the same requirements.txt).
- uses: astral-sh/setup-uv@v10.2.0
with:
enable-cache: ${{ matrix.group == 'rest' }}
cache-dependency-glob: requirements.txt
cache-suffix: pre-commit-${{ matrix.group }}
# mypy and pylint bring their own hook environments, so they need only
# pre-commit. The rest group's language: system patch-targets hook
# imports diet_guard and every patched module (requests, gatelock,
# crdt_sync, freedays, mcp, pydantic) -- so it keeps the full
# requirements.txt. That install used to run in the one job, with plain
# pip, for ~24 s.
- name: Install pre-commit and the system hooks' imports
run: |
if [[ "${{ matrix.group }}" == rest ]]; then
uv pip install --system -r requirements.txt
else
uv pip install --system pre-commit
fi
# One cache per group: a shared key would hold whichever group saved
# first, and the others would rebuild their hook envs on every run.
- uses: actions/cache@v4
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ matrix.group }}-${{ env.pythonLocation }}-${{ hashFiles('.pre-commit-config.yaml') }}
- name: pre-commit run (${{ matrix.group }})
env:
SKIP: ${{ matrix.skip }}
run: pre-commit run ${{ matrix.hooks }} --all-files --show-diff-on-failure --color=always

View File

@ -9,27 +9,46 @@ on:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
python-version: "3.x"
# uv with a cached wheel store installs requirements.txt (git deps
# included) in seconds; plain pip took ~26 s of a ~56 s run.
- uses: astral-sh/setup-uv@v10.2.0
with:
enable-cache: true
cache-dependency-glob: requirements.txt
cache-suffix: tests
- name: Install dependencies
run: pip install -r requirements.txt
run: uv pip install --system -r requirements.txt
# The gate's keyboard and layout tests drive real Tk: widget heights and
# the focus ring come from the font engine, and no mock can answer what
# they ask. Without a display they do not skip -- they fail, which is how
# this job stayed red while the tests themselves were fine.
# this job stayed red while the tests themselves were fine. pytest-xvfb
# (requirements.txt, geometry in pyproject) starts one Xvfb per xdist
# worker: a shared display let workers steal each other's focus.
# ubuntu-latest already ships xvfb, so the unconditional
# `apt-get update && install` spent ~7 s to report "already the newest
# version"; it now installs only on an image that lacks it.
- name: Install a virtual X display
run: sudo apt-get update && sudo apt-get install -y xvfb
run: |
command -v Xvfb >/dev/null \
|| { sudo apt-get update && sudo apt-get install -y xvfb; }
# -n auto spreads the suite over every runner core (pytest-xdist is in
# requirements.txt); pytest-cov merges the workers' coverage and the
# 100% bar still comes from pyproject's fail_under. -q because -v
# printed all ~1050 test ids.
- name: Run tests with coverage
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -v
run: |
python -m pytest \
-n auto \
-p no:sugar \
-q

View File

@ -3,6 +3,14 @@ name: release-apk
on:
push:
branches: [main]
# A publisher, not a gate: build only when something that ends up in
# the APK changed. versionCode is the commit count, so skipped pushes
# still leave it monotonic.
paths:
- 'app/**'
- '.fvmrc'
- '.versioncode-offset'
- '.github/workflows/release-apk.yml'
# Lets a release be rebuilt from the current main without a dummy commit.
workflow_dispatch:
@ -47,10 +55,12 @@ jobs:
with:
distribution: temurin
java-version: "17"
# ~/.gradle caches + wrapper, keyed on the Gradle files.
cache: gradle
- uses: subosito/flutter-action@v2
with:
flutter-version: 3.44.8
flutter-version: 3.50.1
channel: stable
cache: true
@ -98,7 +108,9 @@ jobs:
run: |
flutter build apk --release \
--build-name="${{ steps.ver.outputs.semver }}" \
--build-number="${{ steps.vc.outputs.code }}"
--build-number="${{ steps.vc.outputs.code }}" \
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
# Fail closed. `findByName("release") ?: debug` silently falls back to
# the debug key if key.properties is misplaced, producing a green build

25
.github/workflows/repo-contract.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: repo-contract
# The local pre-commit hook can be skipped (a fresh clone has no hooks), so the
# contract is enforced on push too. Mirrors md-naming.yml.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
repo-contract:
name: repo contract
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the repo contract
run: bash .utils/scripts/check_repo_contract.sh

3
.gitignore vendored
View File

@ -17,3 +17,6 @@ htmlcov/
# ci_mirror.sh cached requirements.txt venv (rebuilt on demand)
.ci-mirror-venv/
# Kuchnia Wikinga probe captures: contain account data, never commit.
kuchnia_probe*.json

View File

@ -9,6 +9,7 @@ default_language_version:
default_stages: [pre-commit]
fail_fast: false
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
@ -26,9 +27,9 @@ repos:
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
# Shared fake widgets, not a test module. Split out of conftest.py only
# because that file passed the 500-line cap.
exclude: ^diet_guard/tests/_(tk_fakes|gate_layout_probe|gate_keyboard_probe)\.py$
# Shared fakes and fixtures, not test modules. Split out of conftest.py
# and test_sync.py only because those files passed the 250-line cap.
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -95,6 +96,10 @@ repos:
rev: v3.3.2
hooks:
- id: pylint
# pre-commit itself runs on 3.15 and `python3` resolves to it; this
# pylint's --jobs=4 pickles with dill, which crashes there
# (no `co_lnotab`). The repo targets 3.14.
language_version: python3.14
args:
- --rcfile=pyproject.toml
- --fail-under=10
@ -102,10 +107,21 @@ repos:
additional_dependencies:
- pytest
- requests
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync
# Kept in step with pyproject.toml: pip refuses two different
# 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.16.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.184
- httpx==0.28.1
- mcp>=2,<3
- pydantic
- defusedxml==0.7.1
# Test suites intentionally use patterns (protected-access, magic-value
# comparisons) that don't belong in the source-code 10/10 gate.
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
@ -125,14 +141,135 @@ repos:
- repo: local
hooks:
- id: ci-mirror
name: CI mirror (clean-venv pytest + pre-commit --all-files)
entry: bash scripts/ci_mirror.sh
# Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form.
- id: ci-mirror-venv
name: CI mirror 1 (clean venv)
entry: bash scripts/ci_mirror.sh venv
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [pre-push]
stages: [manual]
- id: ci-mirror-precommit
name: CI mirror 2 (pre-commit --all-files)
entry: bash scripts/ci_mirror.sh precommit
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-pytest
name: CI mirror 3 (pytest, xvfb, 100% cov)
entry: bash scripts/ci_mirror.sh pytest
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-analyze
name: CI mirror 4 (flutter analyze)
entry: bash scripts/ci_mirror.sh flutter-analyze
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-1
name: CI mirror 5 (flutter test 1/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-2
name: CI mirror 6 (flutter test 2/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 1/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-3
name: CI mirror 7 (flutter test 3/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 2/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-4
name: CI mirror 8 (flutter test 4/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 3/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-5
name: CI mirror 9 (flutter test 5/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 4/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-6
name: CI mirror 10 (flutter test 6/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 5/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-7
name: CI mirror 11 (flutter test 7/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 6/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-8
name: CI mirror 12 (flutter test 8/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 7/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-9
name: CI mirror 13 (flutter test 9/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 8/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-10
name: CI mirror 14 (flutter test 10/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 9/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-11
name: CI mirror 15 (flutter test 11/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 10/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-12
name: CI mirror 16 (flutter test 12/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 11/12
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
@ -140,9 +277,19 @@ repos:
- id: codespell
args:
- --skip=*.json,*.lock,.git,__pycache__,.venv
# Devine: the 1974 ideal-body-weight formula's author, not "define".
- --ignore-words-list=devine
- repo: local
hooks:
# Fails a commit that still points crdt_sync at a local path. Local
# tests would go green against a library CI has never seen, silently.
- id: crdt-sync-override
name: no local crdt_sync dependency_override
entry: bash scripts/check_no_crdt_sync_override.sh app/pubspec.yaml
language: system
pass_filenames: false
always_run: true
# Every commit ships its own patch bump, so the release workflow's clean
# vX.Y.Z tag tracks HEAD instead of whatever version was last hand-edited.
# The Flutter app lives in app/, so point the script at its pubspec.
@ -162,8 +309,104 @@ repos:
# shebang (SC2148) and its variables are read by makepkg rather than by
# the file itself (SC2034). namcap is what actually lints these.
exclude: '^packaging/aur/PKGBUILD$'
- id: max-file-length
name: Max file length (500 lines)
entry: python3 scripts/check_file_length.py
# The shared 250-line cap. Checks only the files in the commit, so an
# unrelated commit never breaks; exits 1 rather than warning. No
# baseline and no allowlist -- those are suppressions. The exemption
# list (generated/vendored/data files) lives with the checker in
# ~/src/utils/file_length/config.py so the gate and the survey cannot
# disagree.
#
# Deliberately unfiltered: no types_or and no files. The cap applies to
# Dart and prose too, and a type filter here is what would silently
# exempt the whole Flutter app and every .md.
- id: file-length
name: file length <= 250 lines
entry: scripts/check_file_length.sh
language: system
types_or: [python, shell]
# unittest.mock.patch fails OPEN: once a refactor moves a name, a patch
# target that still imports redirects nothing, the test passes, and the
# suite writes to the real ~/.local/share/diet_guard. This resolves every
# patch target statically so a stale path fails the commit instead.
- id: patch-targets
name: test patch targets resolve
entry: python3 scripts/check_patch_targets.py diet_guard
language: system
pass_filenames: false
files: ^diet_guard/
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
# Shared gate in ~/src/utils owns the namespaces and the exemption list, so
# one repo's idea of a valid name cannot drift from every other repo's.
- id: md-naming
name: markdown naming convention
entry: scripts/check_md_naming.sh
language: system
files: \.(md|markdown)$
- id: todo-closer
name: close Todo trailer tasks
entry: scripts/todo_hooks.sh closer
language: system
stages: [post-commit]
always_run: true
pass_filenames: false
- id: todo-import-pr-merge
name: import PR Todo sections (pull)
entry: scripts/todo_hooks.sh import-pr post-merge
language: system
stages: [post-merge]
always_run: true
pass_filenames: false
- id: todo-import-pr-rewrite
name: import PR Todo sections (pull --rebase)
entry: scripts/todo_hooks.sh import-pr post-rewrite
language: system
stages: [post-rewrite]
always_run: true
pass_filenames: false
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
# so the question is mechanically answerable at all.
#
# `files:` is what keeps this cheap: a commit touching only source makes
# ZERO network requests, and manifest commits mostly hit a 6h disk cache.
#
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
# answer and passes with a loud banner; `--no-verify` is banned here, so
# a hook that hard-failed on a flaky connection would leave no way to
# commit at all. CI, always online, is the strict authority.
- id: dependency-freshness
name: dependencies on newest stable
entry: scripts/check_dependency_freshness.sh
language: system
pass_filenames: true
files: >-
(pubspec\.(yaml|lock)|pyproject\.toml|requirements.*\.txt|uv\.lock
|package\.json|package-lock\.json|pnpm-lock\.yaml
|Cargo\.(toml|lock)|go\.(mod|sum)
|\.fvmrc|\.nvmrc|\.python-version
|\.github/workflows/.*\.ya?ml)$
- repo: local
hooks:
# The only pre-push hook. Everything that used to run here is now
# `stages: [manual]` -- run on demand with `scripts/check_gate_stamp.sh
# full`, and by CI on every push. finish_auto.sh stamps HEAD after its
# gate; a tree without that receipt cannot leave the machine.
- id: gate-stamp
name: pushed tree passed the local gate (stamp check)
entry: scripts/check_gate_stamp.sh check
language: system
pass_filenames: false
always_run: true
stages: [pre-push]
- id: repo-contract
name: repo contract (CLAUDE.md Commands + test_changed)
entry: scripts/check_repo_contract.sh
language: system
pass_filenames: false
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$

249
AGENTS.md Normal file
View File

@ -0,0 +1,249 @@
# CLAUDE.md — diet_guard
A log-to-unlock gate. Every ~15 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/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu catch-up rule).
## Commands
- One sync tick: `python -m diet_guard sync`
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
- "Send to Claude" worker: `python -m diet_guard claude-worker` ([relay](docs/DOCS-claude-relay.md), [screen](docs/DOCS-log-screen.md))
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
- run: `python -m diet_guard gate --demo`
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
- test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
- lint: `pre-commit run --all-files`
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
- deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
- coverage-gaps: `coverage-gaps coverage.lcov`
## Scheduling
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15: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 at once when no lock is due (free/sick day:
[docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)). Needs `DISPLAY`/`XAUTHORITY`; see the unit file
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.
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` / `app/lib/services/sync_e2e.dart`):
everything lives on `diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
fields sealed with a key from the shared passphrase (`~/.config/crdt-sync/password`; keystore + lock
icon in Settings on the phone). Record ids, tombstones and clocks stay clear, so the food banks' ids
(food names) are visible. The old plaintext `diet-guard-sync/devices` (and its `export_keys.json`
keyring) is copied over and never written or deleted. Locked = `SyncError` / `SyncLockedException`:
nothing is pulled or pushed. The PC keeps its derived key and copy memo in
`~/.local/share/diet_guard/e2e`. The wake-alarm weigh-ins come from `wake-alarm-sync/devices-e2e`
(own header).
**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.
- **`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**, budget, both food banks, the Body doc via `_sync_body`,
and last the newest logged weight into `w` via `_phone_weight`).
`_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
[docs/DOCS-sync-latency.md](docs/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
(listed in `tests/_state_redirects.py`: `_cli_log`, `_cli_gate`, `_mcp`,
`_cli_body`, `_cli_kuchnia` publish sites and `_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 (`~/src/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.
- **Body data persists and syncs** (profile, weight log, PC workouts) as
`body.json`; its tables are informational. [docs/DOCS-body.md](docs/DOCS-body.md).
- **PC and phone share one source of truth for everything**: food log, budget,
budget history, body weight (`w`), Body doc, 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. Exceptions: sync (`kuhyx/syncs`, `~/.config/diet_guard/`) and
read-only workout sources (RunnerUp drop, screen-locker: `_activity_sources`).
- **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
(`~/src/todo/docs/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
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and how many meals fall
between them; interior slots round to the 15-min grid. Default `(480, 1200, 4)` is the old hardcoded
08/12/16/20. The load-bearing rules (integer-only arithmetic, the additive `slot`+`slot_min` /
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff, nearest-slot
satisfaction), the forward-only history, and the two edit surfaces are in
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching `_slots.py` /
`_slot_wire.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/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" or the reward prompt
(removed deliberately, `app/test/repo_invariants_test.dart`). A meal photo is
transient input to Claude only (2026-11-17): never stored, on a `FoodEntry`
or synced; the invariants test asserts no image bytes reach a record.
- 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.
- Catering logs itself since 2026-11-17 (kuhy overrode "delivered ≠ eaten":
"LOG EVEN WITHOUT TAP"): v5 ids `kuchnia:<date>:<dishId>`, undo tombstones.
Don't let its Python and Dart halves drift (shared fixtures) or make the
synced password machine-local. [docs](docs/DOCS-kuchnia-wikinga.md),
[phone](docs/DOCS-kuchnia-wikinga-phone.md).
- 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 `~/src/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`. Re-fetch periodically. Split across five files for the 250-line cap._
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
- [Code generation, testing and theming](docs/DOCS-flutter-rules-testing-and-assets.md)
- [UI: theming, layout and overlays](docs/DOCS-flutter-rules-ui.md)
- [Colour, type, documentation and accessibility](docs/DOCS-flutter-rules-design.md)

1067
CLAUDE.md

File diff suppressed because it is too large Load Diff

1
CLAUDE.md Symbolic link
View File

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

View File

@ -1,151 +0,0 @@
# Design audit — diet-guard
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
Report only — nothing in this repo was changed by the audit itself.
This repo has two UI surfaces, audited separately below.
---
## Flutter app (`app/`)
Theme entry point: `app/lib/main.dart:52` —
`ThemeData(colorSchemeSeed: Colors.teal, useMaterial3: true)`. This is the
**entire** theme definition: no `darkTheme`, no `textTheme` override, no
component themes (`elevatedButtonTheme`, `cardTheme`, etc.), no
`ThemeExtension`. Everything downstream of this one line either inherits
Material 3's generated defaults or bypasses the theme with raw `Colors.*`
literals in individual widgets — sampled across `screens/` and `widgets/`
(11 of 21 files).
### Violations
- **Rule 1 (near-black/near-white)** — `app/lib/widgets/day_status_calendar.dart:79` uses `Colors.black` for the "not logged" cell fill, and `:87`/`:121` use pure `Colors.white` for text — both bypass the muted near-black/near-white the seeded `ColorScheme` would otherwise supply.
- **Rule 2 (saturate neutrals)** — `app/lib/widgets/day_status_calendar.dart:78,104` (`Colors.grey.shade800`) and `app/lib/widgets/slot_selector_row.dart:49` (`Colors.grey`) use Material's generic, zero-chroma grey instead of a grey tinted toward the teal seed.
- **Rule 4 (everything deliberate)** — no centralized token beyond the one-line `ThemeData` call; `day_status_calendar.dart` (8 raw `Colors.*` refs), `slot_selector_row.dart` (4 raw refs, lines 46-49), and `settings_screen.dart:567` each invent status/error colors independently instead of reading `Theme.of(context).colorScheme`.
- **Rule 4 (inconsistency, concrete pair)** — the same semantic "error" state is styled two different ways in the same app: `history_screen.dart:603` uses `Theme.of(context).colorScheme.error`, but `settings_screen.dart:567` hardcodes `Colors.red` for the same purpose.
- **Rule 9 (distinct brightness values)** — `day_status_calendar.dart:80-82` mixes `Colors.red.shade400` (lighter) with `Colors.amber.shade700` / `Colors.green.shade700` (darker) for three parallel status swatches meant to read as one family — inconsistent shade selection, not a deliberate brightness ramp.
- **Rule 11 (mathematically related measurements)** — corner radii are inconsistent across near-identical use cases: `BorderRadius.circular(8)` in `day_status_calendar.dart:105` and `photo_attach_field.dart:95` vs `BorderRadius.circular(6)` in `history_screen.dart:638` for the same "thumbnail clip" purpose, with no shared base unit.
- **Rule 20 (body text ≥16px)** — `day_status_calendar.dart:123` (`fontSize: 14`), `:146` (`fontSize: 11`), `:181` (`fontSize: 12`) are all below the 16px minimum, with no larger default applied elsewhere to compensate for this widget.
- **Rule 28 (icon contrast lower than text)** — `slot_selector_row.dart:54` (`Icon(..., color: color)`) and `:57` (`labelStyle: TextStyle(color: color)`) give the check icon and its adjacent label text the *same* full-strength color — the icon should read lighter/lower-contrast than the text, not equal.
### Passes worth recording
- **Rule 3** — clear hierarchy exists elsewhere: `history_screen.dart:603` correctly pulls the delete/error action from `colorScheme.error`.
- **Rule 18 (container brightness limits)** — only one nested-container case was found (`day_status_calendar.dart`'s `grey.shade800` panel on the default light scaffold); no evidence of a violation.
- **Rule 23 (two typefaces max)** — no `fontFamily` or `google_fonts` import anywhere in `app/lib/` — the whole app uses exactly one (system default) typeface.
- **Rule 26 / 27 (shadows/depth)** — no `BoxShadow`, `elevation:`, or `Card(` usage found in the sampled files; zero depth technique used, so it's trivially consistent (though see Notes — this also means rule 15/16/17 have nothing to evaluate).
- **Rule 28 (partial pass)** — `day_status_calendar.dart:113,127` (`Colors.white70` chevron icons) sit next to `:121` (`Colors.white` full-opacity month label) — here the icon *is* correctly lower-contrast than the text.
### Not applicable
- Rule 5 (optical alignment) — no asymmetric icon/shape widgets found requiring hand-tuned centering.
- Rule 6 (letter-spacing/line-height by size) — no manual `letterSpacing`/`height` found anywhere in `screens/`/`widgets/`; the app relies entirely on Material 3's built-in type scale, which already encodes this rule.
- Rule 7 (container border contrast) — the one border found (`day_status_calendar.dart:172-174`, `Colors.white70` on `Colors.black`) has adequate contrast against both surfaces; no counter-evidence.
- Rule 8 (everything aligns) — default `MainAxisAlignment.spaceBetween`/`spaceAround` usage throughout; no counter-evidence gathered.
- Rule 10 (warm or cool, not both) — the app doesn't saturate its neutrals at all (see Rule 2 violation above), so warm/cool consistency has nothing to check.
- Rule 12 (order by visual weight) — no clear violation or pass identified from the sampled files; would need a full-screen layout review.
- Rule 13 (12-column grid) — mobile-first single-column screens; no grid system in use.
- Rule 14 (space between high-contrast points) — insufficient evidence gathered from the sample.
- Rule 15 (closer = lighter) — no elevation/z-stacking found to evaluate (see Rule 26/27 pass note).
- Rule 16 (shadow blur ≈ 2× distance) — no `BoxShadow` in the codebase.
- Rule 17 (simple on complex) — flat design throughout; no complex background/foreground pairing to break the rule.
- Rule 19 (outer padding ≥ inner padding) — holds everywhere checked, e.g. `day_status_calendar.dart:102` (`EdgeInsets.all(12)` outer) vs `:168` (`EdgeInsets.symmetric(vertical: 2)` cell margin).
- Rule 21 (line length ~70 chars) — no long-form body text in the sampled screens (mostly labels/numbers).
- Rule 22 (button padding h=2×v) — no explicit `ButtonStyle.padding` override found anywhere; buttons run on Material 3 defaults, which already approximate this ratio.
- Rule 24 (nest corners) — no nested corner-radius container pairs found to check a concentric relationship.
- Rule 25 (avoid adjacent hard divides) — insufficient evidence gathered from the sample.
### Notes
- The theme is effectively unstyled beyond a seed color. Every rule above that reads "no evidence"/"insufficient evidence" is really a symptom of the same root cause: there is no `theme.dart`, no `ThemeExtension` for semantic colors (success/warn/danger), and no component themes, so status colors (green/red/amber/grey) get re-invented per-widget instead of being defined once. Centralizing those into a `ThemeExtension` (e.g. `DietGuardStatusColors`) would fix the Rule 4/9/28 violations above in one pass and make Rule 15/16/17/18/26/27 actually checkable against a real design system instead of "nothing to evaluate."
- `day_status_calendar.dart`'s status colors (`red.shade400`/`amber.shade700`/`green.shade700`) do not literally match the Python gatelock's calendar palette (`#ff5555`/`#e0c33c`/`#33cc66` — see Python section below) even though the widget's own doc comment (`day_status_calendar.dart:9`) says it "mirrors" that view. Worth reconciling into one shared value if visual parity between the phone app and the PC lock screen actually matters.
---
## Python/Tkinter gatelock UI (`diet_guard/`, not `app/`)
Files audited: `_gatelock_ui.py` (474 lines), `_gatelock_mealflow.py` (349),
`_gatelock_calendar.py` (466), `_gatelock_core.py` (196),
`_gatelock_nutrition.py` (230), `_gatelock.py` (211), `_gatelock_support.py`
(82), `_calendar_view.py` (151).
**Correction to prior research going in:** there *is* a color-constants block
(`_gatelock_ui.py:27-32`: `BG`, `FG`, `_ACCENT`, `ERR`, `_FIELD_BG`,
`_MUTED`), so "no color/theme constants module" is not quite right — the
real problem is worse than absence: it's **triplication**. `_gatelock_ui.py`
is the closest thing to a canonical module, but `_gatelock_calendar.py:58-60`
and `_calendar_view.py:25-33` each **redefine their own copies** of the same
values instead of importing them (see Violations below). `_gatelock_calendar.py:55-57`
even has a comment justifying this: *"BG/FG/ERR come from `_gatelock_ui`'s
public exports; the rest are private to that module, so equivalents are
defined locally rather than reaching across the boundary."* That's a
structural decision (avoid touching another module's private names) that
produces exactly the drift risk a shared module is supposed to prevent.
Confirmed **no `ttk.Style()` call anywhere** in the 8 files (0 grep hits).
Hex-literal count is also off from the prior estimate: **25 occurrences of
12 distinct hex values** (not ~4) across the 3 files that define palette
constants. Inline `font=` literal count is confirmed accurate: **35
occurrences**.
### The shared `LockConfig.bg` token
`~/utils/gatelock/gatelock/_window.py:71` — `LockConfig.bg: str = "#1a1a1a"`
is the one real shared design token in this family (used by `screen-locker`,
`wake_alarm`, and `diet_guard` alike via `GateRoot`/`LockWindow`).
- `diet_guard/_gatelock_ui.py:27` — `BG = "#1a1a1a"` **re-hardcodes the same
literal instead of importing `gatelock.LockConfig.bg`**. It happens to
match today, but nothing keeps it in sync — if `LockConfig`'s default ever
changes, this constant silently goes stale.
- `diet_guard/_gatelock.py:147` — `LockConfig(mode=..., bg=BG)` then passes
that duplicated literal back into `LockConfig` explicitly. This call is
redundant today (it matches `LockConfig`'s own default) and masks the
duplication: it *looks* like `diet_guard` is deliberately overriding the
background, when it's actually just echoing the default via a second,
unlinked constant.
- Fix direction (report-only, not applied): `_gatelock_ui.py` should import
`LockConfig.bg` (or a `LockConfig()` default instance's `.bg`) rather than
defining its own `BG` literal, and `_gatelock.py:147` should drop the
explicit `bg=BG` kwarg entirely once it's provably redundant.
### Violations
- **Rule 1 (near-black/near-white)** — `_calendar_view.py:25` `_NOT_LOGGED_FILL = "#000000"` is pure black; `_gatelock_ui.py:434` and `:459` (`fg="white"`) are pure white. This is inconsistent with the rest of the palette, which correctly uses `#1a1a1a`/`#e0e0e0` (near-black/near-white, not pure).
- **Rule 2 (saturate neutrals)** — every neutral in the shared palette is a zero-chroma grey (equal R/G/B hex pairs): `BG "#1a1a1a"`, `_FIELD_BG "#2a2a2a"`, `_MUTED "#9a9a9a"` (`_gatelock_ui.py:27,31,32`), plus the duplicate `LockConfig.bg = "#1a1a1a"` (`gatelock/_window.py:71`). None carry any tint — exactly the "generic gray" this rule warns against.
- **Rule 4 (everything deliberate / centralization)** — `_MUTED = "#9a9a9a"` is defined **three times** verbatim: `_gatelock_ui.py:32`, `_gatelock_calendar.py:58`, `_calendar_view.py:33`. `"#003322"` (status text color) is likewise defined 3×: `_gatelock_ui.py:191,421`, `_gatelock_calendar.py:154`, `_calendar_view.py:32`. `_FIELD_BG "#2a2a2a"` and `_ACCENT "#00ff88"`/`"#00cc66"` are each duplicated across `_gatelock_ui.py` and `_gatelock_calendar.py`. No `ttk.Style()` centralizes any of this.
- **Rule 11 (mathematically related measurements)** — font sizes in use: 10, 11, 12, 13, 14, 15, 16, 22, 30 (`_gatelock_ui.py` and `_gatelock_calendar.py`, e.g. `_gatelock_ui.py:130,145,161,285,371,378`) — no common ratio or base unit. Spacing is similarly mixed: `ipady=3` (`_gatelock_ui.py:147,216`) vs `ipady=2` (`:256,330`; `_gatelock_calendar.py:148`) used interchangeably for the same "entry field" role.
- **Rule 20 (body text ≥16px)** — the dominant font size is 12pt (9 occurrences in `_gatelock_ui.py` alone: lines 161,185,209,225,249,260,334,343,... ) with many labels at 11-13pt; only headline-style text (22, 30) clears a 16px-equivalent minimum.
### Passes worth recording
- **Rule 3 (high contrast for important elements)** — `_gatelock_ui.py:416-425` ("Log & Continue", the primary action) uses bright `_ACCENT #00ff88`; `:429-438` ("Fetch from sync", secondary) uses a muted `#334455`/`#445566` pair. Clear, deliberate hierarchy.
- **Rule 9 (distinct brightness values)** — `_calendar_view.py:28-30`: `GREEN #33cc66` / `YELLOW #e0c33c` / `RED #ff5555` are visually distinct hues at roughly matched brightness — better-executed than the Flutter app's equivalent (see Flutter Rule 9 violation above).
- **Rule 18 (container brightness limits)** — `BG "#1a1a1a"` (~10% luma) vs `_FIELD_BG "#2a2a2a"` (~16% luma), a ~6% delta — comfortably within the ~12% dark-interface guideline (`_gatelock_ui.py:27,31`).
- **Rule 19 (outer padding ≥ inner padding)** — outer frame padding (e.g. `padx=6` at `_gatelock_ui.py:144`) is consistently ≥ field-level `ipady=2-3`.
- **Rule 23 (two typefaces max)** — exactly two families used: "Arial" (34 occurrences) and "Courier" (1 occurrence, `_gatelock_ui.py:292`).
- **Rule 26 / 27 (no shadows / single depth technique)** — `relief=` (Tk's raised/sunken/groove bevel, its closest thing to a shadow) is never used in any of the 8 files (0 grep hits); zero depth technique applied, trivially consistent.
### Not applicable
- Rule 5 (optical alignment) — no asymmetric icon/shape widgets in this Tk UI.
- Rule 6 (letter-spacing/line-height by size) — Tk's `font=` tuples have no letter-spacing control and no independent line-height axis; not expressible in this toolkit.
- Rule 7 (container border contrast) — `highlightthickness` varies 0/1/2 (`_gatelock_ui.py:174,193,229`; `_gatelock_calendar.py:235`) but the one case with a matched-to-background `highlightbackground` (`_calendar_view.py:108-115`, future-day cells) is intentional per its own docstring (`day_status_calendar.dart:9`-equivalent design: blend future days into the background), not a rule violation.
- Rule 8 (everything aligns) — grid/pack-based layout; no counter-evidence gathered.
- Rule 10 (warm or cool, not both) — the neutrals aren't saturated at all (Rule 2 violation above), so there's no warm/cool choice to be consistent about.
- Rule 12 (order by visual weight) — not assessed from the sampled files.
- Rule 13 (12-column grid) — fixed-size fullscreen dialog, not a column-grid layout.
- Rule 14 (space between high-contrast points) — insufficient evidence gathered.
- Rule 15 (closer = lighter) — Tk has no z-stacking/elevation concept; nothing to evaluate.
- Rule 16 (shadow blur ≈ 2× distance) — Tk has no drop-shadow primitive; unused.
- Rule 17 (simple on complex) — flat single-color backgrounds throughout; no complex imagery to conflict with.
- Rule 21 (line length ~70 chars) — `wraplength=900` (pixels, e.g. `_gatelock_ui.py:410,446`) is a pixel wrap, not a character-count guarantee; can't verify without rendering.
- Rule 22 (button padding h=2×v) — no `tk.Button` in the sampled files sets explicit `ipadx`/`ipady`; only `Entry` widgets do (grep-confirmed). Buttons run on Tk's own default padding, unexamined by this rule.
- Rule 24 (nest corners) — Tk widgets here are flat-relief rectangles; no corner-radius concept applies.
- Rule 25 (avoid adjacent hard divides) — insufficient evidence gathered.
- Rule 28 (icon contrast lower than text) — this UI uses unicode glyphs embedded in button `text=` (e.g. `"⟳ Fetch from sync"` at `_gatelock_ui.py:431`, `"✕ Close Demo"` at `:456`) rather than a separately-styled icon widget; there's no independent icon-vs-text contrast axis to check.
### Notes
- The real fix for the Python surface's Rule 4 violations is structural: promote `_gatelock_ui.py`'s 6 constants (plus `_calendar_view.py`'s status-color dict) into one importable module that every gatelock file reads from, and have that module import `gatelock.LockConfig`'s `bg` default rather than re-literal-ing `"#1a1a1a"`. That single change collapses 3 duplicate `_MUTED`/`"#003322"` definitions and closes the `LockConfig.bg` drift risk in one pass.
- Because `LockConfig.bg = "#1a1a1a"` is shared by `screen-locker` and `wake_alarm` too, if those repos independently re-hardcode `"#1a1a1a"` the same way `diet_guard` does, this is a family-wide pattern, not a `diet_guard`-only one — worth a follow-up grep across those repos if/when this gets fixed.

20
DOCS-dopamine-ux.md Normal file
View File

@ -0,0 +1,20 @@
# diet-guard dopamine-ux: context
## context you would otherwise rediscover
- This app has **no `design_system` dependency** — `app/lib/ui/theme.dart` is a
hand-transcription of the shared tokens (values are byte-identical, names in
comments). Motion tokens from prompt 01 must be **transcribed into that local
theme file**, matching the existing convention. Do not add the dependency here;
that is a separate, larger refactor.
- Capability baseline, verified 2026-08-16: **no audio package, no `assets:`
block, no `vibration` package, no VIBRATE permission.** The only existing
audio-adjacent thing is the `diet_guard_due_slot` notification channel
(`app/lib/services/notification_backend_io.dart` ~:17-18, :52-55) at
`Importance.high` with no explicit sound/vibration override — leave it alone.
- The app already computes both a **logging streak** and an **adherence streak**
(`_daystatus.py:144`/`:153` on the Python side, mirrored in Dart). You are
making existing true data feel like something, not inventing a new metric.
- diet-guard state lives under XDG (`~/.local/share/diet_guard`), unlike
screen-locker's in-repo JSON. Tests isolate it via
`~/src/diet-guard/diet_guard/tests/conftest.py:97` `_isolate_state`.

30
DOCS-lock-order.md Normal file
View File

@ -0,0 +1,30 @@
# Lock order
When several locks are due at once, gatelock shows the one with the highest
rank first. Each lower lock waits, with no window, until every higher lock has
been cleared. kuhy fixed this order on 2026-11-21:
| Order | Lock | gatelock app | Rank | Repo |
|---|---|---|---|---|
| 1 | workout | screen_locker | 200 | screen-locker |
| 2 | book | book_guard | 175 | book-guard |
| 3 | tutor | tutor_gate | 150 | tutor |
| 4 | diet | diet_guard | 130 | diet-guard |
| 5 | focus | focus_guard | 128 | focus-guard |
| 6 | leetcode | leetcode_guard | 125 | leetcode-guard |
LeetCode goes last. Each rank is a literal in its own repo, not a
`gatelock.RANK_*` constant, so changing one does not need a gatelock release.
Every repo keeps a copy of this file, and its tests fail when its own number
differs from its row here. Change the rank, this table and the copies in the
other repos together.
Not in the table:
- The wake alarm (300) outranks everything.
- The evening chain (`gatelock.evening_chain`) runs its rungs one at a time,
in the order book, tutor, LeetCode. Its book rung locks at 150, which ties
the tutor. Ranks only order locks that are due at the same moment.
- All of these lock with a global grab and VT switching disabled, so no
higher rank is ever a weaker lock. `gatelock/scripts/verify_all_lockers.py`
checks this order on a private X server.

View File

@ -46,7 +46,7 @@ The band boundaries are the calendar's own (at or under budget / up to 20%
over / more than 20% over), so a period and its day cells can never disagree
about what "over" means.
The timer runs the gate automatically every ~30 minutes; no manual
The timer runs the gate automatically every ~15 minutes; no manual
invocation is needed once installed.
## MCP server
@ -87,6 +87,15 @@ bash scripts/setup_mcp.sh # create the venv and install diet_guard[mcp]
Then restart Claude Code in this repo and approve the project MCP server
(registered in `.mcp.json`).
## Error reports
Every uncaught, thread or Tk callback error, and any freeze of the gate window
over 1 s, goes to the shared app-errors spool as app `diet-guard-gate`
through `gatelock.error_report` (`diet_guard/_errors.py`, installed by the
CLI). The PC's `app-errors` timer turns each one into a ticket on the
todoImplementer board (kuhyx/utils `DOCS-app-errors.md`). Nothing shows on
screen. The Flutter app reports on its own, as `diet-guard`.
## Development
```bash
@ -96,4 +105,4 @@ python -m venv .venv && .venv/bin/pip install -r requirements.txt
```
See `CLAUDE.md` for scheduling details and production deployment gotchas,
and `docs/design.md` for the original feature spec.
and `docs/DOCS-design.md` for the original feature spec.

View File

@ -13,7 +13,7 @@ desktop, sharing one food log through GitHub-backed sync.
There is no `linux/` directory. Flutter's GTK embedder manages ~20fps at
3840x2160 -- measured on a stock `flutter create` counter app, so it is the
toolkit rather than this code -- where the same Dart rendered by Chrome
sustains ~144fps (`~/todo/docs/desktop-performance-findings.md`). Running
sustains ~144fps (`~/src/todo/docs/DOCS-desktop-performance-findings.md`). Running
`flutter create --platforms linux` here would silently restore the slow path.
## Commands

View File

@ -16,6 +16,12 @@ analyzer:
- "**/*.g.dart"
- "**/*.freezed.dart"
- "test/**"
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:

View File

@ -18,7 +18,12 @@ val keystoreProperties = Properties().apply {
android {
namespace = "com.kuhy.diet_guard_app"
compileSdk = flutter.compileSdkVersion
// Pinned above `flutter.compileSdkVersion` (36 on Flutter 3.47.2):
// flutter_secure_storage 11.0.0, which arrives with crdt_sync_flutter
// v0.3.1, publishes AAR metadata demanding API 37 or later. That in
// turn needs AGP > 9.1.0, which needs Gradle >= 9.5.0 -- see
// settings.gradle.kts and gradle-wrapper.properties.
compileSdk = 37
ndkVersion = flutter.ndkVersion
compileOptions {
@ -34,7 +39,8 @@ android {
applicationId = "com.kuhy.diet_guard_app"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
// Health Connect (the `health` plugin) needs API 26.
minSdk = maxOf(26, flutter.minSdkVersion)
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName

View File

@ -1,6 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Sync (github_client.dart) needs raw socket access. -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- HapticFeedback on a successful meal log (log_meal_screen.dart). -->
<uses-permission android:name="android.permission.VIBRATE"/>
<!-- Android 13+ requires runtime opt-in to post notifications; requested
at launch via NotificationService.requestPermission(). -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
@ -13,6 +15,16 @@
(permission_handler's ignoreBatteryOptimizations) to actually show
the system dialog instead of silently returning denied. -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<!-- Health Connect steps for the Body screen (health_steps.dart). Read
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
WorkManager isolate never reads Health Connect. -->
<uses-permission android:name="android.permission.health.READ_STEPS"/>
<!-- Camera for the meal photo sent to Claude (meal_photo_source.dart); the
runtime permission is requested before the camera opens. A photo is
transient input: it is never stored or synced. Not every device has a
camera, and the gallery path works without one. -->
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
check is a 15-minute WorkManager periodic task, not exact alarms
(more robust against OEM background-kill; +/-15 min is accepted, see
@ -20,7 +32,7 @@
perceived lateness, which trades robustness for precision we don't
need. -->
<application
android:label="diet_guard_app"
android:label="DietGuard"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
@ -44,7 +56,23 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<!-- Health Connect (Android 13 and below) opens this to show why
the app wants steps; see the `health` plugin README. -->
<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
</intent-filter>
</activity>
<!-- Health Connect (Android 14+) links "view permission usage" here. -->
<activity-alias
android:name="ViewPermissionUsageActivity"
android:exported="true"
android:targetActivity=".MainActivity"
android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
<intent-filter>
<action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
<category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
</intent-filter>
</activity-alias>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
@ -61,5 +89,10 @@
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
<!-- Lets the `health` plugin see whether Health Connect is installed. -->
<package android:name="com.google.android.apps.healthdata"/>
<intent>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
</intent>
</queries>
</manifest>

View File

@ -1,5 +1,8 @@
package com.kuhy.diet_guard_app
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterActivity()
// FlutterFragmentActivity, not FlutterActivity: the `health` plugin requests
// Health Connect permissions through registerForActivityResult, which needs a
// ComponentActivity (see the plugin README, "Android 14").
class MainActivity : FlutterFragmentActivity()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

@ -1,4 +1,7 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=256m -XX:+UseSerialGC -XX:TieredStopAtLevel=1
org.gradle.caching=true
org.gradle.parallel=true
kotlin.compiler.execution.strategy=in-process
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip

View File

@ -19,7 +19,7 @@ pluginManagement {
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.0.1" apply false
id("com.android.application") version "9.3.2" apply false
id("org.jetbrains.kotlin.android") version "2.3.20" apply false
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<rect width="1024" height="1024" fill="#211D1B"/>
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,-2)">
<g fill="none" stroke="#B8862E" stroke-width="66.7417" stroke-linecap="round" stroke-linejoin="round" transform="translate(-40.3384,-42.496) scale(1.07879)">
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
<g transform="translate(356,362) scale(13)" fill="#B8862E" stroke="none">
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>

Before

Width:  |  Height:  |  Size: 656 B

After

Width:  |  Height:  |  Size: 688 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 26 KiB

View File

@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,-2)">
<g fill="none" stroke="#B8862E" stroke-width="66.7417" stroke-linecap="round" stroke-linejoin="round" transform="translate(-40.3384,-42.496) scale(1.07879)">
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
<g transform="translate(356,362) scale(13)" fill="#B8862E" stroke="none">
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>

Before

Width:  |  Height:  |  Size: 604 B

After

Width:  |  Height:  |  Size: 636 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<g fill="none" stroke="#FFFFFF" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,-2)">
<g fill="none" stroke="#FFFFFF" stroke-width="66.7417" stroke-linecap="round" stroke-linejoin="round" transform="translate(-40.3384,-42.496) scale(1.07879)">
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
<g transform="translate(356,362) scale(13)" fill="#FFFFFF" stroke="none">
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>

Before

Width:  |  Height:  |  Size: 604 B

After

Width:  |  Height:  |  Size: 636 B

Binary file not shown.

View File

@ -163,6 +163,11 @@ Future<bool> _launchBrowser(String home, int port) async {
// a browser icon instead of diet_guard's.
'--class=diet_guard_app',
'--no-first-run',
// The distro wrapper appends ~/.config/chromium-flags.conf to every launch,
// which here carries `--load-extension` for Claude in Chrome. Logged out in
// this profile, it opened a claude.ai login tab in a second, normal browser
// window on every start. This flag also drops command-line extensions.
'--disable-extensions',
]);
final started = DateTime.now();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 380 B

After

Width:  |  Height:  |  Size: 403 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 542 B

After

Width:  |  Height:  |  Size: 584 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 726 B

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -10,7 +10,7 @@
#
# Icon PNGs are pre-rendered and committed under desktop/icons/, so this script
# needs no image tooling at run time. Regenerate them with:
# PYTHONPATH=~/testsAndMisc python3 -m python_pkg.app_icons \
# PYTHONPATH=~/src/testsAndMisc python3 -m python_pkg.app_icons \
# generate --app diet_guard_app --linux-out desktop/icons
# ============================================================================
@ -77,7 +77,7 @@ install_desktop_entry() {
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=diet guard
Name=DietGuard
Comment=Diet logging and budget companion
Exec=$LAUNCHER
Icon=$ICON_NAME

View File

@ -0,0 +1,44 @@
/// Content types for the files the desktop wrapper serves.
///
/// Split out of `wrapper_server.dart` for file size. A pure function of the
/// path with no server state, so it lives as a plain sibling library rather
/// than a `part`.
library;
import 'dart:io';
import 'package:path/path.dart' as p;
/// Content type for [filePath].
///
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
/// served as anything but `application/wasm`, and the app then renders
/// nothing at all.
ContentType contentTypeFor(String filePath) {
switch (p.extension(filePath).toLowerCase()) {
case '.html':
return ContentType.html;
case '.js' || '.mjs':
return ContentType('text', 'javascript', charset: 'utf-8');
case '.json':
return ContentType.json;
case '.wasm':
return ContentType('application', 'wasm');
case '.css':
return ContentType('text', 'css', charset: 'utf-8');
case '.png':
return ContentType('image', 'png');
case '.jpg' || '.jpeg':
return ContentType('image', 'jpeg');
case '.svg':
return ContentType('image', 'svg+xml');
case '.ttf':
return ContentType('font', 'ttf');
case '.otf':
return ContentType('font', 'otf');
case '.woff2':
return ContentType('font', 'woff2');
default:
return ContentType.binary;
}
}

View File

@ -0,0 +1,35 @@
/// A wordless page for an error the window itself loaded: Chrome would
/// otherwise paint its own "This page isn't working" sentences over an
/// empty error body. Only the title carries the app's name (OS-level label).
library;
import 'dart:io';
/// HTML page with only an icon — no words painted by the browser.
const String errorIconPage =
'<!doctype html><html><head><meta charset="utf-8"> '
'<title>Diet Guard</title> '
'<style>html,body{margin:0;height:100%; '
'background:#211D1B;display:flex;align-items:center; '
'justify-content:center}</style></head><body> '
'<svg width="96" height="96" viewBox="0 0 24 24" fill="none" '
'stroke="#A39892" stroke-width="2" stroke-linecap="round" '
'aria-hidden="true"><circle cx="12" cy="12" r="9"/> '
'<line x1="5.6" y1="18.4" x2="18.4" y2="5.6"/></svg></body></html>';
/// Whether [request] is the window loading a page, not the app's fetch().
bool isNavigation(HttpRequest request) =>
request.headers.value('sec-fetch-mode') == 'navigate';
/// Replaces an error answer to a page load with [errorIconPage]. Does
/// nothing for fetch() calls, successes, or a response already written.
void paintErrorIcon(HttpRequest request) {
final response = request.response;
if (!isNavigation(request) || response.statusCode < 400) return;
try {
response.headers.contentType = ContentType.html;
response.write(errorIconPage);
} on Exception {
return; // body already sent: leave it alone
}
}

View File

@ -19,6 +19,7 @@ library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/desktop/error_page.dart' show isNavigation;
import 'package:http/http.dart' as http;
/// GitHub's REST API base, which [GitHubProxy] fronts.
@ -177,8 +178,13 @@ class GitHubProxy {
}
void _passThrough(HttpRequest request, http.Response response) {
request.response.statusCode = response.statusCode;
if (isNavigation(request)) {
// Top-level navigation (window load) must not paint error JSON; the app's
// own fetch() calls never send 'navigate', so they still get the body.
return;
}
request.response
..statusCode = response.statusCode
..headers.contentType = ContentType.json
..add(response.bodyBytes);
}

View File

@ -2,7 +2,7 @@
///
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder
/// manages only ~20fps at 4K, where the same Dart code in Chrome sustains
/// ~144fps -- see `~/todo/docs/desktop-performance-findings.md`), so it runs
/// ~144fps -- see `~/src/todo/docs/desktop-performance-findings.md`), so it runs
/// in a browser and cannot touch the filesystem. This process is the other
/// half of the desktop app:
///
@ -23,6 +23,8 @@ import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
import 'package:diet_guard_app/desktop/error_page.dart';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:path/path.dart' as p;
@ -90,6 +92,7 @@ class WrapperServer {
} on Exception {
request.response.statusCode = HttpStatus.internalServerError;
}
paintErrorIcon(request);
await request.response.close();
}
}
@ -103,16 +106,16 @@ class WrapperServer {
return;
}
if (path.startsWith(WrapperPaths.documents)) {
return _storedFile(
return await _storedFile(
request,
'documents',
path.substring(WrapperPaths.documents.length),
);
}
if (path == kSyncAccountPath) {
return _syncAccount(request);
return await _syncAccount(request);
}
return _static(request, path);
return await _static(request, path);
}
/// Serves the shared sync account so a desktop install can self-provision.
@ -218,37 +221,10 @@ class WrapperServer {
await request.response.addStream(file.openRead());
}
/// Content type for [filePath].
/// Content type for [filePath]. See `content_types.dart`.
///
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
/// served as anything but `application/wasm`, and the app then renders
/// nothing at all.
static ContentType contentTypeFor(String filePath) {
switch (p.extension(filePath).toLowerCase()) {
case '.html':
return ContentType.html;
case '.js' || '.mjs':
return ContentType('text', 'javascript', charset: 'utf-8');
case '.json':
return ContentType.json;
case '.wasm':
return ContentType('application', 'wasm');
case '.css':
return ContentType('text', 'css', charset: 'utf-8');
case '.png':
return ContentType('image', 'png');
case '.jpg' || '.jpeg':
return ContentType('image', 'jpeg');
case '.svg':
return ContentType('image', 'svg+xml');
case '.ttf':
return ContentType('font', 'ttf');
case '.otf':
return ContentType('font', 'otf');
case '.woff2':
return ContentType('font', 'woff2');
default:
return ContentType.binary;
}
}
/// Kept as a static forwarder so callers and tests that reach for
/// `WrapperServer.contentTypeFor` keep working after the split.
static ContentType contentTypeFor(String filePath) =>
content_types.contentTypeFor(filePath);
}

View File

@ -2,29 +2,62 @@
/// background due-slot check, then shows the primary meal-logging screen.
library;
import 'dart:async';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show AppErrors, AppErrorsConfig, AppErrorsRouteObserver, installAppErrors;
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/claude_relay_firebase.dart';
import 'package:diet_guard_app/services/firebase_client.dart' show openFirebase;
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:material_ui/material_ui.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// Every error and every wait over 1 s goes to the PC's app-errors ingest,
// which files a board ticket (kuhyx/utils DOCS-app-errors.md). The release
// build passes the versionCode and name as dart-defines (release-apk.yml).
final errors = await installAppErrors(
const AppErrorsConfig(
app: 'diet-guard',
repo: 'kuhyx/diet-guard',
package: 'diet_guard_app',
// 0 unless the release build passes --dart-define=APP_BUILD.
// ignore: avoid_redundant_argument_values
build: int.fromEnvironment('APP_BUILD'),
version: String.fromEnvironment('APP_VERSION'),
),
);
// Before anything that stamps an Hlc or syncs: until this resolves, the
// device id falls back to the pre-migration role constant.
await initSyncDeviceId();
final deviceId = await initSyncDeviceId();
errors.connect(
sink: () async => (await openFirebase())?.patchValues,
deviceId: () async => deviceId,
);
await LogStorageService.init();
await AppSettingsService.init();
await BudgetHistoryService.init();
await MealScheduleService.init();
await FoodBankService.init();
await KuchniaCredentialService.init();
await BodyService.init();
await KuchniaQueueService.init();
// The sparkle button's transport; until this line it fails closed.
claudeRelay = RtdbClaudeRelay.firebase();
final notifications = await NotificationService.init();
// Deliberately *not* awaited before the first frame: the browser's
// `Notification.requestPermission()` does not complete until the user
@ -44,19 +77,25 @@ Future<void> main() async {
// coverage:ignore-start
if (frameStatsEnabled) startFrameStats();
// coverage:ignore-end
runApp(const DietGuardApp());
runApp(DietGuardApp(errors: errors));
}
/// Root widget for the Diet Guard companion app.
class DietGuardApp extends StatelessWidget {
/// Creates the [DietGuardApp] root widget.
const DietGuardApp({super.key});
const DietGuardApp({this.errors, super.key});
/// App-wide error reporting; null in widget tests.
final AppErrors? errors;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Diet Guard',
theme: buildAppTheme(),
navigatorObservers: [
if (errors case final errors?) AppErrorsRouteObserver(errors),
],
home: const LogMealScreen(),
);
}

View File

@ -0,0 +1,142 @@
/// The synced Body document: profile, per-day weights, published workouts.
///
/// Same JSON shape as `~/.local/share/diet_guard/body.json` on the PC (see
/// `docs/DOCS-body.md`). Every field carries its own edit stamp `t`, which is
/// what the sync merge derives its clocks from. Parsing is tolerant: a
/// malformed part is dropped, never raised, so one bad field from a peer
/// cannot take out the rest.
library;
import 'package:diet_guard_app/models/body_entries.dart';
export 'package:diet_guard_app/models/body_entries.dart';
/// Profile field names.
const String profileBirth = 'birth';
/// Profile height field.
const String profileHeight = 'height_cm';
/// Profile sex field (`m` / `f`).
const String profileSex = 'sex';
/// The whole document.
class BodyDocument {
/// Creates a document.
const BodyDocument({
this.profile = const {},
this.weights = const {},
this.bodyFat = const {},
this.steps = const {},
this.activity,
});
/// Parses the local document JSON (already decoded).
factory BodyDocument.fromJson(Object? raw) {
if (raw is! Map) return const BodyDocument();
final profile = <String, Stamped>{};
final rawProfile = raw['profile'];
// Every stamped field is kept, known or not: a field a newer peer added
// (the table prefs were one) must survive this device's re-push.
if (rawProfile is Map) {
rawProfile.forEach((name, field) {
if (name is String && field is Map && field['t'] is String) {
profile[name] = Stamped(field['v'], field['t'] as String);
}
});
}
final weights = <String, WeightEntry>{};
final rawWeights = raw['weights'];
if (rawWeights is Map) {
rawWeights.forEach((day, value) {
final entry = parseWeightValue(value, value is Map ? value['t'] : null);
if (isDateKey(day) && entry != null) weights[day as String] = entry;
});
}
final bodyFat = <String, BodyFatEntry>{};
final rawFat = raw['bodyfat'];
if (rawFat is Map) {
rawFat.forEach((day, value) {
final t = value is Map ? value['t'] : null;
final entry = parseBodyFatValue(value, t);
if (isDateKey(day) && entry != null) bodyFat[day as String] = entry;
});
}
final steps = <String, StepsEntry>{};
final rawSteps = raw['steps'];
if (rawSteps is Map) {
rawSteps.forEach((day, value) {
final t = value is Map ? value['t'] : null;
final entry = parseStepsValue(value, t);
if (isDateKey(day) && entry != null) steps[day as String] = entry;
});
}
final rawActivity = raw['activity'];
ActivityData? activity;
if (rawActivity is Map &&
rawActivity['sessions'] is List &&
rawActivity['t'] is String) {
activity = ActivityData(
sessions: List<Object?>.from(rawActivity['sessions'] as List),
t: rawActivity['t'] as String,
);
}
return BodyDocument(
profile: profile,
weights: weights,
bodyFat: bodyFat,
steps: steps,
activity: activity,
);
}
/// Profile fields by name.
final Map<String, Stamped> profile;
/// Weights by `YYYY-MM-DD`.
final Map<String, WeightEntry> weights;
/// Body fat readings by `YYYY-MM-DD`.
final Map<String, BodyFatEntry> bodyFat;
/// Steps outside workouts by `YYYY-MM-DD` (written by the phone).
final Map<String, StepsEntry> steps;
/// Workouts published by the PC, or null when none ever were.
final ActivityData? activity;
/// Returns a copy with the given parts replaced.
BodyDocument copyWith({
Map<String, Stamped>? profile,
Map<String, WeightEntry>? weights,
Map<String, BodyFatEntry>? bodyFat,
Map<String, StepsEntry>? steps,
ActivityData? activity,
}) => BodyDocument(
profile: profile ?? this.profile,
weights: weights ?? this.weights,
bodyFat: bodyFat ?? this.bodyFat,
steps: steps ?? this.steps,
activity: activity ?? this.activity,
);
/// JSON form of the local document.
Map<String, Object?> toJson() => {
'v': 1,
'profile': {
for (final entry in profile.entries)
entry.key: {'v': entry.value.value, 't': entry.value.t},
},
'weights': {
for (final entry in weights.entries) entry.key: entry.value.toJson(),
},
'bodyfat': {
for (final entry in bodyFat.entries) entry.key: entry.value.toJson(),
},
'steps': {
for (final entry in steps.entries) entry.key: entry.value.toJson(),
},
if (activity != null)
'activity': {'sessions': activity!.sessions, 't': activity!.t},
};
}

View File

@ -0,0 +1,132 @@
/// The Body document's parts: stamped values, dated entries, parsers.
///
/// Split out of `body_document.dart` for the 250-line cap; that file
/// re-exports this one, so importers see no change. Parsing is tolerant: a
/// malformed part is dropped (null), never raised.
library;
/// A value and the ISO time it was last edited.
class Stamped {
/// Creates a stamped value.
const Stamped(this.value, this.t);
/// The value.
final Object? value;
/// ISO-8601 edit time.
final String t;
}
/// One day's weight. [kg] null is a tombstone (a deleted day).
class WeightEntry {
/// Creates an entry.
const WeightEntry({required this.kg, required this.src, required this.t});
/// Kilograms, or null when deleted.
final double? kg;
/// `phone`, `manual` or `init`.
final String src;
/// ISO-8601 edit time.
final String t;
/// JSON form of the local document.
Map<String, Object?> toJson() => {'kg': kg, 'src': src, 't': t};
}
/// One day's body fat %. [pct] null is a tombstone (a deleted day).
class BodyFatEntry {
/// Creates an entry.
const BodyFatEntry({required this.pct, required this.t});
/// Percent, or null when deleted.
final double? pct;
/// ISO-8601 edit time.
final String t;
/// JSON form of the local document.
Map<String, Object?> toJson() => {'pct': pct, 't': t};
}
/// One day's steps outside workouts, as the phone read them.
class StepsEntry {
/// Creates an entry.
const StepsEntry({required this.n, required this.t});
/// Step count.
final int n;
/// ISO-8601 edit time.
final String t;
/// JSON form of the local document.
Map<String, Object?> toJson() => {'n': n, 't': t};
}
/// Workouts published by the PC.
class ActivityData {
/// Creates the published activity.
const ActivityData({required this.sessions, required this.t});
/// Raw session objects, as on the wire.
final List<Object?> sessions;
/// ISO-8601 time the PC last changed them.
final String t;
}
/// Parses an ISO stamp to epoch milliseconds; unparsable -> 0 (the epoch).
int stampMillis(String t) => DateTime.tryParse(t)?.millisecondsSinceEpoch ?? 0;
/// Whether [raw] is a usable weight in kilograms.
bool plausibleKg(Object? raw) => raw is num && raw >= 20 && raw <= 400;
/// Body fat below/above this (%) is a typo, not a measurement.
const double minBodyFat = 3;
/// Upper bound of a plausible body fat %.
const double maxBodyFat = 70;
/// Whether [raw] is a usable body fat %.
bool plausibleBodyFat(Object? raw) =>
raw is num && raw >= minBodyFat && raw <= maxBodyFat;
final RegExp _dateKey = RegExp(r'^\d{4}-\d{2}-\d{2}$');
/// Whether [raw] is a `YYYY-MM-DD` date key.
bool isDateKey(Object? raw) => raw is String && _dateKey.hasMatch(raw);
/// Parses a weight value `{kg, src}` stamped [t], or null when malformed.
///
/// `kg` must be null (a tombstone) or a plausible number.
WeightEntry? parseWeightValue(Object? value, Object? t) {
if (value is! Map || t is! String) return null;
final kg = value['kg'];
if (kg != null && !plausibleKg(kg)) return null;
final src = value['src'];
return WeightEntry(
kg: (kg as num?)?.toDouble(),
src: src is String ? src : 'manual',
t: t,
);
}
/// Parses a body-fat value `{pct}` stamped [t], or null when malformed.
///
/// `pct` must be null (a tombstone) or a plausible number.
BodyFatEntry? parseBodyFatValue(Object? value, Object? t) {
if (value is! Map || t is! String) return null;
final pct = value['pct'];
if (pct != null && !plausibleBodyFat(pct)) return null;
return BodyFatEntry(pct: (pct as num?)?.toDouble(), t: t);
}
/// Parses a steps value `{n}` stamped [t], or null when malformed.
StepsEntry? parseStepsValue(Object? value, Object? t) {
if (value is! Map || t is! String) return null;
final n = value['n'];
if (n is! num || n < 0) return null;
return StepsEntry(n: n.toInt(), t: t);
}

View File

@ -2,6 +2,8 @@
library;
import 'package:diet_guard_app/models/meal_component.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
/// One logged meal, as stored in `food_log.json` under its date key.
///
@ -20,7 +22,7 @@ class FoodEntry {
required this.fatG,
required this.source,
this.id,
this.slot,
this.slotMinute,
this.hmac,
this.components,
this.deleted = false,
@ -40,7 +42,7 @@ class FoodEntry {
carbsG: (json['carbs_g'] as num?)?.toDouble() ?? 0,
fatG: (json['fat_g'] as num?)?.toDouble() ?? 0,
source: json['source'] as String? ?? 'manual',
slot: json['slot'] as int?,
slotMinute: entrySlotMinute(json),
hmac: json['hmac'] as String?,
components: (json['components'] as List?)
?.cast<Map<String, dynamic>>()
@ -79,9 +81,26 @@ class FoodEntry {
/// Provenance label (e.g. `"manual"`, `"food bank"`, `"meal"`).
final String source;
/// The meal-slot hour this entry satisfies (8/12/16/20), or null for a
/// snack that counts toward calories but satisfies no slot.
final int? slot;
/// The meal-slot minute of day this entry was logged against (480 for
/// 08:00, 435 for 07:15), or null for a snack that satisfies no slot.
///
/// A *recorded* minute, not a live checkpoint: which slot it satisfies is
/// decided at read time by `satisfiedSlots`, so an entry written under an
/// older schedule still counts after the schedule moves.
///
/// Read through `entrySlotMinute` (`slot_min` wins, else `slot` x 60) and
/// written back through `slotFields`, so a PC entry carrying `slot_min`
/// survives a round trip through this device. Keeping only the hour would
/// make every edit or tombstone republish a stripped copy, and the merge
/// would spread that lossy copy back to the PC.
///
/// Nothing writes null any more -- the "Snack" chip was removed on
/// 2026-08-14 and every remaining writer resolves a concrete slot through
/// `slotForLog`/`slot_for_log` -- but entries already on disk and arriving
/// over sync still carry no `slot` key, so the null case and every
/// `slot != null` filter built on it are load-bearing. Dropping them would
/// make those historical entries retroactively satisfy meal slots.
final int? slotMinute;
/// HMAC signature, present on entries that have passed through the PC's
/// signing step. Never computed on the phone -- it never holds the key.
@ -115,7 +134,7 @@ class FoodEntry {
'carbs_g': carbsG,
'fat_g': fatG,
'source': source,
if (slot != null) 'slot': slot,
..._slotJson(slotMinute),
if (components != null)
'components': components!.map((c) => c.toJson()).toList(),
if (deleted) 'deleted': true,
@ -132,9 +151,26 @@ class FoodEntry {
carbsG: carbsG,
fatG: fatG,
source: source,
slot: slot,
slotMinute: slotMinute,
hmac: hmac,
components: components,
deleted: true,
);
}
/// Returns the wire fields for [minute], total over every value it can hold.
///
/// [slotFields] throws outside the day, but [entrySlotMinute] does not
/// range-check what a peer sent. A single `slot: 24` arriving over sync would
/// otherwise make every later `writeLog` throw -- one bad entry blocking all
/// logging. Such a value is echoed back unrepaired, by the same whole-hour
/// rule (so a legacy `slot: 24` stays byte-identical), with `~/` only on a
/// non-negative operand -- a negative value travels as `slot_min` alone.
Map<String, int> _slotJson(int? minute) {
if (minute == null) return const {};
if (minute >= 0 && minute < kMinutesPerDay) return slotFields(minute);
return {
if (minute >= 0) 'slot': minute ~/ 60,
if (minute < 0 || minute % 60 != 0) 'slot_min': minute,
};
}

View File

@ -0,0 +1,97 @@
/// One delivered catering dish, with its portion macros.
///
/// The Dart mirror of `diet_guard/_kuchnia_parse.py`'s `Dish`. Every macro is
/// the total *for this portion*, not per 100 g -- the same convention
/// [Nutrition] uses.
///
/// KEEP IN SYNC WITH `diet_guard/_kuchnia_parse.py`. Both sides are gated by
/// `tests/fixtures/kuchnia_day.json`; see `kuchnia_parity_test.dart`.
library;
/// A dish the caterer delivered on a given day.
class KuchniaDish {
/// Creates a dish from its already-validated fields.
const KuchniaDish({
required this.name,
required this.kcal,
required this.proteinG,
required this.carbsG,
required this.fatG,
required this.grams,
required this.priority,
required this.slotLabel,
this.dishId = '',
});
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
///
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse
/// every Monday dinner onto one food-bank entry.
final String name;
/// Calories for this portion.
final double kcal;
/// Protein in grams, for this portion.
final double proteinG;
/// Carbohydrate in grams, for this portion.
final double carbsG;
/// Fat in grams, for this portion.
final double fatG;
/// The portion weight in grams (`nutrition.weight`).
final double grams;
/// The caterer's own eating order, 1..N.
///
/// Falls back to the dish's 1-based position in the payload when
/// `mealPriority` is missing.
final int priority;
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
final String slotLabel;
/// The panel's own id for this meal (`deliveryMealId`), as a string, or ''
/// when the payload carried none.
///
/// Never written to the bank record or the log: it only feeds [autologKey].
final String dishId;
/// The dish half of the auto-log entry id: [dishId], else [bankKey].
///
/// Mirrors the fixture `tests/fixtures/kuchnia_autolog_ids.json`.
String get autologKey => dishId.isNotEmpty ? dishId : bankKey;
/// The curated-bank record for this dish.
///
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
/// ranks foods by how often they were *eaten*, and a delivered dish has not
/// been eaten yet.
///
/// Every macro is declared `double` on this class rather than `num`, which
/// is what keeps the encoded record byte-identical to Python's.
/// `jsonEncode(435)` emits `435` where Python emits `435.0`, and a
/// byte-different record for the same dish makes every refresh look like a
/// change -- which republishes the whole curated bank to every peer. A
/// `.toDouble()` here would be a no-op the analyzer flags; the field types
/// are the guarantee, and `kuchnia_parity_test.dart` asserts the encoding.
Map<String, dynamic> toBankRecord() => {
'desc': name,
'kcal': kcal,
'protein_g': proteinG,
'carbs_g': carbsG,
'fat_g': fatG,
'grams': grams,
'count': 0,
};
/// The curated bank's key for this dish.
///
/// Python uses `str.casefold()` and this uses `String.toLowerCase()`. They
/// agree across the whole Polish alphabet and diverge only on `ß`,
/// ligatures and final sigma; rekeying to unify them would strand every
/// existing entry, so the agreement is pinned by test instead.
String get bankKey => name.trim().toLowerCase();
}

View File

@ -0,0 +1,216 @@
/// The user's eating window and meal count, and the slot minutes they imply.
///
/// A schedule is three numbers -- the first meal's minute of day, the last
/// meal's minute of day, and how many meals fall between them inclusive --
/// from which the intermediate checkpoints are derived by even division and
/// rounded to the 15-minute grid. `MealSchedule(firstMinute: 480,
/// lastMinute: 1200, count: 5)` yields `[480, 660, 840, 1020, 1200]`.
///
/// Every time here is a *minute of day*, an int in `0..1439`. The fields are
/// deliberately named `firstMinute`/`lastMinute` rather than reusing the old
/// hour-valued `first`/`last`, so `flutter analyze` enumerates every call site
/// that still thinks in hours.
///
/// This file is pure: no clock, no storage, no settings lookup. Persistence
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
/// that consumes a schedule lives in `models/slot.dart`.
///
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on
/// every input, because a device that derives different slots than its peer
/// nags for checkpoints the other never offers -- and a slot that can never be
/// satisfied is a permanent lock. `tests/fixtures/meal_schedule_vectors.json`
/// is read by both test suites; three rules make that agreement checkable:
///
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`)
/// while Python's is banker's rounding (`round(2.5) == 2`), so any
/// floating-point path is a latent cross-language split brain. `~/` here,
/// `//` there.
/// * **Non-negative operands to every division.** `~/` truncates while
/// Python's `//` floors (`-7 ~/ 15 == 0`, `-7 // 15 == -1`). Every division
/// below runs on a value [MealSchedule.normalized] has pulled into the day.
/// * **Clamp, don't reject.** Every out-of-range input is normalised to the
/// nearest legal schedule rather than throwing, so the two languages cannot
/// disagree about which inputs are errors.
library;
import 'package:flutter/foundation.dart';
/// Fewest meals a schedule may describe.
const int kMinMealCount = 2;
/// Most meals a schedule may describe.
///
/// Bounded by legibility, not nutrition: the pills that render these have to
/// stay readable on a phone at their widest (all-logged) size -- see
/// `test/widgets/slot_selector_row_test.dart`.
const int kMaxMealCount = 6;
/// Minutes in a day; a minute of day is `0..kMinutesPerDay - 1`.
const int kMinutesPerDay = 1440;
/// Minimum spacing between two checkpoints, and the grid interior checkpoints
/// are rounded onto.
///
/// One constant for both is what makes the strict-ascent proof in
/// [MealSchedule.slots] work: points at least one grid step apart cannot round
/// onto the same grid mark.
const int kSlotGridMinutes = 15;
/// Grace period after the final checkpoint, before the gate stops firing.
///
/// Deliberately a constant rather than the slot spacing: it is how long you
/// have to log a late dinner, which has nothing to do with how many meals you
/// eat. Tying it to the spacing would stretch the lockout window to midnight
/// at four meals, contradicting the "don't trap me overnight" intent.
const int kEnforcementTailMinutes = 120;
const int _lastMinute = kMinutesPerDay - 1;
int _clamp(int value, int low, int high) =>
value < low ? low : (value > high ? high : value);
/// An eating window and the number of meals inside it.
@immutable
class MealSchedule {
/// Creates a [MealSchedule].
const MealSchedule({
required this.firstMinute,
required this.lastMinute,
required this.count,
});
/// Minute of day of the first meal, 0-1424.
final int firstMinute;
/// Minute of day of the last meal, at least one grid step (15 minutes) after
/// [firstMinute] and at most 1439.
final int lastMinute;
/// Total meals including both endpoints.
final int count;
/// Returns an equivalent schedule guaranteed to satisfy the invariants.
///
/// Ordering matters: [firstMinute] is clamped into the day leaving room for
/// one grid step, then [lastMinute] is clamped to at least one grid step
/// after it, then [count] is clamped to how many grid-spaced checkpoints the
/// window holds. That last clamp is the load-bearing one -- see [slots].
MealSchedule normalized() {
final first = _clamp(firstMinute, 0, _lastMinute - kSlotGridMinutes);
final last = _clamp(lastMinute, first + kSlotGridMinutes, _lastMinute);
// A window of W minutes holds at most W ~/ 15 + 1 checkpoints spaced a
// grid step apart; asking for more would round two onto one mark.
final capacity = (last - first) ~/ kSlotGridMinutes + 1;
final normCount = _clamp(
count,
kMinMealCount,
kMaxMealCount < capacity ? kMaxMealCount : capacity,
);
return MealSchedule(firstMinute: first, lastMinute: last, count: normCount);
}
/// Returns the meal-slot minutes, ascending, with both endpoints exact.
///
/// With `span = last - first` and `d = count - 1`, interior slot *i* is
/// `raw = first + (i*span + d ~/ 2) ~/ d` (even division, the `d ~/ 2` term
/// a round-half-up bias that keeps it free of floating point), then snapped
/// to the nearest absolute quarter hour by `(raw + 7) ~/ 15 * 15`. The
/// endpoints are [firstMinute] and [lastMinute] exactly -- never snapped.
///
/// Strictly ascending, provably: [normalized] caps [count] so that
/// `span / d >= 15`, hence consecutive `raw` values differ by at least 15,
/// and two integers at least 15 apart never snap onto the same grid mark.
/// Snapping moves a value by at most 7, so no interior slot can reach an
/// endpoint. That matters because slot minutes are set members, map keys
/// *and* notification ids: a repeat silently drops a checkpoint.
List<int> slots() {
final schedule = normalized();
final first = schedule.firstMinute;
final last = schedule.lastMinute;
final span = last - first;
final divisions = schedule.count - 1;
return [
first,
for (var index = 1; index < divisions; index++)
(first + (index * span + divisions ~/ 2) ~/ divisions + 7) ~/
kSlotGridMinutes *
kSlotGridMinutes,
last,
];
}
/// The minute at which slot enforcement stops for the day.
///
/// Derived from the *normalised* last meal, so it always agrees with the
/// last entry of [slots]. Clamped to the end of the day: a 23:00 last meal
/// would otherwise put the cutoff at 1500, making `minute < cutoff`
/// vacuously true so the enforcement window never closes.
int get enforcementEndMinute {
final end = normalized().lastMinute + kEnforcementTailMinutes;
return end < kMinutesPerDay ? end : kMinutesPerDay;
}
@override
bool operator ==(Object other) =>
other is MealSchedule &&
other.firstMinute == firstMinute &&
other.lastMinute == lastMinute &&
other.count == count;
@override
int get hashCode => Object.hash(firstMinute, lastMinute, count);
@override
String toString() => 'MealSchedule($firstMinute-$lastMinute x$count)';
}
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement
/// closing at 22:00. Still what a device uses before the user has chosen
/// anything, so upgrading changes no behaviour.
const MealSchedule kDefaultSchedule = MealSchedule(
firstMinute: 8 * 60,
lastMinute: 20 * 60,
count: 4,
);
/// Returns the synced `sched:<date>` value for [schedule].
///
/// Mirrors `_meal_schedule.schedule_to_wire`. Backward compatible by
/// construction: `f`/`l` carry whole hours exactly as before the move to
/// minutes, and `fm`/`lm` appear only when an endpoint is off the hour, so a
/// whole-hour schedule encodes byte-identically to the old `{f, l, n}` form.
/// Normalised first, so every `~/` runs on a non-negative value.
Map<String, int> scheduleToWire(MealSchedule schedule) {
final norm = schedule.normalized();
final first = norm.firstMinute;
final last = norm.lastMinute;
return {
'f': first ~/ 60,
'l': last ~/ 60,
'n': norm.count,
if (first % 60 != 0) 'fm': first,
if (last % 60 != 0) 'lm': last,
};
}
/// Returns the normalised schedule a `sched:<date>` value describes, or null.
///
/// Mirrors `_meal_schedule.schedule_from_wire`. `fm`/`lm` win when they are
/// ints; otherwise `f`/`l` are hours. Never throws: anything without int `f`,
/// `l` and `n` yields null, so one bad field from a peer cannot take out the
/// whole history.
MealSchedule? scheduleFromWire(Object? raw) {
if (raw is! Map) return null;
final first = raw['f'];
final last = raw['l'];
final count = raw['n'];
if (first is! int || last is! int || count is! int) return null;
final firstMinute = raw['fm'];
final lastMinute = raw['lm'];
return MealSchedule(
firstMinute: firstMinute is int ? firstMinute : first * 60,
lastMinute: lastMinute is int ? lastMinute : last * 60,
count: count,
).normalized();
}

View File

@ -1,84 +1,157 @@
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py`.
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py` and
/// `_slot_wire.py`.
///
/// Deliberately I/O-free and clock-free: every function is a total function
/// of its `now` argument and the fixed slot constants below, so the
/// time-of-day edges are exhaustively unit-testable without mocking the
/// wall clock. Shared between the in-app status bar and the background
/// notification check (Milestone 4), exactly like the Python original is
/// shared between the gate dashboard and the lock decision.
/// Deliberately I/O-free and clock-free: every function is a total function of
/// its `now` and `schedule` arguments, so the time-of-day edges are
/// exhaustively unit-testable without mocking the wall clock. Shared between
/// the in-app status row and the background notification check, exactly like
/// the Python original is shared between the gate dashboard and the lock
/// decision.
///
/// A slot is a *minute of day* (`0..1439`): 480, 720, 960, 1200 by default.
/// A logged meal satisfies the slot nearest its recorded slot minute
/// ([satisfiedSlots]), so an entry written under an older schedule still
/// counts after the schedule moves -- nothing stored is ever rewritten.
///
/// `schedule` is a required argument on every function here, deliberately: it
/// used to be read from module constants, and a default would let a call site
/// that was missed during a refactor keep deriving the old fixed hours on one
/// device only. That is the split brain this design exists to prevent -- a
/// slot one device offers and the other does not is a checkpoint that can
/// never be satisfied. Callers resolve the value at the impure edge, through
/// `MealScheduleService.current`.
///
/// **Entry wire rule** (mirrors `_slot_wire.py`): writers always write
/// `slot = minute ~/ 60` and add `slot_min = minute` only when the minute is
/// off the hour, so whole-hour entries stay byte-identical to the pre-minute
/// format and an older peer still reads an hour. Readers prefer an int
/// `slot_min`, then `slot * 60`, else no slot. See [slotFields] and
/// [entrySlotMinute]; `tests/fixtures/meal_schedule_vectors.json` gates both
/// languages.
library;
/// First slot hour of the day (08:00), mirrors `GATE_DAY_START_HOUR`.
const int gateDayStartHour = 8;
import 'package:diet_guard_app/models/meal_schedule.dart';
/// Hours between slots, mirrors `GATE_SLOT_INTERVAL_HOURS`.
const int gateSlotIntervalHours = 4;
/// Returns [now]'s minute of day, `0..1439` (seconds are ignored).
///
/// Mirrors `_slots.minute_of_day`.
int minuteOfDay(DateTime now) => now.hour * 60 + now.minute;
/// Exclusive end of the enforcement window (22:00), mirrors
/// `GATE_EATING_END_HOUR`.
const int gateEatingEndHour = 22;
/// Returns the fixed meal-slot hours for a day, e.g. `(8, 12, 16, 20)`.
/// Returns the meal-slot minutes for a day, e.g. `[480, 720, 960, 1200]`.
///
/// Mirrors `_slots.day_slots`.
List<int> daySlots() {
final slots = <int>[];
for (
var hour = gateDayStartHour;
hour < gateEatingEndHour;
hour += gateSlotIntervalHours
) {
slots.add(hour);
}
return slots;
}
List<int> daySlots(MealSchedule schedule) => schedule.slots();
/// Returns true if [now] is inside the daily slot-enforcement window.
///
/// Mirrors `_slots.within_enforcement_window`.
bool withinEnforcementWindow(DateTime now) =>
now.hour >= gateDayStartHour && now.hour < gateEatingEndHour;
/// Returns today's slots whose hour has arrived as of [now].
///
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
List<int> elapsedSlots(DateTime now) {
if (!withinEnforcementWindow(now)) return const [];
return daySlots().where((slot) => slot <= now.hour).toList();
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) {
final minute = minuteOfDay(now);
return schedule.slots().first <= minute &&
minute < schedule.enforcementEndMinute;
}
/// Returns elapsed slots not yet covered by [logged].
/// Returns today's slots whose minute has arrived as of [now].
///
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
List<int> elapsedSlots(DateTime now, MealSchedule schedule) {
if (!withinEnforcementWindow(now, schedule)) return const [];
final minute = minuteOfDay(now);
return daySlots(schedule).where((slot) => slot <= minute).toList();
}
/// Returns elapsed slots not yet covered by [logged] (normally
/// [satisfiedSlots] of the entries' slot minutes).
///
/// Mirrors `_slots.missing_slots`.
List<int> missingSlots(DateTime now, Set<int> logged) =>
elapsedSlots(now).where((slot) => !logged.contains(slot)).toList();
List<int> missingSlots(DateTime now, Set<int> logged, MealSchedule schedule) =>
elapsedSlots(
now,
schedule,
).where((slot) => !logged.contains(slot)).toList();
/// Returns the most recent elapsed slot as of [now], or null.
///
/// Mirrors `_slots.current_slot`.
int? currentSlot(DateTime now) {
final elapsed = elapsedSlots(now);
int? currentSlot(DateTime now, MealSchedule schedule) {
final elapsed = elapsedSlots(now, schedule);
return elapsed.isEmpty ? null : elapsed.last;
}
/// Returns the slot a meal logged at [now] should be attributed to.
///
/// CLAMP RULE (keep byte-identical with `_slots.slot_for_log`): before the
/// first window, clamp to the first slot; after the last window, clamp to the
/// last slot; behaviour inside a window is unchanged.
/// first slot, clamp to the first slot; after the enforcement window ends,
/// clamp to the last slot; behaviour inside a window is unchanged. The two
/// languages must reach each answer by the *same* branch, not merely agree on
/// the value -- the shared fixture pins every minute edge for that reason.
///
/// Unlike [currentSlot] this never returns null, which is the point: an
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or
/// 22:30 still produced a "you haven't logged your meal" reminder. Attribution
/// is deliberately separate from [elapsedSlots]/[missingSlots] -- widening
/// *those* would instead make every slot fall due at 23:00.
int slotForLog(DateTime now) {
final slots = daySlots();
if (now.hour < gateDayStartHour) return slots.first;
return currentSlot(now) ?? slots.last;
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
/// still produced a "you haven't logged your meal" reminder. Attribution is
/// deliberately separate from [elapsedSlots]/[missingSlots] -- widening
/// *those* would instead make every slot fall due at the end of the day.
int slotForLog(DateTime now, MealSchedule schedule) {
final slots = daySlots(schedule);
if (minuteOfDay(now) < slots.first) return slots.first;
return currentSlot(now, schedule) ?? slots.last;
}
/// Returns a human `HH:00` label for [slot], e.g. `"08:00"`.
/// Returns the slot closest to [minute]; an exact tie goes to the earlier.
///
/// Mirrors `_slots.nearest_slot`, whose `min` keeps the first minimal element
/// of the ascending slots -- hence replacing the best only on a strictly
/// smaller distance here.
int nearestSlot(int minute, MealSchedule schedule) {
final slots = daySlots(schedule);
var best = slots.first;
for (final slot in slots) {
if ((slot - minute).abs() < (best - minute).abs()) best = slot;
}
return best;
}
/// Returns the slots covered by meals recorded at [entryMinutes].
///
/// Mirrors `_slots.satisfied_slots`. Many-to-one is intended: two meals
/// snapping onto one slot satisfy only that slot.
Set<int> satisfiedSlots(Iterable<int> entryMinutes, MealSchedule schedule) => {
for (final minute in entryMinutes) nearestSlot(minute, schedule),
};
/// Returns the entry fields that record [minute] as its slot.
///
/// Mirrors `_slot_wire.slot_fields`; throws [ArgumentError] for a minute
/// outside the day, as Python raises `ValueError`.
Map<String, int> slotFields(int minute) {
if (minute < 0 || minute >= kMinutesPerDay) {
throw ArgumentError.value(
minute,
'minute',
'slot minute is outside 0..${kMinutesPerDay - 1}',
);
}
return {'slot': minute ~/ 60, if (minute % 60 != 0) 'slot_min': minute};
}
/// Returns the slot minute a raw log entry records, or null when it has none.
///
/// Mirrors `_slot_wire.entry_slot_minute`: an int `slot_min` wins, else an int
/// `slot` is an hour, else null. Values are not range-checked.
int? entrySlotMinute(Map<String, Object?> entry) {
final slotMin = entry['slot_min'];
if (slotMin is int) return slotMin;
final slot = entry['slot'];
if (slot is int) return slot * 60;
return null;
}
/// Returns a human `HH:MM` label for a slot minute, e.g. `"07:15"`.
///
/// Mirrors `_slots.slot_label`.
String slotLabel(int slot) => '${(slot % 24).toString().padLeft(2, '0')}:00';
String slotLabel(int minute) {
final wrapped = minute % kMinutesPerDay;
final hours = (wrapped ~/ 60).toString().padLeft(2, '0');
final minutes = (wrapped % 60).toString().padLeft(2, '0');
return '$hours:$minutes';
}

View File

@ -0,0 +1,72 @@
/// One published workout, as the PC syncs it in the Body document.
///
/// Split out of `services/activity_kcal.dart` for the 250-line cap; that
/// file re-exports it, so importers see no change. Parsing is tolerant: a
/// malformed session is dropped, an unparsable time reads as null.
library;
/// One workout, reduced to what the energy formulas need.
class Session {
/// Creates a session.
const Session({
required this.day,
required this.kind,
required this.minutes,
required this.km,
required this.label,
required this.source,
this.start,
this.end,
});
/// Parses the synced wire object (`day, kind, min, km, label, src`), or
/// null when it is malformed.
static Session? fromWire(Object? raw) {
if (raw is! Map) return null;
final day = raw['day'];
final kind = raw['kind'];
final minutes = raw['min'];
final km = raw['km'];
if (day is! String || kind is! String || minutes is! num) return null;
if (km != null && km is! num) return null;
return Session(
day: day,
kind: kind,
minutes: minutes.toDouble(),
km: (km as num?)?.toDouble(),
label: raw['label'] is String ? raw['label'] as String : kind,
source: raw['src'] is String ? raw['src'] as String : '',
start: _stampOrNull(raw['start']),
end: _stampOrNull(raw['end']),
);
}
/// Local `YYYY-MM-DD` the workout happened on.
final String day;
/// `strength`, `run`, `walk`, `cycle` or `other`.
final String kind;
/// Duration in minutes.
final double minutes;
/// Distance, or null when the source has none.
final double? km;
/// Human description.
final String label;
/// Where it came from (`runnerup`, `screen-locker`).
final String source;
/// ISO start time, when the source knows it.
final String? start;
/// ISO end time, when the source knows it. The phone drops Health
/// Connect steps inside `start..end`, so a walk is not counted twice.
final String? end;
}
/// An ISO time string, or null when absent or unparsable.
String? _stampOrNull(Object? value) =>
value is String && DateTime.tryParse(value) != null ? value : null;

View File

@ -0,0 +1,247 @@
/// The Body screen: the goal sentence first, then weight (+ graph), BMI,
/// ideal weight, BMR, measured activity and steps, the week planner, the
/// profile (at the top instead while incomplete), and body fat last.
///
/// The phone half of the PC gate's Body tab (`_gatelock_body*.py`), reading
/// the same synced `body.json` (see `docs/DOCS-body.md`). **Informational
/// only**: nothing here writes the daily budget -- there is deliberately no
/// "apply" button.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/body_screen_data.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/body_calc.dart';
import 'package:diet_guard_app/services/body_energy.dart';
import 'package:diet_guard_app/services/body_prefs.dart';
import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/health_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/activity_card.dart';
import 'package:diet_guard_app/widgets/body/body_section.dart';
import 'package:diet_guard_app/widgets/body/body_stats_cards.dart';
import 'package:diet_guard_app/widgets/body/body_tile_grid.dart';
import 'package:diet_guard_app/widgets/body/goal_card.dart';
import 'package:diet_guard_app/widgets/body/profile_card.dart';
import 'package:diet_guard_app/widgets/body/week_plan_card.dart';
import 'package:diet_guard_app/widgets/body/weight_card.dart';
import 'package:material_ui/material_ui.dart';
export 'package:diet_guard_app/screens/body_screen_data.dart';
/// The Body screen.
class BodyScreen extends StatefulWidget {
/// Creates the screen.
const BodyScreen({super.key});
@override
State<BodyScreen> createState() => _BodyScreenState();
}
class _BodyScreenState extends State<BodyScreen> {
Map<String, double> _logged = const {};
/// Decided once, when the screen opens: a complete profile sits at the
/// bottom, an incomplete one at the top. Re-deciding on every build would
/// yank the card away mid-edit the moment the last field is saved; it
/// moves the next time the screen is entered.
late final bool _profileAtTop = !BodyService.instance.profileComplete;
/// Whether the Health Connect button shows: supported and not yet granted.
///
/// A notifier, not a bool: the Activity sheet stays open while the
/// permission is granted, and its button must disappear and its numbers
/// refresh without reopening the sheet.
final ValueNotifier<bool> _canConnectSteps = ValueNotifier(false);
@override
void dispose() {
_canConnectSteps.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
unawaited(_loadLog());
unawaited(_loadSteps());
}
/// Refreshes steps (only when already permitted -- never prompts) and
/// decides whether to offer the connect button.
Future<void> _loadSteps() async {
final source = stepsSource;
if (!source.supported) return;
final granted = await source.hasPermission().catchError((_) => false);
if (granted) await refreshSteps();
if (!mounted) return;
_canConnectSteps.value = !granted;
setState(() {});
}
Future<void> _connectSteps() async {
final granted = await stepsSource.requestPermission().catchError(
(_) => false,
);
if (granted) await refreshSteps();
if (!mounted) return;
_canConnectSteps.value = !granted;
setState(() {});
}
Future<void> _loadLog() async {
final log = await LogStorageService.instance.readLog();
if (!mounted) return;
setState(() => _logged = kcalByDay(log));
}
/// Any profile/weight write changes every derived card; the cards read
/// [BodyService] in `build`, so a rebuild is all they need.
void _onChanged() => setState(() {});
@override
Widget build(BuildContext context) {
final body = BodyService.instance;
final today = DateTime.now();
final bio = currentBiometrics(body, today);
final (exercise, _, _) = bodyExercise(body, bio, today);
final tiles = _tiles(body, bio, exercise);
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: BodyTileGrid(tiles: tiles),
),
),
),
);
}
/// The Activity card from the live service state.
Widget _activityCard({required bool canConnect}) {
final body = BodyService.instance;
final (exercise, stepsKcal, window) = bodyExercise(
body,
currentBiometrics(body, DateTime.now()),
DateTime.now(),
);
return ActivityCard(
sessions: body.sessions,
weightKg: body.latestWeight?.$2,
exercise: exercise,
steps: stepsByDay(body),
stepsKcal: stepsKcal,
window: window,
onConnectSteps: canConnect ? _connectSteps : null,
);
}
/// Every section as a tile: the profile first while it is incomplete, last
/// otherwise (decided once, see [_profileAtTop]).
List<BodyTileSpec> _tiles(
BodyService body,
Biometrics? bio,
Map<String, double>? exercise,
) {
final weight = body.latestWeight?.$2;
final bodyFat = body.latestBodyFat?.$2;
final age = bodyAgeText(body, DateTime.now());
final profile = BodyTileSpec(
semanticLabel: 'Profile',
icon: Icons.person,
value: age,
valueIcon: age == null ? null : Icons.cake,
builder: (_) => ProfileCard(onSaved: _onChanged),
);
final goal = bio == null
? null
: goalTarget(
savedGoal(body),
tableBmr(bio, bodyFat).value!,
tableBmr(bio, bodyFat).name,
exercise,
).kcal;
return [
if (_profileAtTop) profile,
BodyTileSpec(
semanticLabel: 'Daily calorie target',
icon: Icons.flag,
value: goal == null ? null : '$goal',
valueIcon: goal == null ? null : MacroKind.kcal.icon,
builder: (_) => bio == null
? BodySection(
semanticLabel: 'Daily calorie target',
children: [
Row(
children: [
for (final icon in bodyMissingIcons(body))
StatusCue(
kind: CueKind.warn,
icon: icon,
semanticLabel: bodyMissingNote(body),
),
],
),
],
)
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
),
BodyTileSpec(
semanticLabel: 'Weight',
icon: Icons.monitor_weight,
value: weight == null ? null : formatKg(weight),
builder: (_) => WeightCard(onChanged: _onChanged),
),
if (bio != null) ...[
BodyTileSpec(
semanticLabel: 'BMI',
icon: Icons.accessibility_new,
value: oneDecimal(bmiReport(bio).bmi),
builder: (_) => BmiCard(bio: bio),
),
BodyTileSpec(
semanticLabel: 'Ideal weight',
icon: Icons.balance,
builder: (_) => IdealWeightCard(bio: bio),
),
BodyTileSpec(
semanticLabel: 'Resting metabolism (BMR)',
icon: Icons.bedtime,
value: whole(tableBmr(bio, bodyFat).value!),
valueIcon: MacroKind.kcal.icon,
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
),
],
BodyTileSpec(
semanticLabel: 'Activity',
icon: Icons.directions_run,
builder: (_) => ValueListenableBuilder<bool>(
valueListenable: _canConnectSteps,
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
),
),
BodyTileSpec(
semanticLabel: 'Week planner',
icon: Icons.calendar_view_week,
builder: (_) => WeekPlanCard(
defaultTarget: AppSettingsService.dailyKcalGoal,
logged: _logged,
),
),
if (!_profileAtTop) profile,
BodyTileSpec(
semanticLabel: 'Body fat',
icon: Icons.percent,
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
builder: (_) => BodyFatCard(onChanged: _onChanged),
),
];
}
}

View File

@ -0,0 +1,88 @@
/// Pure data helpers behind the Body screen (split out for the 250-line cap).
library;
import 'package:diet_guard_app/services/activity_kcal.dart';
import 'package:diet_guard_app/services/body_calc.dart';
import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/body_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:material_ui/material_ui.dart' show IconData, Icons;
/// Builds the person from the stored profile and newest weight, or null
/// when anything the formulas need is missing.
Biometrics? currentBiometrics(BodyService body, DateTime today) {
final birth = DateTime.tryParse(body.birth ?? '');
final height = body.heightCm;
final sex = body.sex;
final weight = body.latestWeight;
if (birth == null || height == null || sex == null || weight == null) {
return null;
}
return Biometrics(
weightKg: weight.$2,
heightCm: height,
ageYears: ageOn(birth, today).toDouble(),
isMale: sex == 'm',
);
}
/// Steps outside workouts by day, as stored.
Map<String, int> stepsByDay(BodyService body) =>
body.document.steps.map((day, entry) => MapEntry(day, entry.n));
/// Mean daily exercise per formula (steps included), the steps' own share,
/// and the number of full days averaged -- like the PC's `_body_view`: the
/// two means are null without a person, or without any published workout
/// or step count.
(Map<String, double>?, double?, int) bodyExercise(
BodyService body,
Biometrics? bio,
DateTime today,
) {
final sessions = body.sessions;
final steps = stepsByDay(body);
if (bio == null || (sessions == null && steps.isEmpty)) {
return (null, null, 0);
}
final byDay = steps.map((day, n) => MapEntry(day, stepKcal(n, bio)));
final weight = bio.weightKg;
final all = sessions ?? const <Session>[];
return (
dailyExercise(all, weight, today, byDay),
extraShare(all, today, byDay),
windowDays(all, today, byDay),
);
}
/// Sums each day's non-deleted kcal.
Map<String, double> kcalByDay(DayLog log) => {
for (final entry in log.entries)
entry.key: entry.value
.where((food) => !food.deleted)
.fold<double>(0, (sum, food) => sum + food.kcal),
};
/// Glyphs of the inputs still missing (profile, weight), in the order the
/// user should supply them; the visible counterpart of [bodyMissingNote].
List<IconData> bodyMissingIcons(BodyService body) => [
if (body.birth == null || body.heightCm == null || body.sex == null)
Icons.person,
if (body.latestWeight == null) Icons.monitor_weight,
];
/// Spoken reason the numbers are missing (screen readers, tests; never
/// painted).
String bodyMissingNote(BodyService body) {
if (body.latestWeight == null && body.birth == null) {
return 'Set your profile and enter your weight to see BMI, ideal '
'weight and calorie targets.';
}
if (body.latestWeight == null) return 'Enter your weight to see the numbers.';
return 'Set your profile (birth date, height, sex) to see the numbers.';
}
/// The age in whole years, or null while no birth date is stored.
String? bodyAgeText(BodyService body, DateTime today) {
final birth = DateTime.tryParse(body.birth ?? '');
return birth == null ? null : '${ageOn(birth, today)}';
}

View File

@ -9,6 +9,7 @@ library;
import 'dart:async';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
import 'package:diet_guard_app/models/day_status.dart';
import 'package:diet_guard_app/models/period_average.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
@ -17,11 +18,13 @@ import 'package:diet_guard_app/services/average_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/widgets/average_summary_row.dart';
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
class CalendarScreen extends StatefulWidget {
@ -101,12 +104,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
/// Opens [HistoryScreen] pre-filtered to the tapped day.
void _onDaySelected(DateTime day) {
unawaited(
Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => HistoryScreen(
initialDateRange: DateTimeRange(start: day, end: day),
),
Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => HistoryScreen(
initialDateRange: DateTimeRange(start: day, end: day),
),
),
);
@ -153,11 +154,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
@override
Widget build(BuildContext context) {
if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
return const Scaffold(body: WaitWatch.centered('calendar.load'));
}
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('Calendar')),
appBar: AppBar(),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
@ -170,11 +170,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
if (_budgetStatus != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
_budgetStatus!,
style: TextStyle(
color: _budgetError ? theme.colorScheme.error : null,
),
child: StatusCue(
key: ValueKey(_budgetStatus),
kind: _budgetError ? CueKind.error : CueKind.ok,
semanticLabel: _budgetStatus!,
),
),
const SizedBox(height: 12),
@ -217,7 +216,11 @@ class _BudgetRow extends StatelessWidget {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Daily budget (kcal):'),
Icon(
MacroKind.kcal.icon,
color: MacroKind.kcal.color,
semanticLabel: 'Daily budget (kcal)',
),
const SizedBox(width: 8),
SizedBox(
width: 90,
@ -232,7 +235,10 @@ class _BudgetRow extends StatelessWidget {
const SizedBox(width: 8),
FilledButton(
onPressed: onEditOrSave,
child: Text(editing ? 'Save' : 'Edit'),
child: Icon(
editing ? Icons.check : Icons.edit,
semanticLabel: editing ? 'Save' : 'Edit',
),
),
],
);

View File

@ -8,14 +8,15 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart';
import 'package:material_ui/material_ui.dart';
import 'package:uuid/uuid.dart';
/// Edit screen for an existing [FoodEntry].
///
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slot],
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slotMinute],
/// and [FoodEntry.deleted]. All nutritional fields and
/// the description are editable.
class EditEntryScreen extends StatefulWidget {
@ -35,12 +36,17 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
List<FoodSuggestion> _suggestions = const [];
String _source = 'manual';
String? _status;
int _rejections = 0;
@override
void initState() {
super.initState();
final e = widget.entry;
_descController = TextEditingController(text: e.desc);
// Same clear-before-fill discipline as `fillControllersFromDish`: the
// entry's macros describe the whole eaten portion, so any reference
// weight left in `perGrams` would rescale them on save.
_macros.clear();
_macros.kcal.text = e.kcal.toStringAsFixed(0);
_macros.protein.text = e.proteinG.toStringAsFixed(0);
_macros.carbs.text = e.carbsG.toStringAsFixed(0);
@ -76,21 +82,17 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
}
Future<void> _onDescChanged() async {
final matches = await FoodBankService.instance.search(
_descController.text,
);
final matches = await FoodBankService.instance.search(_descController.text);
if (!mounted) return;
setState(() => _suggestions = matches);
}
void _onSuggestionSelected(FoodSuggestion suggestion) {
_descController.text = suggestion.name;
_macros.kcal.text = suggestion.nutrition.kcal.toStringAsFixed(0);
_macros.protein.text = suggestion.nutrition.proteinG.toStringAsFixed(0);
_macros.carbs.text = suggestion.nutrition.carbsG.toStringAsFixed(0);
_macros.fat.text = suggestion.nutrition.fatG.toStringAsFixed(0);
_macros.perGrams.text = suggestion.nutrition.grams.toStringAsFixed(0);
_macros.grams.text = suggestion.nutrition.grams.toStringAsFixed(0);
// Routed through `fillFrom` rather than six hand-written assignments, so
// this path and the log screen's cannot drift and neither can forget a
// field. It clears first, so nothing survives from the previous pick.
_macros.fillFrom(suggestion.nutrition);
setState(() {
_source = 'food bank';
_suggestions = const [];
@ -102,7 +104,10 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
Future<void> _onSave() async {
final desc = _descController.text.trim();
if (desc.isEmpty) {
setState(() => _status = 'Description cannot be empty.');
setState(() {
_status = 'Description cannot be empty.';
_rejections++;
});
return;
}
final nutrition = nutritionForPortion(
@ -128,7 +133,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
carbsG: nutrition.carbsG,
fatG: nutrition.fatG,
source: _source,
slot: e.slot,
slotMinute: e.slotMinute,
);
await LogStorageService.instance.updateEntry(e, updated);
final log = await LogStorageService.instance.readLog();
@ -140,17 +145,16 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Edit meal')),
appBar: AppBar(),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
IconField(
icon: Icons.restaurant,
semanticLabel: 'What did you eat?',
controller: _descController,
decoration: const InputDecoration(
labelText: 'What did you eat?',
),
),
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 240),
@ -166,12 +170,20 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
width: double.infinity,
child: ElevatedButton(
onPressed: _onSave,
child: const Text('Save'),
child: const Icon(Icons.check, semanticLabel: 'Save'),
),
),
if (_status != null) ...[
const SizedBox(height: 12),
Text(_status!),
// New key per rejection so a repeat error shakes again.
Align(
alignment: Alignment.centerLeft,
child: StatusCue(
key: ValueKey(_rejections),
kind: CueKind.error,
semanticLabel: _status!,
),
),
],
],
),

View File

@ -1,164 +1,25 @@
/// Food bank browser: lists every entry across the log-derived and manual
/// banks with filtering, sorting, and the ability to add new manual entries.
///
/// The filter model, the filter sheet and the add-entry dialog live under
/// `lib/widgets/food_bank/` (split for the repo's 250-line cap); this file is
/// the screen that wires them together.
library;
import 'dart:async';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:flutter/material.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_record_tile.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_tile_grid.dart';
import 'package:material_ui/material_ui.dart';
// ---------------------------------------------------------------------------
// Filter / sort state
// ---------------------------------------------------------------------------
/// Sort field for the food bank list.
enum FbSortField {
/// Sort alphabetically by name.
name,
/// Sort by calories.
kcal,
/// Sort by protein (g).
protein,
/// Sort by carbohydrates (g).
carbs,
/// Sort by fat (g).
fat,
/// Sort by usage count (most-used first by default).
count,
}
/// Active filter criteria for the food bank list.
class FbFilter {
/// Creates a [FbFilter] with the given criteria.
FbFilter({
this.nameQuery = '',
this.minKcal,
this.maxKcal,
this.minProtein,
this.maxProtein,
this.minCarbs,
this.maxCarbs,
this.minFat,
this.maxFat,
});
/// Substring match on the food name.
String nameQuery;
/// Minimum kcal.
double? minKcal;
/// Maximum kcal.
double? maxKcal;
/// Minimum protein (g).
double? minProtein;
/// Maximum protein (g).
double? maxProtein;
/// Minimum carbs (g).
double? minCarbs;
/// Maximum carbs (g).
double? maxCarbs;
/// Minimum fat (g).
double? minFat;
/// Maximum fat (g).
double? maxFat;
/// True when any criterion is set.
bool get isActive =>
nameQuery.isNotEmpty ||
minKcal != null ||
maxKcal != null ||
minProtein != null ||
maxProtein != null ||
minCarbs != null ||
maxCarbs != null ||
minFat != null ||
maxFat != null;
}
// ---------------------------------------------------------------------------
// Pure filter / sort helper
// ---------------------------------------------------------------------------
/// Filters and sorts [entries] by [filter] and [sortField]/[ascending].
///
/// Exposed as a top-level function for unit tests.
List<FoodBankRecord> applyFbFilter(
List<FoodBankRecord> entries,
FbFilter filter,
FbSortField sortField, {
required bool ascending,
}) {
var result = [...entries];
if (filter.nameQuery.isNotEmpty) {
final q = filter.nameQuery.toLowerCase();
result = result.where((e) => e.desc.toLowerCase().contains(q)).toList();
}
if (filter.minKcal != null) {
result = result.where((e) => e.kcal >= filter.minKcal!).toList();
}
if (filter.maxKcal != null) {
result = result.where((e) => e.kcal <= filter.maxKcal!).toList();
}
if (filter.minProtein != null) {
result = result.where((e) => e.proteinG >= filter.minProtein!).toList();
}
if (filter.maxProtein != null) {
result = result.where((e) => e.proteinG <= filter.maxProtein!).toList();
}
if (filter.minCarbs != null) {
result = result.where((e) => e.carbsG >= filter.minCarbs!).toList();
}
if (filter.maxCarbs != null) {
result = result.where((e) => e.carbsG <= filter.maxCarbs!).toList();
}
if (filter.minFat != null) {
result = result.where((e) => e.fatG >= filter.minFat!).toList();
}
if (filter.maxFat != null) {
result = result.where((e) => e.fatG <= filter.maxFat!).toList();
}
result.sort((a, b) {
int cmp;
switch (sortField) {
case FbSortField.name:
cmp = a.desc.compareTo(b.desc);
case FbSortField.kcal:
cmp = a.kcal.compareTo(b.kcal);
case FbSortField.protein:
cmp = a.proteinG.compareTo(b.proteinG);
case FbSortField.carbs:
cmp = a.carbsG.compareTo(b.carbsG);
case FbSortField.fat:
cmp = a.fatG.compareTo(b.fatG);
case FbSortField.count:
cmp = a.count.compareTo(b.count);
}
return ascending ? cmp : -cmp;
});
return result;
}
// ---------------------------------------------------------------------------
// Screen
// ---------------------------------------------------------------------------
/// Lists all food bank entries (log-derived + manual) with filtering/sorting
/// and a FAB for adding new manual entries.
/// Browses every banked food -- log-derived and manually curated -- with
/// filtering, sorting, and an add-entry dialog.
class FoodBankScreen extends StatefulWidget {
/// Creates a [FoodBankScreen].
const FoodBankScreen({super.key});
@ -235,7 +96,7 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
isScrollControlled: true,
useSafeArea: true,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setSheet) => _FbFilterSheet(
builder: (ctx, setSheet) => FbFilterSheet(
filter: draft,
sortField: draftSort,
ascending: draftAsc,
@ -271,10 +132,17 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
);
}
/// Shows the full macro line for a tapped tile.
Future<void> _openDetail(FoodBankRecord record) => showModalBottomSheet<void>(
context: context,
useSafeArea: true,
builder: (_) => SafeArea(child: RecordTile(record)),
);
Future<void> _openAddDialog() async {
final result = await showDialog<FoodBankRecord>(
context: context,
builder: (_) => const _AddEntryDialog(),
builder: (_) => const AddEntryDialog(),
);
if (result == null) return;
await FoodBankService.instance.addManualEntry(result);
@ -286,15 +154,16 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
final all = _allEntries;
return Scaffold(
appBar: AppBar(
title: const Text('Food Bank'),
actions: [
if (all != null)
Stack(
alignment: Alignment.center,
children: [
IconButton(
icon: const Icon(Icons.filter_list),
tooltip: 'Filter & sort',
icon: const Icon(
Icons.filter_list,
semanticLabel: 'Filter & sort',
),
onPressed: _openFilterSheet,
),
if (_filter.isActive)
@ -315,398 +184,23 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
],
),
body: all == null
? const Center(child: CircularProgressIndicator())
? const WaitWatch.centered('food_bank.load')
: _displayed.isEmpty
? Center(
child: Text(
all.isEmpty
? 'Food bank is empty.\n'
'Log meals to populate it, or add entries manually.'
child: Icon(
all.isEmpty ? Icons.restaurant_menu : Icons.filter_list_off,
size: 64,
color: Theme.of(context).colorScheme.outline,
semanticLabel: all.isEmpty
? 'Food bank is empty.'
: 'No entries match the current filter.',
textAlign: TextAlign.center,
),
)
: ListView.builder(
itemCount: _displayed.length,
itemBuilder: (context, i) => _RecordTile(_displayed[i]),
),
: FbTileGrid(records: _displayed, onOpen: _openDetail),
floatingActionButton: FloatingActionButton(
onPressed: _openAddDialog,
tooltip: 'Add manual entry',
child: const Icon(Icons.add),
child: const Icon(Icons.add, semanticLabel: 'Add manual entry'),
),
);
}
}
// ---------------------------------------------------------------------------
// Record tile
// ---------------------------------------------------------------------------
class _RecordTile extends StatelessWidget {
const _RecordTile(this.record);
final FoodBankRecord record;
@override
Widget build(BuildContext context) {
final macros =
'P ${record.proteinG.toStringAsFixed(0)} g '
'C ${record.carbsG.toStringAsFixed(0)} g '
'F ${record.fatG.toStringAsFixed(0)} g';
final per = record.grams > 0
? ' per ${record.grams.toStringAsFixed(0)} g'
: '';
return ListTile(
title: Text(record.desc),
subtitle: Text(
'${record.kcal.toStringAsFixed(0)} kcal$per · $macros',
),
trailing: record.count > 0
? Text(
'×${record.count.toStringAsFixed(0)}',
style: Theme.of(context).textTheme.bodySmall,
)
: null,
);
}
}
// ---------------------------------------------------------------------------
// Filter sheet
// ---------------------------------------------------------------------------
class _FbFilterSheet extends StatelessWidget {
const _FbFilterSheet({
required this.filter,
required this.sortField,
required this.ascending,
required this.maxKcal,
required this.maxProtein,
required this.maxCarbs,
required this.maxFat,
required this.onFilterChanged,
required this.onSortChanged,
required this.onApply,
required this.onClear,
});
final FbFilter filter;
final FbSortField sortField;
final bool ascending;
final double maxKcal;
final double maxProtein;
final double maxCarbs;
final double maxFat;
final void Function(FbFilter) onFilterChanged;
final void Function({required FbSortField field, required bool asc})
onSortChanged;
final VoidCallback onApply;
final VoidCallback onClear;
@override
Widget build(BuildContext context) {
return DraggableScrollableSheet(
initialChildSize: 0.85,
minChildSize: 0.5,
maxChildSize: 0.95,
builder: (context, scroll) => Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
child: Row(
children: [
Expanded(
child: Text(
'Filter & Sort',
style: Theme.of(context).textTheme.titleMedium,
),
),
TextButton(
onPressed: onClear,
child: const Text('Clear all'),
),
],
),
),
const Divider(),
Expanded(
child: ListView(
controller: scroll,
padding: const EdgeInsets.all(16),
children: [
TextField(
decoration: const InputDecoration(
labelText: 'Search by name',
prefixIcon: Icon(Icons.search),
isDense: true,
),
controller: TextEditingController(text: filter.nameQuery)
..selection = TextSelection.collapsed(
offset: filter.nameQuery.length,
),
onChanged: (v) {
filter.nameQuery = v;
onFilterChanged(filter);
},
),
const SizedBox(height: 16),
if (maxKcal > 0) ...[
Text(
'Kcal range',
style: Theme.of(context).textTheme.labelLarge,
),
RangeSlider(
max: maxKcal,
values: RangeValues(
filter.minKcal ?? 0,
filter.maxKcal ?? maxKcal,
),
labels: RangeLabels(
(filter.minKcal ?? 0).toStringAsFixed(0),
(filter.maxKcal ?? maxKcal).toStringAsFixed(0),
),
onChanged: (v) {
filter.minKcal = v.start > 0 ? v.start : null;
filter.maxKcal = v.end < maxKcal ? v.end : null;
onFilterChanged(filter);
},
),
const SizedBox(height: 8),
],
if (maxProtein > 0) ...[
Text(
'Protein range (g)',
style: Theme.of(context).textTheme.labelLarge,
),
RangeSlider(
max: maxProtein,
values: RangeValues(
filter.minProtein ?? 0,
filter.maxProtein ?? maxProtein,
),
labels: RangeLabels(
(filter.minProtein ?? 0).toStringAsFixed(0),
(filter.maxProtein ?? maxProtein).toStringAsFixed(0),
),
onChanged: (v) {
filter.minProtein = v.start > 0 ? v.start : null;
filter.maxProtein = v.end < maxProtein ? v.end : null;
onFilterChanged(filter);
},
),
const SizedBox(height: 8),
],
if (maxCarbs > 0) ...[
Text(
'Carbs range (g)',
style: Theme.of(context).textTheme.labelLarge,
),
RangeSlider(
max: maxCarbs,
values: RangeValues(
filter.minCarbs ?? 0,
filter.maxCarbs ?? maxCarbs,
),
labels: RangeLabels(
(filter.minCarbs ?? 0).toStringAsFixed(0),
(filter.maxCarbs ?? maxCarbs).toStringAsFixed(0),
),
onChanged: (v) {
filter.minCarbs = v.start > 0 ? v.start : null;
filter.maxCarbs = v.end < maxCarbs ? v.end : null;
onFilterChanged(filter);
},
),
const SizedBox(height: 8),
],
if (maxFat > 0) ...[
Text(
'Fat range (g)',
style: Theme.of(context).textTheme.labelLarge,
),
RangeSlider(
max: maxFat,
values: RangeValues(
filter.minFat ?? 0,
filter.maxFat ?? maxFat,
),
labels: RangeLabels(
(filter.minFat ?? 0).toStringAsFixed(0),
(filter.maxFat ?? maxFat).toStringAsFixed(0),
),
onChanged: (v) {
filter.minFat = v.start > 0 ? v.start : null;
filter.maxFat = v.end < maxFat ? v.end : null;
onFilterChanged(filter);
},
),
const SizedBox(height: 8),
],
Text(
'Sort by',
style: Theme.of(context).textTheme.labelLarge,
),
const SizedBox(height: 4),
Row(
children: [
Expanded(
child: DropdownButton<FbSortField>(
isExpanded: true,
value: sortField,
items: const [
DropdownMenuItem(
value: FbSortField.count,
child: Text('Usage count'),
),
DropdownMenuItem(
value: FbSortField.name,
child: Text('Name'),
),
DropdownMenuItem(
value: FbSortField.kcal,
child: Text('Kcal'),
),
DropdownMenuItem(
value: FbSortField.protein,
child: Text('Protein'),
),
DropdownMenuItem(
value: FbSortField.carbs,
child: Text('Carbs'),
),
DropdownMenuItem(
value: FbSortField.fat,
child: Text('Fat'),
),
],
onChanged: (v) {
if (v != null) {
onSortChanged(field: v, asc: ascending);
}
},
),
),
const SizedBox(width: 8),
IconButton(
icon: Icon(
ascending ? Icons.arrow_upward : Icons.arrow_downward,
),
tooltip: ascending ? 'Ascending' : 'Descending',
onPressed: () =>
onSortChanged(field: sortField, asc: !ascending),
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.all(16),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: onApply,
child: const Text('Apply'),
),
),
),
],
),
);
}
}
// ---------------------------------------------------------------------------
// Add entry dialog
// ---------------------------------------------------------------------------
class _AddEntryDialog extends StatefulWidget {
const _AddEntryDialog();
@override
State<_AddEntryDialog> createState() => _AddEntryDialogState();
}
class _AddEntryDialogState extends State<_AddEntryDialog> {
final _name = TextEditingController();
final _grams = TextEditingController(text: '100');
final _kcal = TextEditingController();
final _protein = TextEditingController();
final _carbs = TextEditingController();
final _fat = TextEditingController();
@override
void dispose() {
_name.dispose();
_grams.dispose();
_kcal.dispose();
_protein.dispose();
_carbs.dispose();
_fat.dispose();
super.dispose();
}
void _save() {
final name = _name.text.trim();
if (name.isEmpty) return;
Navigator.of(context).pop(
FoodBankRecord(
desc: name,
kcal: double.tryParse(_kcal.text) ?? 0,
proteinG: double.tryParse(_protein.text) ?? 0,
carbsG: double.tryParse(_carbs.text) ?? 0,
fatG: double.tryParse(_fat.text) ?? 0,
grams: double.tryParse(_grams.text) ?? 100,
count: 0,
),
);
}
Widget _field(String label, TextEditingController ctrl) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: TextField(
controller: ctrl,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(labelText: label, isDense: true),
),
);
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Add to food bank'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: TextField(
controller: _name,
decoration: const InputDecoration(
labelText: 'Name',
isDense: true,
),
),
),
_field('Reference grams', _grams),
_field('Kcal', _kcal),
_field('Protein (g)', _protein),
_field('Carbs (g)', _carbs),
_field('Fat (g)', _fat),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: _save,
child: const Text('Save to bank'),
),
],
);
}
}

View File

@ -0,0 +1,56 @@
// The "paste your OAuth client id" dialog shown before the device flow.
//
// Split out of `github_mirror_screen.dart` for the repo's 250-line cap. A
// `part` so the class can stay library-private: it is an implementation
// detail of that screen and nothing else may construct it.
part of 'github_mirror_screen.dart';
/// Dialog shown when "Connect GitHub" is tapped with no OAuth App client id
/// configured yet. Explains what it is, how to get one, and lets the user
/// paste it in directly — rather than leaving them to discover a buried
/// field on their own. Pops the trimmed client id, or null if cancelled.
class _ClientIdSetupDialog extends StatefulWidget {
const _ClientIdSetupDialog();
@override
State<_ClientIdSetupDialog> createState() => _ClientIdSetupDialogState();
}
class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Icon-only: the setup steps (open github.com/settings/developers, make
// an OAuth App with Device Flow, paste its client id) live in the repo
// docs, not on screen.
return AlertDialog(
content: IconField(
icon: Icons.apps,
semanticLabel: 'Client ID',
controller: _controller,
autofocus: true,
),
actions: [
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
),
IconButton.filled(
onPressed: () {
final id = _controller.text.trim();
if (id.isNotEmpty) Navigator.of(context).pop(id);
},
icon: const Icon(Icons.arrow_forward, semanticLabel: 'Continue'),
),
],
);
}
}

View File

@ -0,0 +1,156 @@
// Connect / save / test / sync actions for the GitHub mirror screen.
//
// Split out of `github_mirror_screen.dart` for the repo's 250-line cap. A
// `part` rather than a separate library: every one of these methods drives
// the screen's private state (`_busy`, `_status`, `_storedToken`, the four
// controllers) and calls its private helpers, none of which are reachable
// across a library boundary in Dart.
//
// A mixin rather than an extension, because these call `setState`, which is
// `@protected` -- an extension is not a subclass of `State`, so the analyzer
// (correctly) rejects it there.
part of 'github_mirror_screen.dart';
mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
// The four text controllers stay declared on the State, which creates and
// disposes them; the mixin only reads and writes their text.
TextEditingController get _ownerController;
TextEditingController get _repoController;
TextEditingController get _tokenController;
TextEditingController get _clientIdController;
bool _busy = false;
Widget? _status;
String _storedToken = '';
SyncSettings _currentSettings() {
final typed = _tokenController.text.trim();
return SyncSettings(
owner: _ownerController.text.trim(),
repo: _repoController.text.trim(),
// The `_storedToken` side is web-only (the wrapper holds the real
// token), so it is unreachable from a VM test.
token: typed.isEmpty && !SyncSettings.exposesTokenValue
// coverage:ignore-line
? _storedToken
: typed,
clientId: _clientIdController.text.trim(),
);
}
/// Shows the outcome as an icon cue; [semanticLabel] is spoken, never
/// painted.
void _showCue(CueKind kind, String semanticLabel) {
if (!mounted) return;
setState(
() => _status = StatusCue(
key: UniqueKey(),
kind: kind,
semanticLabel: semanticLabel,
),
);
}
Future<void> _connectGitHub() async {
var clientId = _clientIdController.text.trim();
if (clientId.isEmpty) {
final entered = await showDialog<String>(
context: context,
builder: (_) => const _ClientIdSetupDialog(),
);
if (entered == null || entered.isEmpty) return;
clientId = entered;
if (!mounted) return;
setState(() => _clientIdController.text = clientId);
await _currentSettings().save();
}
final auth = createDeviceAuth(clientId, httpClient: widget.httpClient);
try {
final device = await auth.requestDeviceCode();
if (!mounted) return;
final token = await showDialog<String>(
context: context,
barrierDismissible: false,
builder: (_) => DeviceCodeDialog(device: device, auth: auth),
);
if (token != null && token.isNotEmpty) {
setState(() {
_storedToken = token;
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
});
_showCue(CueKind.info, 'Connected — syncing…');
await _currentSettings().save();
await _syncAfterConnect();
}
} on Exception catch (e) {
_showCue(CueKind.error, 'Could not start device flow: $e');
} finally {
auth.close();
}
}
/// Runs a sync right after connecting so the device-flow token is proven
/// to work immediately, with clear confirmation either way.
Future<void> _syncAfterConnect() async {
final settings = _currentSettings();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
await runSync(await syncBackend(client));
await SyncHealth.recordSuccess();
_showCue(CueKind.ok, 'Connected and synced.');
} on Exception catch (e) {
await SyncHealth.recordFailure();
_showCue(CueKind.error, 'Connected, but sync failed: $e');
} finally {
client.close();
}
}
Future<void> _save() async {
setState(() => _busy = true);
await _currentSettings().save();
if (!mounted) return;
setState(() => _busy = false);
_showCue(CueKind.ok, 'Saved.');
}
Future<void> _testConnection() async {
setState(() => _busy = true);
final settings = _currentSettings();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
final ok = await client.canAccessRepo();
if (ok) {
_showCue(CueKind.ok, 'GitHub connection OK.');
} else {
_showCue(CueKind.error, 'GitHub connection failed.');
}
} on Exception catch (e) {
_showCue(CueKind.error, 'GitHub connection failed: $e');
} finally {
client.close();
if (mounted) setState(() => _busy = false);
}
}
Future<void> _syncNow() async {
setState(() => _busy = true);
final settings = _currentSettings();
await settings.save();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
await runSync(await syncBackend(client));
// Clears any stored failure: this is the button a user reaches
// *because* the banner told them syncing had stopped, so a successful
// run here must dismiss the warning it caused.
await SyncHealth.recordSuccess();
_showCue(CueKind.ok, 'Synced.');
} on Exception catch (e) {
await SyncHealth.recordFailure();
_showCue(CueKind.error, 'Sync failed: $e');
} finally {
client.close();
if (mounted) setState(() => _busy = false);
}
}
}

View File

@ -0,0 +1,187 @@
/// Sync configuration for the GitHub cutover mirror. Kept app-local rather
/// than folded into the shared `sync_settings_ui` package because connecting
/// here also triggers a real log sync via [_syncAfterConnect] -- unlike the
/// shared package's Firebase section, which only saves settings. See
/// `lib/screens/settings_screen.dart` for the link to this screen and to the
/// shared Sync settings screen.
library;
import 'dart:async';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:github_device_auth/github_device_auth.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
part 'github_client_id_dialog.dart';
part 'github_mirror_actions.dart';
/// Screen for configuring and triggering the GitHub mirror sync.
class GitHubMirrorScreen extends StatefulWidget {
/// Creates a [GitHubMirrorScreen].
const GitHubMirrorScreen({super.key, this.httpClient});
/// Injectable HTTP client; tests pass a [MockClient].
final http.Client? httpClient;
@override
State<GitHubMirrorScreen> createState() => _GitHubMirrorScreenState();
}
class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
with _GitHubMirrorActions {
@override
final _ownerController = TextEditingController();
@override
final _repoController = TextEditingController();
@override
final _tokenController = TextEditingController();
@override
final _clientIdController = TextEditingController();
bool _loading = true;
@override
void initState() {
super.initState();
unawaited(_load());
}
/// Loads saved settings, defaulting to blank fields if loading itself
/// fails (e.g. no secret service available yet) -- the screen must still
/// render, not spin forever, so the user can fill them in from scratch.
Future<void> _load() async {
SyncSettings settings;
try {
settings = await SyncSettings.load();
// SyncSettings.load()'s only awaited calls are SharedPreferences
// (always mocked successfully under flutter test) and the token
// vault, whose own read() already swallows its errors internally --
// so this catch has no reachable path from a VM test, the same reason
// _currentSettings()'s web-only branch below is marked unreachable.
// coverage:ignore-start
} on Exception {
settings = const SyncSettings(owner: '', repo: '', token: '');
// coverage:ignore-end
}
if (!mounted) return;
_ownerController.text = settings.owner;
_repoController.text = settings.repo;
// On web the stored "token" is only a stand-in for one the desktop
// wrapper holds (see TokenVault); showing it would invite the user to
// edit a literal. [_storedToken] keeps it for round-tripping.
_storedToken = settings.token;
_tokenController.text = SyncSettings.exposesTokenValue
? settings.token
: '';
_clientIdController.text = settings.clientId;
setState(() => _loading = false);
}
@override
void dispose() {
_ownerController.dispose();
_repoController.dispose();
_tokenController.dispose();
_clientIdController.dispose();
super.dispose();
}
/// The token as loaded, so a platform that cannot display it (web) still
/// round-trips it instead of blanking it on the next save.
/// Runs the OAuth device flow and, on success, fills in the token field.
@override
Widget build(BuildContext context) {
if (_loading) {
return const Scaffold(body: WaitWatch.centered('github_mirror.load'));
}
return Scaffold(
// No title and no explanatory paragraph: the code glyph that opened this
// screen names it, and the connect button is self-evident.
appBar: AppBar(),
// Centred and capped at the prose width so fields do not span the
// whole window on the desktop surface.
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: ListView(
padding: const EdgeInsets.all(16),
children: [
Align(
alignment: Alignment.centerLeft,
child: IconButton.filled(
onPressed: _connectGitHub,
icon: const Icon(
Icons.login,
semanticLabel: 'Connect GitHub',
),
),
),
const SizedBox(height: 16),
IconField(
icon: Icons.person_outline,
semanticLabel: 'GitHub owner',
controller: _ownerController,
),
const SizedBox(height: 8),
IconField(
icon: Icons.folder_outlined,
semanticLabel: 'Repo',
controller: _repoController,
),
const SizedBox(height: 8),
IconField(
icon: Icons.apps,
semanticLabel: 'OAuth App client id',
controller: _clientIdController,
),
const SizedBox(height: 8),
IconField(
icon: Icons.key,
semanticLabel: 'Personal access token (fallback)',
controller: _tokenController,
obscure: true,
),
const SizedBox(height: 16),
Wrap(
spacing: 8,
children: [
IconButton.filled(
onPressed: _busy ? null : _save,
icon: const Icon(Icons.check, semanticLabel: 'Save'),
),
// Tests the GitHub connection only (a canAccessRepo call);
// it says nothing about Firebase.
IconButton.outlined(
onPressed: _busy ? null : _testConnection,
tooltip: 'Test',
icon: const Icon(
Icons.network_check,
semanticLabel: 'Test GitHub connection',
),
),
IconButton.filled(
onPressed: _busy ? null : _syncNow,
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
),
],
),
if (_status != null) ...[
const SizedBox(height: 16),
Align(alignment: Alignment.centerLeft, child: _status),
],
],
),
),
),
);
}
}

View File

@ -1,276 +1,27 @@
/// Logged meal history with day grouping, filtering, and sorting.
///
/// The filter model, the grouped list and the filter sheet live in
/// `lib/widgets/history/` (split for the repo's 250-line cap); this file is the
/// screen that wires them together and owns the filter state.
library;
import 'dart:async';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart';
import 'package:diet_guard_app/widgets/history/history_filter.dart';
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
import 'package:diet_guard_app/widgets/history/history_list.dart';
import 'package:material_ui/material_ui.dart';
// ---------------------------------------------------------------------------
// Filter & sort state
// ---------------------------------------------------------------------------
/// Sort field for the history list.
enum HistorySortField {
/// Sort by entry date/time.
date,
/// Sort by calories.
kcal,
/// Sort by protein (g).
protein,
/// Sort by carbohydrates (g).
carbs,
/// Sort by fat (g).
fat,
/// Sort by description text.
description,
}
/// All active filter criteria; [isActive] is true when any criterion is set.
class HistoryFilter {
/// Creates a [HistoryFilter] with the given criteria.
HistoryFilter({
this.nameQuery = '',
this.dateRange,
this.minKcal,
this.maxKcal,
this.minProtein,
this.maxProtein,
this.minCarbs,
this.maxCarbs,
this.minFat,
this.maxFat,
this.source,
});
/// Substring match on the food description.
String nameQuery;
/// Optional date range filter.
DateTimeRange? dateRange;
/// Minimum kcal.
double? minKcal;
/// Maximum kcal.
double? maxKcal;
/// Minimum protein (g).
double? minProtein;
/// Maximum protein (g).
double? maxProtein;
/// Minimum carbs (g).
double? minCarbs;
/// Maximum carbs (g).
double? maxCarbs;
/// Minimum fat (g).
double? minFat;
/// Maximum fat (g).
double? maxFat;
/// null = all, or a source string from the log.
String? source;
/// True when any filter criterion is active.
bool get isActive =>
nameQuery.isNotEmpty ||
dateRange != null ||
minKcal != null ||
maxKcal != null ||
minProtein != null ||
maxProtein != null ||
minCarbs != null ||
maxCarbs != null ||
minFat != null ||
maxFat != null ||
source != null;
}
// ---------------------------------------------------------------------------
// List item sealed hierarchy for day-grouped rendering
// ---------------------------------------------------------------------------
sealed class _HistoryItem {}
final class _DayHeader extends _HistoryItem {
_DayHeader(
this.dateKey,
this.totalKcal,
this.entryCount,
this.totalProtein,
this.totalCarbs,
this.totalFat,
);
final String dateKey;
final double totalKcal;
final int entryCount;
final double totalProtein;
final double totalCarbs;
final double totalFat;
}
final class _EntryRow extends _HistoryItem {
_EntryRow(this.entry);
final FoodEntry entry;
}
// ---------------------------------------------------------------------------
// Pure filter / sort / group helpers
// ---------------------------------------------------------------------------
/// Applies [filter] and sort criteria to [entries] and returns the result.
/// Logged meal history: every entry, grouped by day, filterable and sortable.
///
/// Exposed as a top-level function for unit tests.
List<FoodEntry> applyHistoryFilter(
List<FoodEntry> entries,
HistoryFilter filter,
HistorySortField sortField, {
required bool ascending,
}) {
var result = [...entries];
if (filter.nameQuery.isNotEmpty) {
final q = filter.nameQuery.toLowerCase();
result = result.where((e) => e.desc.toLowerCase().contains(q)).toList();
}
if (filter.dateRange != null) {
final start = filter.dateRange!.start;
final end = filter.dateRange!.end.add(const Duration(days: 1));
result = result.where((e) {
final t = DateTime.tryParse(e.time);
return t != null && !t.isBefore(start) && t.isBefore(end);
}).toList();
}
if (filter.minKcal != null) {
result = result.where((e) => e.kcal >= filter.minKcal!).toList();
}
if (filter.maxKcal != null) {
result = result.where((e) => e.kcal <= filter.maxKcal!).toList();
}
if (filter.minProtein != null) {
result = result.where((e) => e.proteinG >= filter.minProtein!).toList();
}
if (filter.maxProtein != null) {
result = result.where((e) => e.proteinG <= filter.maxProtein!).toList();
}
if (filter.minCarbs != null) {
result = result.where((e) => e.carbsG >= filter.minCarbs!).toList();
}
if (filter.maxCarbs != null) {
result = result.where((e) => e.carbsG <= filter.maxCarbs!).toList();
}
if (filter.minFat != null) {
result = result.where((e) => e.fatG >= filter.minFat!).toList();
}
if (filter.maxFat != null) {
result = result.where((e) => e.fatG <= filter.maxFat!).toList();
}
if (filter.source != null) {
result = result.where((e) => e.source == filter.source).toList();
}
result.sort((a, b) {
int cmp;
switch (sortField) {
case HistorySortField.date:
final at = DateTime.tryParse(a.time) ?? DateTime(0);
final bt = DateTime.tryParse(b.time) ?? DateTime(0);
cmp = at.compareTo(bt);
case HistorySortField.kcal:
cmp = a.kcal.compareTo(b.kcal);
case HistorySortField.protein:
cmp = a.proteinG.compareTo(b.proteinG);
case HistorySortField.carbs:
cmp = a.carbsG.compareTo(b.carbsG);
case HistorySortField.fat:
cmp = a.fatG.compareTo(b.fatG);
case HistorySortField.description:
cmp = a.desc.compareTo(b.desc);
}
return ascending ? cmp : -cmp;
});
return result;
}
List<_HistoryItem> _buildGroupedItems(List<FoodEntry> entries) {
final byDay = <String, List<FoodEntry>>{};
for (final e in entries) {
final day = e.time.length >= 10 ? e.time.substring(0, 10) : 'unknown';
byDay.putIfAbsent(day, () => []).add(e);
}
final days = byDay.keys.toList()..sort((a, b) => b.compareTo(a));
final items = <_HistoryItem>[];
for (final day in days) {
final dayEntries = byDay[day]!;
final totalKcal = sumKcal(dayEntries);
final totalProtein = dayEntries.fold<double>(0, (s, e) => s + e.proteinG);
final totalCarbs = dayEntries.fold<double>(0, (s, e) => s + e.carbsG);
final totalFat = dayEntries.fold<double>(0, (s, e) => s + e.fatG);
items
..add(
_DayHeader(
day,
totalKcal,
dayEntries.length,
totalProtein,
totalCarbs,
totalFat,
),
)
..addAll(dayEntries.map(_EntryRow.new));
}
return items;
}
String _dateRangeLabel(DateTimeRange r) =>
'${r.start.toString().substring(0, 10)}'
' – ${r.end.toString().substring(0, 10)}';
String _formatDay(String dateKey) {
try {
final d = DateTime.parse(dateKey);
const wd = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const mo = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
return '${wd[d.weekday - 1]} ${d.day} ${mo[d.month - 1]} ${d.year}';
} on Exception {
return dateKey;
}
}
// ---------------------------------------------------------------------------
// Screen
// ---------------------------------------------------------------------------
/// Shows every non-deleted logged entry, grouped by day, with optional
/// filtering and sorting.
/// Owns the live [HistoryFilter] and sort order; the sheet that edits them and
/// the list that renders the result are separate widgets under
/// `lib/widgets/history/`.
class HistoryScreen extends StatefulWidget {
/// Creates a [HistoryScreen].
///
@ -368,7 +119,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
isScrollControlled: true,
useSafeArea: true,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setSheet) => _FilterSheet(
builder: (ctx, setSheet) => FilterSheet(
filter: draft,
sortField: draftSortField,
ascending: draftSortAscending,
@ -409,15 +160,16 @@ class _HistoryScreenState extends State<HistoryScreen> {
final allEntries = _allEntries;
return Scaffold(
appBar: AppBar(
title: const Text('History'),
actions: [
if (allEntries != null)
Stack(
alignment: Alignment.center,
children: [
IconButton(
icon: const Icon(Icons.filter_list),
tooltip: 'Filter & sort',
icon: const Icon(
Icons.filter_list,
semanticLabel: 'Filter & sort',
),
onPressed: _openFilterSheet,
),
if (_filter.isActive)
@ -438,17 +190,20 @@ class _HistoryScreenState extends State<HistoryScreen> {
],
),
body: allEntries == null
? const Center(child: CircularProgressIndicator())
? const WaitWatch.centered('history.load')
: _displayed.isEmpty
? Center(
child: Text(
allEntries.isEmpty
child: Icon(
allEntries.isEmpty ? Icons.restaurant : Icons.filter_list_off,
size: 64,
color: Theme.of(context).colorScheme.outline,
semanticLabel: allEntries.isEmpty
? 'Nothing logged yet.'
: 'No entries match the current filter.',
),
)
: _GroupedList(
items: _buildGroupedItems(_displayed),
: GroupedList(
items: buildGroupedItems(_displayed),
onDeleteEntry: _load,
onEditEntry: _onEditEntry,
),
@ -459,594 +214,3 @@ class _HistoryScreenState extends State<HistoryScreen> {
// ---------------------------------------------------------------------------
// Grouped list widget
// ---------------------------------------------------------------------------
class _GroupedList extends StatelessWidget {
const _GroupedList({
required this.items,
required this.onDeleteEntry,
required this.onEditEntry,
});
final List<_HistoryItem> items;
final Future<void> Function() onDeleteEntry;
final Future<void> Function(FoodEntry) onEditEntry;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return switch (item) {
_DayHeader() => _DayHeaderTile(item),
_EntryRow() => _EntryTile(
item.entry,
onDelete: onDeleteEntry,
onEdit: () => onEditEntry(item.entry),
),
};
},
);
}
}
class _DayHeaderTile extends StatelessWidget {
const _DayHeaderTile(this.header);
final _DayHeader header;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final textTheme = Theme.of(context).textTheme;
// The budget that applied on *that* day, not today's -- a later budget
// change must not repaint months of history red.
final goal = BudgetHistoryService.schedule.forDay(header.dateKey);
final kcalColor = header.totalKcal > goal
? colorScheme.error
: colorScheme.primary;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
color: colorScheme.surfaceContainerHighest,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
_formatDay(header.dateKey),
style: textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
Text(
'${header.entryCount}'
' ${header.entryCount == 1 ? 'entry' : 'entries'}',
style: textTheme.bodySmall,
),
],
),
const SizedBox(height: 2),
Row(
children: [
Text(
'${header.totalKcal.round()} / $goal kcal',
style: textTheme.bodySmall?.copyWith(color: kcalColor),
),
const SizedBox(width: 8),
Text(
'P ${header.totalProtein.round()}g · '
'C ${header.totalCarbs.round()}g · '
'F ${header.totalFat.round()}g',
style: textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
],
),
);
}
}
class _EntryTile extends StatelessWidget {
const _EntryTile(this.entry, {this.onDelete, this.onEdit});
final FoodEntry entry;
/// Called after a confirmed delete so the parent can reload.
final Future<void> Function()? onDelete;
/// Called when the tile is tapped to open the edit screen.
final Future<void> Function()? onEdit;
@override
Widget build(BuildContext context) {
final canDelete = entry.id != null;
return ListTile(
leading: const Icon(Icons.restaurant),
title: Text(entry.desc),
subtitle: Text('${entry.time} • ${entry.source}'),
// Delete needs a focusable control, not just a long-press. Long-press has
// no keyboard equivalent at all, so on the desktop build (a Chrome --app
// window) deleting an entry was pointer-only: unreachable by keyboard and
// invisible to a screen reader. The trailing row keeps the kcal figure
// and adds an IconButton, which Tab reaches and Enter/Space activates.
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('${entry.kcal.toStringAsFixed(0)} kcal'),
if (canDelete)
IconButton(
icon: const Icon(Icons.delete_outline),
tooltip: 'Delete entry',
onPressed: () => _confirmDelete(context),
),
],
),
// Any entry can be edited (legacy null-id entries gain a UUID on save).
// Delete remains id-only to avoid ambiguous time+desc matches.
onTap: () => onEdit?.call(),
// Retained as a redundant pointer shortcut, never the only route.
onLongPress: canDelete ? () => _confirmDelete(context) : null,
);
}
Future<void> _confirmDelete(BuildContext context) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: const Text('Delete entry?'),
content: Text('Remove "${entry.desc}" from history?'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
TextButton(
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Delete'),
),
],
),
);
if (confirmed == true) {
await LogStorageService.instance.deleteEntry(entry.id!);
await onDelete?.call();
}
}
}
// ---------------------------------------------------------------------------
// Filter sheet
// ---------------------------------------------------------------------------
class _FilterSheet extends StatelessWidget {
const _FilterSheet({
required this.filter,
required this.sortField,
required this.ascending,
required this.maxKcal,
required this.maxProtein,
required this.maxCarbs,
required this.maxFat,
required this.onFilterChanged,
required this.onSortChanged,
required this.onApply,
required this.onClear,
});
final HistoryFilter filter;
final HistorySortField sortField;
final bool ascending;
final double maxKcal;
final double maxProtein;
final double maxCarbs;
final double maxFat;
final void Function(HistoryFilter) onFilterChanged;
final void Function({required HistorySortField field, required bool asc})
onSortChanged;
final VoidCallback onApply;
final VoidCallback onClear;
@override
Widget build(BuildContext context) {
return DraggableScrollableSheet(
initialChildSize: 0.9,
minChildSize: 0.5,
maxChildSize: 0.95,
builder: (context, scroll) => Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
child: Row(
children: [
Expanded(
child: Text(
'Filter & Sort',
style: Theme.of(context).textTheme.titleMedium,
),
),
TextButton(onPressed: onClear, child: const Text('Clear all')),
],
),
),
const Divider(),
Expanded(
child: SingleChildScrollView(
controller: scroll,
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Name search
_NameSearchField(
initialQuery: filter.nameQuery,
onChanged: (v) {
filter.nameQuery = v;
onFilterChanged(filter);
},
),
const SizedBox(height: 16),
// Date range
Text(
'Date range',
style: Theme.of(context).textTheme.labelLarge,
),
const SizedBox(height: 4),
OutlinedButton.icon(
icon: const Icon(Icons.date_range),
label: Text(
filter.dateRange == null
? 'Any date'
: _dateRangeLabel(filter.dateRange!),
),
onPressed: () async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2020),
lastDate: DateTime.now().add(const Duration(days: 1)),
initialDateRange: filter.dateRange,
);
if (picked != null) {
filter.dateRange = picked;
onFilterChanged(filter);
}
},
),
if (filter.dateRange != null)
TextButton(
onPressed: () {
filter.dateRange = null;
onFilterChanged(filter);
},
child: const Text('Clear date range'),
),
const SizedBox(height: 16),
// Kcal range
if (maxKcal > 0) ...[
Text(
'Kcal range',
style: Theme.of(context).textTheme.labelLarge,
),
_SliderEndpointLabels(
lo: '0',
hi: maxKcal.round().toString(),
),
RangeSlider(
key: const Key('kcal-range-slider'),
max: maxKcal,
values: RangeValues(
filter.minKcal ?? 0,
filter.maxKcal ?? maxKcal,
),
labels: RangeLabels(
(filter.minKcal ?? 0).toStringAsFixed(0),
(filter.maxKcal ?? maxKcal).toStringAsFixed(0),
),
onChanged: (v) {
filter.minKcal = v.start > 0 ? v.start : null;
filter.maxKcal = v.end < maxKcal ? v.end : null;
onFilterChanged(filter);
},
),
_SliderSelectedLabel(
'${(filter.minKcal ?? 0).round()}'
' – ${(filter.maxKcal ?? maxKcal).round()} kcal',
),
const SizedBox(height: 8),
],
// Protein range
if (maxProtein > 0) ...[
Text(
'Protein range (g)',
style: Theme.of(context).textTheme.labelLarge,
),
_SliderEndpointLabels(
lo: '0',
hi: '${maxProtein.round()}g',
),
RangeSlider(
key: const Key('protein-range-slider'),
max: maxProtein,
values: RangeValues(
filter.minProtein ?? 0,
filter.maxProtein ?? maxProtein,
),
labels: RangeLabels(
(filter.minProtein ?? 0).toStringAsFixed(0),
(filter.maxProtein ?? maxProtein).toStringAsFixed(0),
),
onChanged: (v) {
filter.minProtein = v.start > 0 ? v.start : null;
filter.maxProtein = v.end < maxProtein ? v.end : null;
onFilterChanged(filter);
},
),
_SliderSelectedLabel(
'${(filter.minProtein ?? 0).round()}'
' – ${(filter.maxProtein ?? maxProtein).round()}g',
),
const SizedBox(height: 8),
],
// Carbs range
if (maxCarbs > 0) ...[
Text(
'Carbs range (g)',
style: Theme.of(context).textTheme.labelLarge,
),
_SliderEndpointLabels(lo: '0', hi: '${maxCarbs.round()}g'),
RangeSlider(
key: const Key('carbs-range-slider'),
max: maxCarbs,
values: RangeValues(
filter.minCarbs ?? 0,
filter.maxCarbs ?? maxCarbs,
),
labels: RangeLabels(
(filter.minCarbs ?? 0).toStringAsFixed(0),
(filter.maxCarbs ?? maxCarbs).toStringAsFixed(0),
),
onChanged: (v) {
filter.minCarbs = v.start > 0 ? v.start : null;
filter.maxCarbs = v.end < maxCarbs ? v.end : null;
onFilterChanged(filter);
},
),
_SliderSelectedLabel(
'${(filter.minCarbs ?? 0).round()}'
' – ${(filter.maxCarbs ?? maxCarbs).round()}g',
),
const SizedBox(height: 8),
],
// Fat range
if (maxFat > 0) ...[
Text(
'Fat range (g)',
style: Theme.of(context).textTheme.labelLarge,
),
_SliderEndpointLabels(lo: '0', hi: '${maxFat.round()}g'),
RangeSlider(
key: const Key('fat-range-slider'),
max: maxFat,
values: RangeValues(
filter.minFat ?? 0,
filter.maxFat ?? maxFat,
),
labels: RangeLabels(
(filter.minFat ?? 0).toStringAsFixed(0),
(filter.maxFat ?? maxFat).toStringAsFixed(0),
),
onChanged: (v) {
filter.minFat = v.start > 0 ? v.start : null;
filter.maxFat = v.end < maxFat ? v.end : null;
onFilterChanged(filter);
},
),
_SliderSelectedLabel(
'${(filter.minFat ?? 0).round()}'
' – ${(filter.maxFat ?? maxFat).round()}g',
),
const SizedBox(height: 8),
],
// Source filter
Text('Source', style: Theme.of(context).textTheme.labelLarge),
const SizedBox(height: 4),
Wrap(
spacing: 8,
children: [
FilterChip(
label: const Text('All'),
selected: filter.source == null,
onSelected: (_) {
filter.source = null;
onFilterChanged(filter);
},
),
for (final src in ['manual', 'food bank'])
FilterChip(
label: Text(src),
selected: filter.source == src,
onSelected: (_) {
filter.source = src;
onFilterChanged(filter);
},
),
],
),
const SizedBox(height: 16),
// Sort
Text(
'Sort by',
style: Theme.of(context).textTheme.labelLarge,
),
const SizedBox(height: 4),
Row(
children: [
Expanded(
child: DropdownButton<HistorySortField>(
isExpanded: true,
value: sortField,
items: const [
DropdownMenuItem(
value: HistorySortField.date,
child: Text('Date'),
),
DropdownMenuItem(
value: HistorySortField.kcal,
child: Text('Kcal'),
),
DropdownMenuItem(
value: HistorySortField.protein,
child: Text('Protein'),
),
DropdownMenuItem(
value: HistorySortField.carbs,
child: Text('Carbs'),
),
DropdownMenuItem(
value: HistorySortField.fat,
child: Text('Fat'),
),
DropdownMenuItem(
value: HistorySortField.description,
child: Text('Description'),
),
],
onChanged: (v) {
if (v != null) {
onSortChanged(field: v, asc: ascending);
}
},
),
),
const SizedBox(width: 8),
IconButton(
icon: Icon(
ascending ? Icons.arrow_upward : Icons.arrow_downward,
),
tooltip: ascending ? 'Ascending' : 'Descending',
onPressed: () =>
onSortChanged(field: sortField, asc: !ascending),
),
],
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: onApply,
child: const Text('Apply'),
),
),
),
],
),
);
}
}
// ---------------------------------------------------------------------------
// Slider label helpers
// ---------------------------------------------------------------------------
/// Thin row showing the min (0) and max endpoint values for a range slider.
/// The filter sheet's name-search field, owning a persistent controller.
///
/// Stateful on purpose. The controller used to be built inside
/// `_FilterSheet.build` with the caret forced to the end of the text, and
/// `onChanged` rebuilds the sheet — so every keystroke discarded the controller
/// and re-slammed the caret to end-of-text. Appending worked, but Home/End and
/// arrow-key editing in the middle of the query were silently undone on each
/// character. Keeping the controller in State fixes that without changing how
/// the filter is plumbed.
class _NameSearchField extends StatefulWidget {
const _NameSearchField({required this.initialQuery, required this.onChanged});
/// Query text to seed the field with on first build only.
final String initialQuery;
/// Called on each edit with the new query.
final ValueChanged<String> onChanged;
@override
State<_NameSearchField> createState() => _NameSearchFieldState();
}
class _NameSearchFieldState extends State<_NameSearchField> {
late final TextEditingController _controller = TextEditingController(
text: widget.initialQuery,
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'Search by name',
prefixIcon: Icon(Icons.search),
isDense: true,
),
onChanged: widget.onChanged,
);
}
}
class _SliderEndpointLabels extends StatelessWidget {
const _SliderEndpointLabels({required this.lo, required this.hi});
final String lo;
final String hi;
@override
Widget build(BuildContext context) {
final style = Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
return Row(
children: [
Text(lo, style: style),
const Spacer(),
Text(hi, style: style),
],
);
}
}
/// Centred text showing the currently-selected range value (always visible).
class _SliderSelectedLabel extends StatelessWidget {
const _SliderSelectedLabel(this.label);
final String label;
@override
Widget build(BuildContext context) {
return Center(
child: Text(
label,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.primary,
),
),
);
}
}

View File

@ -0,0 +1,74 @@
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/screens/log_meal_progress.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:material_ui/material_ui.dart';
/// Writes [suggestion]'s name and macros into the log form's controllers.
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap.
void fillControllersFromSuggestion(
FoodSuggestion suggestion,
TextEditingController desc,
MacroControllers macros,
) {
desc.text = suggestion.name;
macros.fillFrom(suggestion.nutrition);
}
/// Builds the [Nutrition] for a submit from the form's macro controllers.
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Pure over
/// its inputs, so the per-portion scaling is testable without a widget.
Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
nutritionForPortion(
kcal: parseMacroField(macros.kcal),
proteinG: parseMacroField(macros.protein),
carbsG: parseMacroField(macros.carbs),
fatG: parseMacroField(macros.fat),
perGrams: parseMacroField(macros.perGrams),
ateGrams: parseMacroField(macros.grams),
source: source,
);
/// The destination buttons in [LogMealScreen]'s app bar, after [leading]
/// (the date picker).
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
/// the order of the buttons are unchanged.
List<Widget> logMealAppBarActions({
required VoidCallback onFoodBank,
required VoidCallback onHistory,
required VoidCallback onCalendar,
required VoidCallback onSettings,
required VoidCallback onBody,
List<Widget> leading = const [],
}) => [
...leading,
IconButton(
tooltip: 'Body',
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
onPressed: onBody,
),
IconButton(
tooltip: 'Foods',
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'),
onPressed: onFoodBank,
),
IconButton(
tooltip: 'History',
icon: const Icon(Icons.history, semanticLabel: 'History'),
onPressed: onHistory,
),
IconButton(
tooltip: 'Calendar',
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
onPressed: onCalendar,
),
IconButton(
tooltip: 'Sync',
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
onPressed: onSettings,
),
];

View File

@ -0,0 +1,137 @@
/// The sparkle button: send the typed text and/or photo to Claude.
///
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
/// ceiling. The transport is behind [ClaudeRelayClient]; this only drives the
/// button's states and shows the meal Claude logged.
///
/// The photo lives in [photo] for one send and nowhere else.
library;
import 'dart:async';
import 'dart:typed_data';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/log_entry_lookup.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_photo_source.dart';
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:diet_guard_app/widgets/meal_action_row.dart';
import 'package:material_ui/material_ui.dart';
/// Photo attach and the Claude send, for the log screen's state.
mixin LogMealClaudeMixin<T extends StatefulWidget>
on
LogMealSyncMixin<T>,
LogMealDueMixin<T>,
LogMealLoggedMixin<T>,
LogMealFutureMixin<T> {
/// The relay this screen sends through. Supplied by the screen.
ClaudeRelayClient get relay;
/// Where photos come from. Supplied by the screen.
MealPhotoSource get photoSource;
/// The food field. Supplied by the screen.
TextEditingController get claudeDesc;
/// The macro fields. Supplied by the screen.
MacroControllers get claudeMacros;
/// The sparkle button's state.
ClaudeButtonState claudeState = ClaudeButtonState.idle;
/// The attached photo's JPEG bytes, or null. Never stored or synced.
Uint8List? photo;
StreamSubscription<ClaudeRelayEvent>? _relaySub;
String? _pendingRid;
/// Whether there is something to send (a description or a photo).
bool get canSend =>
futureDate == null &&
(claudeDesc.text.trim().isNotEmpty || photo != null);
/// Attaches a photo from [origin]; backing out keeps the current one.
Future<void> attachPhoto(PhotoOrigin origin) async {
final bytes = await photoSource.pick(origin);
if (!mounted || bytes == null) return;
setState(() => photo = bytes);
}
/// Drops the attached photo.
void removePhoto() => setState(() => photo = null);
/// Sends the form to Claude and follows the request's events.
void sendToClaude() {
if (!canSend) return;
final request = ClaudeRelayRequest(
requestId: newRequestId(),
slotMinute: targetSlot,
mode: dueMode ? ClaudeRelayMode.due : ClaudeRelayMode.normal,
text: claudeDesc.text.trim(),
photoJpeg: photo,
);
unawaited(_relaySub?.cancel());
_pendingRid = request.requestId;
setState(() => claudeState = ClaudeButtonState.sending);
_relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e)));
}
Future<void> _onEvent(ClaudeRelayEvent event) async {
if (!mounted) return;
switch (event) {
case ClaudeRelayQueued():
setState(() => claudeState = ClaudeButtonState.queued);
case ClaudeRelayLocked():
_pendingRid = null;
setState(() => claudeState = ClaudeButtonState.locked);
case ClaudeRelayFailed():
_pendingRid = null;
setState(() => claudeState = ClaudeButtonState.error);
case ClaudeRelayLogged(:final entry):
_pendingRid = null;
// The worker logged it under the request id; the sync would deliver
// the same record, so this only shows it now and never doubles it.
final stored = await LogStorageService.instance.addIfAbsent(entry);
if (!mounted) return;
claudeDesc.clear();
claudeMacros.clear();
setState(() {
claudeState = ClaudeButtonState.idle;
photo = null;
});
showLogged([LoggedMeal(stored, LoggedOrigin.claude)]);
await publishAfterLog();
await refreshSlots();
}
}
/// Withdraws a request that is still in flight or queued, because the user
/// just logged the meal here instead.
///
/// Unclaimed: the node is deleted and the stream dropped. Already claimed
/// (the PC is mid-estimate): the meal will be logged, so the stream stays
/// open and its row shows with an undo rather than the entry turning up
/// unseen after the next sync. That race is accepted, see
/// `docs/DOCS-claude-relay.md`.
Future<void> withdrawClaude() async {
final rid = _pendingRid;
final waiting =
claudeState == ClaudeButtonState.sending ||
claudeState == ClaudeButtonState.queued;
if (rid == null || !waiting) return;
if (await relay.cancel(rid)) {
_pendingRid = null;
await _relaySub?.cancel();
}
}
/// Cancels the event subscription; call from `dispose`. A request still
/// queued on the PC reaches this phone through sync instead.
void disposeClaude() => unawaited(_relaySub?.cancel());
}

View File

@ -0,0 +1,89 @@
/// Due mode: some slot has elapsed with nothing logged.
///
/// The log screen then strips everything that is not "log this meal now" (the
/// app bar, sync banner, date row), hides the Android status bar, and targets
/// the oldest due slot with both the check and the sparkle. Its own file
/// because `log_meal_screen.dart` is at the repo's 250-line ceiling.
///
/// Slot arithmetic is not touched here: due slots come from `missingSlots`
/// and the nearest-slot rule from `slotForLog`, both in `models/slot.dart`.
library;
import 'dart:async';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';
/// The clock the log screen reads for "which slots are due".
///
/// A hook rather than a constructor argument so the whole screen suite can pin
/// it once (`flutter_test_config.dart` pins 07:00, before the first slot);
/// otherwise every nav and slot test would pass at night and fail by day, once
/// due mode hides the app bar.
@visibleForTesting
DateTime Function() logMealClock = DateTime.now;
/// Shows or hides the Android status bar.
///
/// `main.dart` sets no system-UI mode, so "visible" is the platform default:
/// both bars shown. [hidden] true is sticky-immersive; false puts both back.
@visibleForTesting
Future<void> Function({required bool hidden}) setStatusBarHidden = _setBars;
Future<void> _setBars({required bool hidden}) => hidden
? SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky)
: SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: SystemUiOverlay.values,
);
/// Due-mode state and slot targeting for the log screen's state.
mixin LogMealDueMixin<T extends StatefulWidget> on LogMealSyncMixin<T> {
/// Whether the first read of today's log has finished. Until then the
/// screen draws neither mode, so it never flashes the app bar and drops it.
bool slotsLoaded = false;
bool _statusBarHidden = false;
/// What the screen reads as "now" (see [logMealClock]).
DateTime get screenNow => logMealClock();
/// Elapsed slots with nothing logged, oldest first.
List<int> get dueSlots =>
missingSlots(screenNow, loggedSlots, MealScheduleService.current);
/// Whether the screen is in due mode.
bool get dueMode => slotsLoaded && dueSlots.isNotEmpty;
/// The slot a log or a send lands in: the oldest due slot, else the slot
/// nearest [screenNow] (`slotForLog`).
int get targetSlot => dueSlots.isNotEmpty
? dueSlots.first
: slotForLog(screenNow, MealScheduleService.current);
@override
Future<void> refreshSlots() async {
await super.refreshSlots();
if (!mounted) return;
setState(() => slotsLoaded = true);
await syncStatusBar();
}
/// Hides the status bar while in due mode and restores it on exit.
Future<void> syncStatusBar() async {
final hide = dueMode;
if (hide == _statusBarHidden) return;
_statusBarHidden = hide;
await setStatusBarHidden(hidden: hide);
}
/// Puts the status bar back; call from `dispose`.
void restoreStatusBar() {
if (!_statusBarHidden) return;
_statusBarHidden = false;
unawaited(setStatusBarHidden(hidden: false));
}
}

View File

@ -0,0 +1,169 @@
/// Lets the user pre-log a meal against a future date + slot instead of now.
///
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
///
/// Scoped to dates strictly after today: the date picker's `firstDate` is
/// tomorrow.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:material_ui/material_ui.dart';
/// Adds a future-date meal-log picker to [LogMealScreen]'s state.
mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
DateTime? _futureDate;
int? _futureSlot;
Set<int> _futureLoggedSlots = {};
MealSchedule? _futureSchedule;
/// The date currently chosen for a future log, or null when logging for
/// today through the screen's normal flow.
DateTime? get futureDate => _futureDate;
/// The slot chosen for [futureDate], or null until one is picked.
int? get futureSlot => _futureSlot;
/// Called after the picked date changes (including back to today), for
/// state keyed to the old date to drop itself. No-op unless overridden.
void onLogDateChanged() {}
/// Clears back to "log for today", dropping the picked date and slot.
void resetFutureLog() {
setState(() {
_futureDate = null;
_futureSlot = null;
_futureLoggedSlots = {};
_futureSchedule = null;
});
onLogDateChanged();
}
Future<void> _pickFutureDate() async {
final today = DateTime.now();
final tomorrow = DateTime(today.year, today.month, today.day + 1);
final picked = await pickDate(
context: context,
firstDate: tomorrow,
lastDate: tomorrow.add(const Duration(days: 365)),
initialDate: _futureDate ?? tomorrow,
);
if (picked == null || !mounted) return;
await selectLogDate(picked);
}
/// Switches the form to log against [picked] (strictly after today): what
/// the date picker does once a date is chosen.
Future<void> selectLogDate(DateTime picked) async {
final log = await LogStorageService.instance.readLog();
if (!mounted) return;
final day = localDateKey(picked);
final schedule = MealScheduleService.history.forDay(day);
// Snapped against the schedule for *that* day, the same rule as
// `loggedSlotsToday`: an exact match would show a pre-logged meal's slot
// as open again after a schedule edit, inviting a duplicate.
final logged = satisfiedSlots([
for (final entry in log[day] ?? const <FoodEntry>[])
if (!entry.deleted) ?entry.slotMinute,
], schedule);
setState(() {
_futureDate = picked;
_futureSchedule = schedule;
_futureLoggedSlots = logged;
_futureSlot = null;
});
onLogDateChanged();
}
/// The app bar's date actions: the picker (leftmost icon) and, once a date
/// is picked, a way back to today. A picked date tints the picker gold with
/// a small dot; no text is painted.
List<Widget> buildDateActions(BuildContext context) {
final date = _futureDate;
final gold = Theme.of(context).colorScheme.primary;
return [
IconButton(
// Not Icons.calendar_month: the bar's own "Calendar" nav button uses
// that, and two on screen make `find.byIcon` ambiguous.
icon: Stack(
clipBehavior: Clip.none,
children: [
Icon(
Icons.edit_calendar,
color: date == null ? null : gold,
semanticLabel: date == null ? 'Log for later' : 'Change date',
),
if (date != null)
Positioned(
top: -1,
right: -1,
child: Container(
key: const ValueKey('log-date-badge'),
width: 8,
height: 8,
decoration: BoxDecoration(
color: gold,
shape: BoxShape.circle,
),
),
),
],
),
onPressed: _pickFutureDate,
),
if (date != null)
IconButton(
icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
onPressed: resetFutureLog,
),
];
}
/// The slot row for a picked future date, else nothing.
///
/// Today has no slot row any more: the screen derives today's slot (the
/// oldest due one, else the nearest). A *future* date has no due slots to
/// derive from, so the row survives for exactly that case.
Widget buildSlotRow() {
final date = _futureDate;
if (date == null) return const SizedBox.shrink();
return SlotSelectorRow(
now: DateTime(date.year, date.month, date.day),
schedule: _futureSchedule,
loggedSlots: _futureLoggedSlots,
selectedSlot: _futureSlot,
onSlotSelected: (slot) => setState(() => _futureSlot = slot),
);
}
/// Resolves the slot/time to log against: the future pick when one is
/// active, otherwise [todaySlot] for now. `error` is set instead when a
/// future date is chosen but no slot on it has been picked yet.
({String? error, int? slot, DateTime? when}) resolveLogTarget(
int? todaySlot,
) {
final date = _futureDate;
if (date == null) return (error: null, slot: todaySlot, when: null);
final slot = _futureSlot;
if (slot == null) {
return (
error: 'Pick a slot for that date first.',
slot: null,
when: null,
);
}
return (
error: null,
slot: slot,
// The slot is a minute of day, not an hour: passing it as the hour
// argument would roll 720 (12:00) forward a whole month.
when: DateTime(date.year, date.month, date.day, slot ~/ 60, slot % 60),
);
}
}

View File

@ -0,0 +1,82 @@
/// The meals the screen logged for the user, shown below the action row with
/// an undo, plus the catering auto-log that fills the first of them.
///
/// The rows stay until the next meal is logged. Undo tombstones that one entry
/// by id (`deleteEntry`, never `undoLastToday`: several rows can be on screen,
/// and an auto-logged dish is not necessarily the newest entry), so the
/// deterministic catering id keeps blocking a re-log on the next open.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
import 'package:material_ui/material_ui.dart';
/// Logged-meal rows, undo and the catering auto-log.
mixin LogMealLoggedMixin<T extends StatefulWidget>
on LogMealSyncMixin<T>, LogMealDueMixin<T> {
/// The rows under the action row, oldest first.
List<LoggedMeal> loggedRows = const [];
/// The latest open-or-resume chain. Tests await it instead of guessing how
/// long real file I/O takes (a fixed sleep flaked under load).
@visibleForTesting
Future<void> openChain = Future<void>.value();
/// Replaces the rows with [meals]: a new log retires the previous ones.
void showLogged(List<LoggedMeal> meals) {
if (mounted) setState(() => loggedRows = meals);
}
/// Tombstones [meal]'s entry, drops its row and republishes.
Future<void> undoLogged(LoggedMeal meal) async {
final id = meal.entry.id;
if (id == null) return;
setState(() => loggedRows = [...loggedRows]..remove(meal));
await LogStorageService.instance.deleteEntry(id);
await publishAfterLog();
await refreshSlots();
}
/// Logs the delivered dishes of the due slots, no tap needed.
///
/// The old rule "a delivered meal is not an eaten meal" was overridden by
/// kuhy on 2026-11-17 ("LOG EVEN WITHOUT TAP"). Safe to call repeatedly: the
/// ids are deterministic (see `kuchnia_autolog.dart`).
Future<void> autoLogCatering() async {
if (!dueMode) return;
final entries = await KuchniaAutoLog.instance.logDue(dueSlots);
if (!mounted || entries.isEmpty) return;
showLogged([for (final e in entries) LoggedMeal(e, LoggedOrigin.catering)]);
await publishAfterLog();
await refreshSlots();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// A resume does what an open does, with one sync (autoSync is
// single-flight, so calling super too would let the auto-log run before
// the pull finished). Pause still pushes through the sync mixin.
if (state == AppLifecycleState.resumed) {
startOpenChain();
return;
}
super.didChangeAppLifecycleState(state);
}
/// Starts [onOpenedOrResumed] and keeps its future in [openChain].
void startOpenChain() => openChain = onOpenedOrResumed();
/// What a fresh open or a resume does: show the screen from the local log,
/// pull what other devices logged, then auto-log what is still due.
Future<void> onOpenedOrResumed() async {
unawaited(refreshSlots());
await autoSync();
await refreshSlots();
await autoLogCatering();
}
}

View File

@ -0,0 +1,69 @@
import 'package:diet_guard_app/screens/body_screen.dart';
import 'package:diet_guard_app/screens/calendar_screen.dart';
import 'package:diet_guard_app/screens/food_bank_screen.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
/// The five app-bar destinations reachable from [LogMealScreen].
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. The routes
/// are unchanged -- each pushes exactly the [MaterialPageRoute] it did before.
mixin LogMealNavMixin<T extends StatefulWidget> on State<T> {
/// The screen's injected HTTP client, forwarded to [SettingsScreen].
http.Client? get syncHttpClient;
/// Re-reads the meal schedule and today's logged slots.
///
/// Called when [SettingsScreen] pops, because the schedule editor lives
/// there: without it the slot row keeps rendering the schedule that was in
/// force when this screen was built, so switching from four meals to five
/// showed the old four checkpoints until the app was restarted. Verified on
/// the phone -- the settings preview and the reminder both updated while the
/// row behind them did not.
Future<void> onScheduleMayHaveChanged();
/// Pushes the entry history screen.
void onOpenHistory() {
Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => const HistoryScreen()));
}
/// Pushes the adherence calendar screen.
void onOpenCalendar() {
Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => const CalendarScreen()));
}
/// Pushes the Body screen (weight, BMI, calorie targets, week planner).
void onOpenBody() {
Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => const BodyScreen()));
}
/// Pushes the food bank screen.
void onOpenFoodBank() {
Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => const FoodBankScreen()));
}
/// Pushes the settings screen, forwarding the HTTP client.
///
/// Awaits the pop, unlike the other three: settings owns the meal-schedule
/// editor, so the slot row has to be rebuilt against whatever the user
/// chose there.
Future<void> onOpenSettings() async {
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => SettingsScreen(httpClient: syncHttpClient),
),
);
if (!mounted) return;
await onScheduleMayHaveChanged();
}
}

View File

@ -0,0 +1,57 @@
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:flutter/widgets.dart';
/// Reads a macro field as a number, treating blank or unparsable as zero.
double parseMacroField(TextEditingController controller) =>
double.tryParse(controller.text.trim()) ?? 0;
/// Summarises today from the log just written.
///
/// Takes the already-read [log] rather than re-reading, so the card can
/// never disagree with the write that produced it. [logged] is that write:
/// the card counts up from the totals without it.
TodayProgress buildTodayProgress(DayLog log, {FoodEntry? logged}) {
final budget = AppSettingsService.dailyKcalGoal;
final today = localDateKey(DateTime.now());
final entries = _live(log[today]);
final before = logged == null ? log : _without(log, logged.id);
final macros = sumMacros(entries);
return TodayProgress(
consumedKcal: sumKcal(entries),
budgetKcal: budget,
proteinG: macros.proteinG,
carbsG: macros.carbsG,
fatG: macros.fatG,
adherenceStreak: _streak(log),
loggedSlotMinute: logged == null ? null : _slotOf(logged),
loggedKcal: logged?.kcal,
previousKcal: logged == null ? null : sumKcal(_live(before[today])),
previousAdherenceStreak: logged == null ? null : _streak(before),
);
}
int _slotOf(FoodEntry entry) =>
entry.slotMinute ??
slotForLog(DateTime.parse(entry.time), MealScheduleService.current);
List<FoodEntry> _live(List<FoodEntry>? entries) =>
(entries ?? const <FoodEntry>[]).where((entry) => !entry.deleted).toList();
int _streak(DayLog log) =>
adherenceStreak(statusMap(log, schedule: BudgetHistoryService.schedule));
DayLog _without(DayLog log, String? id) => {
for (final MapEntry(:key, :value) in log.entries)
key: [
for (final entry in value)
if (entry.id != id) entry,
],
};

View File

@ -1,407 +1,248 @@
/// Single-food meal logging screen -- the app's primary, done-criterion
/// screen: "I can open the diet app on my phone and fill meal I ate."
///
/// Two modes. **Due mode** (a slot elapsed with nothing logged) shows only
/// what logging needs: the food field, suggestions, macros and the action row,
/// with the status bar hidden. **Normal mode** adds the app bar, the sync
/// banner and the date row. Either way the action row is photo / Claude /
/// log, and the field never moves between states.
library;
import 'dart:async';
import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/calendar_screen.dart';
import 'package:diet_guard_app/screens/food_bank_screen.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/screens/log_meal_actions.dart';
import 'package:diet_guard_app/screens/log_meal_claude_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_progress.dart';
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_feedback.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:diet_guard_app/services/meal_photo_source.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:diet_guard_app/widgets/meal_action_row.dart';
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
/// Lets the user log one food item, with food-bank autocomplete and
/// today's slot status.
/// Lets the user log one food item, with food-bank autocomplete.
class LogMealScreen extends StatefulWidget {
/// Creates a [LogMealScreen].
const LogMealScreen({super.key, this.httpClient});
const LogMealScreen({super.key, this.httpClient, this.relay, this.photos});
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
/// Production leaves this null so [GitHubClient] builds a real one.
final http.Client? httpClient;
/// Where the sparkle button sends; the app-wide [claudeRelay] when null.
final ClaudeRelayClient? relay;
/// Where photos come from; the camera/gallery picker when null.
final MealPhotoSource? photos;
@override
State<LogMealScreen> createState() => _LogMealScreenState();
}
class _LogMealScreenState extends State<LogMealScreen>
with WidgetsBindingObserver {
with
WidgetsBindingObserver,
LogMealSyncMixin<LogMealScreen>,
LogMealDueMixin<LogMealScreen>,
LogMealLoggedMixin<LogMealScreen>,
LogMealNavMixin<LogMealScreen>,
LogMealFutureMixin<LogMealScreen>,
LogMealClaudeMixin<LogMealScreen> {
@override
http.Client? get syncHttpClient => widget.httpClient;
@override
ClaudeRelayClient get relay => widget.relay ?? claudeRelay;
@override
late final MealPhotoSource photoSource =
widget.photos ?? ImagePickerPhotoSource();
final TextEditingController _descController = TextEditingController();
final MacroControllers _macros = MacroControllers();
@override
TextEditingController get claudeDesc => _descController;
@override
MacroControllers get claudeMacros => _macros;
List<FoodSuggestion> _suggestions = const [];
Set<int> _loggedSlots = {};
int? _selectedSlot;
String _source = 'manual';
String? _status;
CueState? _cue; // painted as a tinted icon, never as text
TodayProgress? _progress;
/// Single-flight guard so a launch sync and a lifecycle sync never overlap.
bool _autoSyncing = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_descController.addListener(_onDescChanged);
for (final controller in [
_macros.kcal,
_macros.protein,
_macros.carbs,
_macros.fat,
_macros.perGrams,
_macros.grams,
]) {
controller.addListener(_onMacroEdited);
}
_selectedSlot = slotForLog(DateTime.now());
unawaited(_refreshSlots());
_macros.addListenerToAll(_onMacroEdited);
unawaited(_onDescChanged());
unawaited(_autoSync());
// Health first, so a device that stalled earlier says so before a tick.
unawaited(refreshSyncHealth());
startOpenChain();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
disposeClaude();
restoreStatusBar();
_descController.dispose();
_macros.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Pull on resume (catch up on what another device logged while this one
// was backgrounded) and push on pause (keep the remote near-current).
final isResumeOrPause =
state == AppLifecycleState.resumed || state == AppLifecycleState.paused;
if (isResumeOrPause) {
unawaited(_autoSync());
}
}
/// Best-effort background sync: silent, skips when unconfigured, and never
/// overlaps itself. Failures are swallowed -- the Settings screen's manual
/// "Sync now" is where errors get surfaced. The try wraps even loading
/// [SyncSettings] itself: under `flutter test`, the shared_preferences and
/// secure-storage platform channels are unmocked by default and throw
/// [MissingPluginException], which must degrade exactly like "offline"
/// rather than crash every screen that mounts this widget.
///
/// [_refreshSlots] only runs after an actual sync (not on the unconfigured
/// path, which every existing screen test takes): a fire-and-forget tail
/// await here can resolve after a *later* test's `tearDown` has already
/// reset [LogStorageService]'s singleton -- `mounted` alone doesn't bound
/// that, since widget disposal between tests isn't synchronized with a
/// still-pending Future from an earlier one.
Future<void> _autoSync() async {
if (_autoSyncing) return;
_autoSyncing = true;
try {
final settings = await SyncSettings.load();
// Either backend counts. `isConfigured` means "has a GitHub token", so
// gating on it alone silently skips every sync on a device connected
// only to Firebase -- and once the mirror is retired that is every
// device. Same fix workout_app's push() already carries.
if (!settings.isConfigured && await openFirebase() == null) return;
final client = createGitHubClient(
settings,
httpClient: widget.httpClient,
);
try {
await runSync(await syncBackend(client));
} finally {
client.close();
}
if (!mounted) return;
await _refreshSlots();
} on Object catch (error, stackTrace) {
// Best-effort, but never silent: this swallowed the reason a desktop
// install could not publish at all, which looked identical to "nothing
// to sync". Offline and unmocked-platform-channel-under-test both land
// here too, so it stays non-fatal -- it just says why now.
log(
'diet_guard auto-sync failed',
level: 1000,
error: error,
stackTrace: stackTrace,
);
} finally {
_autoSyncing = false;
}
}
/// Queues the platform's offline push backstop so a meal logged while
/// offline still uploads on reconnect. The in-process [_autoSync] covers
/// the online case; this is the backstop (a no-op on web, which has no
/// out-of-page scheduler -- see background_tasks.dart).
// coverage:ignore-start
Future<void> _enqueueSyncBackstop() => enqueueSyncBackstop();
// coverage:ignore-end
Future<void> _refreshSlots() async {
final logged = await LogStorageService.instance.loggedSlotsToday();
if (!mounted) return;
setState(() => _loggedSlots = logged);
}
void _onMacroEdited() {
if (_source == 'food bank') {
setState(() => _source = 'manual');
}
if (_source == 'food bank') setState(() => _source = 'manual');
}
/// Re-runs the food-bank search and dismisses the previous progress card,
/// only while the field is non-empty: [_onLogMeal]'s own `clear()` fires
/// this listener too, and would otherwise race it and null the new card.
Future<void> _onDescChanged() async {
final matches = await FoodBankService.instance.search(
_descController.text,
);
final matches = await FoodBankService.instance.search(_descController.text);
if (!mounted) return;
setState(() {
_suggestions = matches;
// Typing the *next* meal dismisses the previous log's progress card.
// Guarded on non-empty text because _onLogMeal's own
// `_descController.clear()` also fires this listener: without the
// guard the two async chains race and the clear can null the card
// right after _onLogMeal set it, so the card never appears on device
// (in-memory test stores resolve fast enough to hide this).
if (_descController.text.isNotEmpty) _progress = null;
});
}
void _onSuggestionSelected(FoodSuggestion suggestion) {
_descController.text = suggestion.name;
_macros.kcal.text = suggestion.nutrition.kcal.toStringAsFixed(0);
_macros.protein.text = suggestion.nutrition.proteinG.toStringAsFixed(0);
_macros.carbs.text = suggestion.nutrition.carbsG.toStringAsFixed(0);
_macros.fat.text = suggestion.nutrition.fatG.toStringAsFixed(0);
_macros.perGrams.text = suggestion.nutrition.grams.toStringAsFixed(0);
_macros.grams.text = suggestion.nutrition.grams.toStringAsFixed(0);
fillControllersFromSuggestion(suggestion, _descController, _macros);
setState(() {
_source = 'food bank';
_suggestions = const [];
});
}
double _parse(TextEditingController controller) =>
double.tryParse(controller.text.trim()) ?? 0;
Future<void> _onLogMeal() async {
final desc = _descController.text.trim();
if (desc.isEmpty) {
setState(() {
_status = 'Type what you ate first.';
_progress = null;
});
if (desc.isEmpty) return;
final target = resolveLogTarget(targetSlot);
if (target.error != null) {
setState(() => _cue = CueState.next(_cue, CueKind.error, target.error!));
return;
}
final nutrition = nutritionForPortion(
kcal: _parse(_macros.kcal),
proteinG: _parse(_macros.protein),
carbsG: _parse(_macros.carbs),
fatG: _parse(_macros.fat),
perGrams: _parse(_macros.perGrams),
ateGrams: _parse(_macros.grams),
source: _source,
);
await LogStorageService.instance.logMeal(
LogFeedback.mealLogged(); // on the tap, before the write
unawaited(withdrawClaude()); // else Claude would log it a second time
final entry = await LogStorageService.instance.logMeal(
desc,
nutrition,
slot: _selectedSlot,
nutritionFromControllers(_macros, _source),
slotMinute: target.slot,
when: target.when,
);
final log = await LogStorageService.instance.readLog();
await FoodBankService.instance.rebuildAndPersist(log);
// Push the new meal now instead of waiting for the next lifecycle event,
// so the PC gate can see it in seconds. Fire-and-forget and best-effort:
// _autoSync is single-flight and swallows offline/transient failures.
unawaited(_autoSync());
// Offline backstop: if the push above fails (no connectivity), a
// connectivity-gated WorkManager task uploads the meal on reconnect.
unawaited(_enqueueSyncBackstop());
await _dismissStaleReminder();
resetFutureLog();
final log = await publishAfterLog();
if (!mounted) return;
_descController.clear();
_macros.clear();
setState(() {
_source = 'manual';
_selectedSlot = slotForLog(DateTime.now());
photo = null; // else a stale photo keeps the sparkle lit
claudeState = ClaudeButtonState.idle;
});
await _refreshSlots();
await refreshSlots();
if (!mounted) return;
showLogged([LoggedMeal(entry, LoggedOrigin.local)]);
setState(() {
_status = null;
_progress = _buildProgress(log, desc);
_cue = null;
_progress = buildTodayProgress(log, logged: entry);
});
}
/// Clears any reminder the meal just logged has now satisfied.
///
/// Without this a notification already on screen survives until the next
/// background tick (up to 15 minutes), which reads as a false alarm even
/// though the meal was logged on this very device. Passes
/// `pullWhenDue: false` because [_autoSync] above already owns the network
/// here and the local log is by definition the freshest copy.
///
/// [checkAndNotify] already swallows notification-platform failures, so
/// the meal -- written before this runs -- can never be lost to one.
Future<void> _dismissStaleReminder() => checkAndNotify(pullWhenDue: false);
/// Summarises today from the log just written.
///
/// Takes the already-read [log] rather than re-reading, so the card can
/// never disagree with the write that produced it.
TodayProgress _buildProgress(DayLog log, String desc) {
final budget = AppSettingsService.dailyKcalGoal;
final today = localDateKey(DateTime.now());
final entries = (log[today] ?? const <FoodEntry>[])
.where((entry) => !entry.deleted)
.toList();
final macros = sumMacros(entries);
return TodayProgress(
justLogged: desc,
consumedKcal: sumKcal(entries),
budgetKcal: budget,
proteinG: macros.proteinG,
carbsG: macros.carbsG,
fatG: macros.fatG,
adherenceStreak: adherenceStreak(
statusMap(log, schedule: BudgetHistoryService.schedule),
),
);
}
void _onOpenHistory() {
unawaited(
Navigator.of(context).push<void>(
MaterialPageRoute(builder: (_) => const HistoryScreen()),
),
);
}
void _onOpenCalendar() {
unawaited(
Navigator.of(context).push<void>(
MaterialPageRoute(builder: (_) => const CalendarScreen()),
),
);
}
void _onOpenFoodBank() {
unawaited(
Navigator.of(context).push<void>(
MaterialPageRoute(builder: (_) => const FoodBankScreen()),
),
);
}
void _onOpenSettings() {
unawaited(
Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => SettingsScreen(httpClient: widget.httpClient),
),
),
);
}
@override
Widget build(BuildContext context) {
if (!slotsLoaded) return const Scaffold();
final due = dueMode;
// Dimmed while Claude works, but never moved: nothing is added around it.
final busy = claudeState == ClaudeButtonState.sending;
// Hard rule: nothing sits under the keyboard, so the extras collapse.
final typing = MediaQuery.viewInsetsOf(context).bottom > 0;
final dim = busy || claudeState == ClaudeButtonState.queued;
return Scaffold(
appBar: AppBar(
title: const Text('Diet Guard'),
actions: [
IconButton(
icon: const Icon(Icons.restaurant_menu),
tooltip: 'Food bank',
onPressed: _onOpenFoodBank,
),
IconButton(
icon: const Icon(Icons.history),
tooltip: 'History',
onPressed: _onOpenHistory,
),
IconButton(
icon: const Icon(Icons.calendar_month),
tooltip: 'Calendar',
onPressed: _onOpenCalendar,
),
IconButton(
icon: const Icon(Icons.settings),
tooltip: 'Sync settings',
onPressed: _onOpenSettings,
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SlotSelectorRow(
now: DateTime.now(),
loggedSlots: _loggedSlots,
selectedSlot: _selectedSlot,
onSlotSelected: (slot) => setState(() => _selectedSlot = slot),
appBar: due
? null
: AppBar(
actions: logMealAppBarActions(
onFoodBank: onOpenFoodBank,
onHistory: onOpenHistory,
onCalendar: onOpenCalendar,
onSettings: onOpenSettings,
onBody: onOpenBody,
leading: buildDateActions(context),
),
),
const SizedBox(height: 8),
TextField(
controller: _descController,
decoration: const InputDecoration(labelText: 'What did you eat?'),
),
AutocompleteSuggestionList(
suggestions: _suggestions,
onSelected: _onSuggestionSelected,
compact: true,
),
const SizedBox(height: 8),
MacroInputRow(controllers: _macros, compact: true),
const SizedBox(height: 8),
Row(
children: [
const Spacer(),
Tooltip(
message: 'Log meal',
child: FilledButton(
onPressed: _onLogMeal,
child: const Icon(Icons.check_circle),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!due) SyncHealthBanner(status: syncHealth),
buildSlotRow(),
Opacity(
opacity: dim ? 0.5 : 1,
child: IgnorePointer(
ignoring: busy,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconField(
controller: _descController,
icon: Icons.fastfood,
semanticLabel: 'What did you eat?',
onChanged: (_) => setState(() {}),
),
AutocompleteSuggestionList(
suggestions: _suggestions,
onSelected: _onSuggestionSelected,
compact: true,
compactLimit: due ? 2 : 3,
reserveHeight: due,
),
const SizedBox(height: AppSpacing.sm),
MacroInputRow(controllers: _macros, compact: true),
],
),
),
),
const SizedBox(height: AppSpacing.sm),
MealActionRow(
claude: claudeState,
photoAttached: photo != null,
canSend: canSend,
canLog: _descController.text.trim().isNotEmpty,
onPhoto: () => unawaited(attachPhoto(PhotoOrigin.camera)),
onGallery: () => unawaited(attachPhoto(PhotoOrigin.gallery)),
onRemovePhoto: removePhoto,
onSend: sendToClaude,
onLog: _onLogMeal,
),
if (!typing)
for (final meal in loggedRows)
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
if (_cue != null) ...[
const SizedBox(height: AppSpacing.sm),
_cue!.widget,
],
if (_progress != null && !due && !typing) ...[
const SizedBox(height: AppSpacing.sm),
TodayProgressCard(progress: _progress!),
],
),
// Mutually exclusive: _status carries a validation complaint,
// _progress the post-log summary. A successful log clears one
// and sets the other, so the two never stack.
if (_status != null) ...[
const SizedBox(height: AppSpacing.sm),
Text(_status!),
],
if (_progress != null) ...[
const SizedBox(height: AppSpacing.sm),
TodayProgressCard(progress: _progress!),
],
],
),
),
),
);

View File

@ -0,0 +1,183 @@
import 'dart:async';
import 'dart:developer';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/health_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_attempt.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. It is a
/// mixin rather than a helper class because the behaviour is inseparable from
/// the State it drives: it observes the widget lifecycle, calls `setState`,
/// and reads `mounted`. The screen's own fields stay declared on the State and
/// are reached here through the abstract members below, so the split moves
/// behaviour without moving ownership of the widget's state.
mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
implements WidgetsBindingObserver {
/// Single-flight guard so a launch sync and a lifecycle sync never overlap.
bool autoSyncing = false;
/// Latest sync health, driving the "not syncing" banner. Null until read.
SyncHealthStatus? syncHealth;
/// The slots that already carry a logged meal today.
Set<int> loggedSlots = {};
/// The screen's injected HTTP client, or null to use the default.
///
/// Declared abstract so the mixin stays independent of the widget's own
/// field: `widget` is typed `T` here, so `widget.httpClient` would not
/// resolve. The State supplies it.
http.Client? get syncHttpClient;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Pull on resume (catch up on what another device logged while this one
// was backgrounded) and push on pause (keep the remote near-current).
final isResumeOrPause =
state == AppLifecycleState.resumed || state == AppLifecycleState.paused;
if (isResumeOrPause) {
unawaited(autoSync());
}
}
/// Best-effort background sync: silent, skips when unconfigured, and never
/// overlaps itself. Failures are swallowed -- the Settings screen's manual
/// "Sync now" is where errors get surfaced. The try wraps even loading
/// [SyncSettings] itself: under `flutter test`, the shared_preferences and
/// secure-storage platform channels are unmocked by default and throw
/// [MissingPluginException], which must degrade exactly like "offline"
/// rather than crash every screen that mounts this widget.
///
/// [refreshSlots] only runs after an actual sync (not on the unconfigured
/// path, which every existing screen test takes): a fire-and-forget tail
/// await here can resolve after a *later* test's `tearDown` has already
/// reset [LogStorageService]'s singleton -- `mounted` alone doesn't bound
/// that, since widget disposal between tests isn't synchronized with a
/// still-pending Future from an earlier one.
Future<void> autoSync() async {
if (autoSyncing) return;
autoSyncing = true;
bool? landed; // null until the sync itself ran
try {
final settings = await SyncSettings.load();
// Either backend counts. `isConfigured` means "has a GitHub token", so
// gating on it alone silently skips every sync on a device connected
// only to Firebase -- and once the mirror is retired that is every
// device. Same fix workout_app's push() already carries.
if (!settings.isConfigured && await openFirebase() == null) {
// Never a silent return: an unconfigured device looked exactly like a
// healthy one with nothing to send, which is how meals sat unpublished
// for days. Recorded so the banner can say so.
log(
'diet_guard auto-sync: no backend configured; nothing to push',
level: 900,
);
await SyncHealth.recordUnconfigured();
if (mounted) await refreshSyncHealth();
return;
}
final client = createGitHubClient(settings, httpClient: syncHttpClient);
landed = await attemptSync(() async {
try {
// Foreground only (this mixin is UI), and never prompts: fresh
// Health Connect steps ride along in this tick's body.json.
await refreshSteps();
await runSync(await syncBackend(client));
} finally {
client.close();
}
});
if (!mounted) return;
// Outside attemptSync: a refresh error is no sync failure.
if (landed) await refreshSlots();
await refreshSyncHealth();
} on Object catch (error, stackTrace) {
// Best-effort, but never silent: this swallowed the reason a desktop
// install could not publish at all, which looked identical to "nothing
// to sync". Offline and unmocked-platform-channel-under-test both land
// here too, so it stays non-fatal -- it just says why now.
log(
'diet_guard auto-sync failed',
level: 1000,
error: error,
stackTrace: stackTrace,
);
// attemptSync already recorded the sync's own outcome; only a failure
// before it (loading settings) is one here.
if (landed == null) await SyncHealth.recordFailure();
if (mounted) await refreshSyncHealth();
} finally {
autoSyncing = false;
}
}
/// Re-reads sync health so the banner reflects the tick that just ran.
Future<void> refreshSyncHealth() async {
final status = await SyncHealth.read();
if (!mounted) return;
setState(() => syncHealth = status);
}
/// Queues the platform's offline push backstop so a meal logged while
/// offline still uploads on reconnect. The in-process [autoSync] covers
/// the online case; this is the backstop (a no-op on web, which has no
/// out-of-page scheduler -- see background_tasks.dart).
// coverage:ignore-start
/// Schedules the WorkManager backstop that syncs when the app is closed.
Future<void> enqueueSyncBackstopTask() => enqueueSyncBackstop();
// coverage:ignore-end
/// Everything that must follow a write to the food log, shared by the
/// manual submit and "Fill all" so a batch fill publishes exactly like a
/// typed meal. Call it once per batch, not per entry: [autoSync] is
/// single-flight, so a second call while the first is in flight is dropped
/// and the later entries would wait for the next tick.
///
/// Returns the log as read after the write.
Future<DayLog> publishAfterLog() async {
final log = await LogStorageService.instance.readLog();
await FoodBankService.instance.rebuildAndPersist(log);
// Push the new meal now instead of waiting for the next lifecycle event,
// so the PC gate can see it in seconds. Fire-and-forget and best-effort:
// autoSync is single-flight and swallows offline/transient failures.
unawaited(autoSync());
// Offline backstop: if the push above fails (no connectivity), a
// connectivity-gated WorkManager task uploads the meal on reconnect.
unawaited(enqueueSyncBackstopTask());
// Clears a reminder the meal just logged has now satisfied; without it a
// notification already on screen survives up to 15 min and reads as a
// false alarm. `pullWhenDue: false` because `autoSync` above already owns
// the network for this submit.
await checkAndNotify(pullWhenDue: false);
return log;
}
/// Re-reads which meal slots are already logged today.
Future<void> refreshSlots() async {
final logged = await LogStorageService.instance.loggedSlotsToday();
if (!mounted) return;
setState(() => loggedSlots = logged);
}
/// Re-derives the due slots after the settings screen pops.
///
/// The meal-schedule editor lives in settings, and which slots are due (and
/// so whether the screen is in due mode) reads `MealScheduleService.current`
/// at refresh time. Found on the phone: without this the settings preview
/// and the overdue reminder both updated while the screen behind them kept
/// the old checkpoints until the app was restarted.
Future<void> onScheduleMayHaveChanged() => refreshSlots();
}

View File

@ -0,0 +1,69 @@
// The debounced daily-kcal-goal field and the battery-exemption request.
//
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
// mixin: these drive the screen's private state and call `setState`, which is
// `@protected` and therefore unreachable from an extension.
part of 'settings_screen.dart';
mixin _SettingsKcalGoal on State<SettingsScreen> {
/// The latest outcome as an icon cue; null until something happened.
Widget? _status;
void _showCue(CueKind kind, String semanticLabel) {
if (!mounted) return;
setState(
() => _status = StatusCue(
key: UniqueKey(),
kind: kind,
semanticLabel: semanticLabel,
),
);
}
Timer? _kcalGoalDebounce;
int? _pendingKcalGoal;
/// Persists the pending goal, if any, and clears it.
void _flushKcalGoal() {
final goal = _pendingKcalGoal;
if (goal == null) return;
_pendingKcalGoal = null;
unawaited(AppSettingsService.instance.saveDailyKcalGoal(goal));
}
/// Saves the typed goal once typing settles.
///
/// Debounced because every keystroke would otherwise be a real edit:
/// typing "2000" saved 2, 20, 200, 2000 in turn, and a sync tick landing
/// between keystrokes would push a nonsense budget to the other device.
void _onKcalGoalChanged(String value) {
_kcalGoalDebounce?.cancel();
final goal = int.tryParse(value);
if (goal == null || goal <= 0) return;
_pendingKcalGoal = goal;
_kcalGoalDebounce = Timer(
const Duration(milliseconds: 600),
_flushKcalGoal,
);
}
/// Requests exemption from OEM battery optimization (MIUI, some Samsung
/// configs), which can otherwise degrade the 15-minute background-check
/// reliability well past its accepted ±15 min target.
Future<void> _requestBatteryExemption() async {
final request =
widget.requestBatteryExemption ??
() => Permission.ignoreBatteryOptimizations.request();
try {
final status = await request();
if (status.isGranted) {
_showCue(CueKind.ok, 'Battery optimization exemption granted.');
} else {
_showCue(CueKind.warn, 'Exemption not granted.');
}
} on Exception catch (e) {
_showCue(CueKind.error, 'Could not request exemption: $e');
}
}
}

View File

@ -0,0 +1,210 @@
/// The catering-panel credential section of the settings screen.
///
/// Its own file because `settings_screen.dart` sits at the repo's 250-line
/// ceiling.
///
/// Two things about this section are deliberate:
///
/// * **The fields show on every platform, the fetch button only on Android.**
/// The panel sends no CORS headers, so a browser cannot call it -- but the
/// desktop app is where the user is most likely to be typing a password, and
/// the credential syncs, so hiding the fields there would mean the phone
/// could only ever be set up by typing on the phone.
/// * **The password is stored and synced in plaintext**, and the section says
/// so rather than implying otherwise. The rest of the synced state is not
/// encrypted either.
library;
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart';
/// What a delivery fetch reports: a cue [kind], a spoken [label] (never
/// painted) and, when dishes were banked, their [count] (painted as a number).
class FetchOutcome {
/// Creates an outcome.
const FetchOutcome(this.kind, this.label, {this.count});
/// Icon/colour of the cue.
final CueKind kind;
/// Spoken description; never painted.
final String label;
/// Dishes banked, shown as a bare number next to the cue.
final int? count;
}
/// Fetches today's delivery and reports what was banked.
///
/// Deliberately "banked", not "logged": the explicit fetch only fills the
/// food bank; logging is the log screen's auto-log (`kuchnia_autolog.dart`).
/// Top-level so the settings screen can pass it without growing.
Future<FetchOutcome> fetchTodaysDelivery() async {
final result = await refreshDelivery(DateTime.now());
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);
if (result.dishes.isEmpty) {
return const FetchOutcome(CueKind.warn, 'No delivery found for today.');
}
final count = result.dishes.length;
return FetchOutcome(CueKind.ok, '$count dishes added', count: count);
}
/// Credential fields plus, on Android, a "fetch today's delivery" action.
class KuchniaSettingsSection extends StatefulWidget {
/// Creates the section.
///
/// [canFetch] defaults to [kuchniaFetchSupported] -- false on web, where the
/// button is replaced by a one-line explanation rather than silently
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
/// widget test can drive the section without a network or a platform check.
const KuchniaSettingsSection({this.canFetch, this.onFetch, super.key});
/// Whether this platform can reach the catering panel; null means ask.
final bool? canFetch;
/// Fetches today's delivery and returns a status line; null means the real
/// one.
final Future<FetchOutcome> Function()? onFetch;
@override
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
}
class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
late final TextEditingController _username = TextEditingController(
text: KuchniaCredentialService.username,
);
late final TextEditingController _password = TextEditingController(
text: KuchniaCredentialService.password,
);
bool _obscured = true;
bool _busy = false;
Widget? _status;
@override
void dispose() {
_username.dispose();
_password.dispose();
super.dispose();
}
Future<void> _save() async {
if (!KuchniaCredentialService.isInitialized) return;
await KuchniaCredentialService.instance.save(
_username.text,
_password.text,
);
if (!mounted) return;
setState(
() => _status = StatusCue(
key: UniqueKey(),
kind: CueKind.ok,
semanticLabel: 'Saved. It will sync to your other devices.',
),
);
}
Future<void> _fetch() async {
setState(() {
_busy = true;
_status = null;
});
final outcome = await (widget.onFetch ?? fetchTodaysDelivery)();
if (!mounted) return;
setState(() {
_busy = false;
_status = Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.sm,
children: [
StatusCue(
key: UniqueKey(),
kind: outcome.kind,
semanticLabel: outcome.label,
),
if (outcome.count != null) Text('${outcome.count}'),
],
);
});
}
@override
Widget build(BuildContext context) {
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
// The section owns its own leading divider so the settings screen needs a
// single line for it -- that file sits on the repo's 250-line ceiling.
// No heading or blurb: the delivery truck on the fetch button names it.
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: IconField(
icon: Icons.alternate_email,
semanticLabel: 'Panel e-mail',
controller: _username,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
onSubmitted: (_) => _save(),
),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: IconField(
icon: Icons.key,
semanticLabel: 'Panel password',
controller: _password,
obscure: _obscured,
autocorrect: false,
onSubmitted: (_) => _save(),
suffix: IconButton(
icon: Icon(
_obscured ? Icons.visibility : Icons.visibility_off,
semanticLabel: _obscured ? 'Show password' : 'Hide password',
),
onPressed: () => setState(() => _obscured = !_obscured),
),
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
IconButton.filled(
onPressed: _save,
icon: const Icon(Icons.check, semanticLabel: 'Save login'),
),
// Browser builds show the button greyed out: the panel blocks
// browser requests, and the disabled state is the cue.
IconButton.outlined(
onPressed: canFetch && !_busy ? _fetch : null,
icon: _busy
? const WaitWatch(
operation: 'kuchnia.sync',
child: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
)
: const Icon(
Icons.local_shipping_outlined,
semanticLabel: "Fetch today's delivery",
),
),
],
),
if (_status != null) ...[const SizedBox(height: 8), _status!],
],
);
}
}

View File

@ -0,0 +1,35 @@
// The meal-schedule section: owns the schedule state and its persistence;
// the widgets themselves live in `widgets/meal_schedule_editor.dart`.
//
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
// private state and calls `setState`.
part of 'settings_screen.dart';
mixin _SettingsMealSchedule on State<SettingsScreen> {
MealSchedule _schedule = kDefaultSchedule;
void _loadSchedule() {
_schedule = MealScheduleService.current;
}
Future<void> _applySchedule(MealSchedule next) async {
final normalized = next.normalized();
setState(() => _schedule = normalized);
if (!MealScheduleService.isInitialized) return;
await MealScheduleService.instance.recordChange(normalized);
// The reminder ids are slot minutes, so a schedule change leaves posted
// reminders for checkpoints that no longer exist. Re-running the check
// cancels them immediately rather than leaving a stale nag until the
// next background tick.
await checkAndNotify(pullWhenDue: false);
}
List<Widget> _mealScheduleSection(BuildContext context) => [
MealScheduleEditor(
schedule: _schedule,
onChanged: (next) => unawaited(_applySchedule(next)),
),
];
}

View File

@ -1,40 +1,57 @@
/// Sync configuration. Primary path: "Connect Firebase" — sign in with the
/// shared sync account, whose password is kept in the OS keystore. GitHub is
/// only the cutover mirror, so its whole setup (device-flow OAuth, owner/repo,
/// client id, PAT fallback) sits under "Advanced (GitHub mirror)" rather than
/// competing with Firebase as a visible choice. Auto-sync (app launch +
/// lifecycle pause/resume) lives in [LogMealScreen] and is silent on failure
/// -- this screen is where errors get surfaced, as inline status text.
/// App settings: kcal goal, notifications, data export/import, and links to
/// the shared Firebase "Sync settings" and the app-local GitHub mirror (its
/// connect also runs a real `runSync`, which the shared screen does not).
library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show E2ePassphraseButton;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_e2e.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/data_backup_row.dart';
import 'package:diet_guard_app/widgets/log_sound_tile.dart';
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:kuhy_credit/kuhy_credit.dart';
import 'package:material_ui/material_ui.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:sync_settings_ui/sync_settings_ui.dart';
/// Screen for configuring and triggering cross-device sync.
part 'settings_kcal_goal.dart';
part 'settings_meal_schedule.dart';
/// Screen for app-specific settings and links to sync configuration.
class SettingsScreen extends StatefulWidget {
/// Creates a [SettingsScreen].
const SettingsScreen({
super.key,
this.httpClient,
this.requestBatteryExemption,
this.googleFirebaseFactory,
this.googleAvailable,
this.accountLoader,
this.accountSaver,
this.accountClearer,
this.sessionProbe,
this.firebaseFactory,
});
/// Injectable HTTP client; tests pass a [MockClient].
/// HTTP client for the linked [GitHubMirrorScreen]; tests pass [MockClient].
final http.Client? httpClient;
/// Injectable battery-optimization-exemption request; tests pass a fake.
@ -42,60 +59,50 @@ class SettingsScreen extends StatefulWidget {
/// `Permission.ignoreBatteryOptimizations.request()`.
final Future<PermissionStatus> Function()? requestBatteryExemption;
/// Builds the Firebase backend via Google sign-in, for the shared Sync
/// settings screen. Injected so tests need no platform channel -- the
/// plugin reaches the OS account picker.
final Future<FirebaseRestClient?> Function()? googleFirebaseFactory;
/// Whether to offer the Google button. Defaults to what the platform
/// supports; injected by tests, whose host reports unsupported.
final bool? googleAvailable;
/// Reads the stored Firebase account. Injected for the same reason as
/// [googleFirebaseFactory]: the keystore is a platform channel.
///
/// Backed by [storedAccount], not [loadAccount]: the shared screen reads
/// the account back right after a Google sign-in, and [loadAccount]'s
/// desktop fallback throws on Android (seen on the phone as "Google sign-in
/// failed"). See the keystore-only read in [firebase_backend.dart].
final Future<FirebaseAccount?> Function()? accountLoader;
/// Persists the account. See [accountLoader].
final Future<void> Function(FirebaseAccount)? accountSaver;
/// Forgets the account and any cached session. See [accountLoader].
final Future<void> Function()? accountClearer;
/// Whether a Firebase session is stored. See [accountLoader].
final Future<bool> Function()? sessionProbe;
/// Builds the Firebase backend from the stored account. Injected so tests
/// can supply a fake.
final Future<FirebaseRestClient?> Function()? firebaseFactory;
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
class _SettingsScreenState extends State<SettingsScreen>
with _SettingsKcalGoal, _SettingsMealSchedule {
final _kcalGoalController = TextEditingController();
final _ownerController = TextEditingController();
final _repoController = TextEditingController();
final _tokenController = TextEditingController();
final _clientIdController = TextEditingController();
final _firebaseEmailController = TextEditingController();
final _firebasePasswordController = TextEditingController();
bool _firebaseConfigured = false;
bool _loading = true;
bool _busy = false;
String? _status;
@override
void initState() {
super.initState();
unawaited(_load());
}
/// Loads saved settings, defaulting to blank fields if loading itself
/// fails (e.g. no secret service available yet) -- the screen must still
/// render, not spin forever, so the user can fill them in from scratch.
Future<void> _load() async {
SyncSettings settings;
try {
settings = await SyncSettings.load();
} on Exception {
settings = const SyncSettings(owner: '', repo: '', token: '');
}
if (!mounted) return;
_kcalGoalController.text = AppSettingsService.dailyKcalGoal.toString();
_ownerController.text = settings.owner;
_repoController.text = settings.repo;
// On web the stored "token" is only a stand-in for one the desktop
// wrapper holds (see TokenVault); showing it would invite the user to
// edit a literal. [_storedToken] keeps it for round-tripping.
_storedToken = settings.token;
_tokenController.text = SyncSettings.exposesTokenValue
? settings.token
: '';
_clientIdController.text = settings.clientId;
// Reflect a previously-stored account, so a returning user sees the
// real state instead of an empty form that looks unconfigured.
final account = await loadAccount();
if (!mounted) return;
if (account != null) _firebaseEmailController.text = account.email;
setState(() {
_firebaseConfigured = account != null;
_loading = false;
});
_loadSchedule();
}
@override
@ -105,180 +112,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
// the edit the user just typed.
_flushKcalGoal();
_kcalGoalController.dispose();
_ownerController.dispose();
_repoController.dispose();
_tokenController.dispose();
_firebaseEmailController.dispose();
_firebasePasswordController.dispose();
_clientIdController.dispose();
super.dispose();
}
/// The token as loaded, so a platform that cannot display it (web) still
/// round-trips it instead of blanking it on the next save.
String _storedToken = '';
Timer? _kcalGoalDebounce;
int? _pendingKcalGoal;
/// Persists the pending goal, if any, and clears it.
void _flushKcalGoal() {
final goal = _pendingKcalGoal;
if (goal == null) return;
_pendingKcalGoal = null;
unawaited(AppSettingsService.instance.saveDailyKcalGoal(goal));
}
/// Saves the typed goal once typing settles.
///
/// Debounced because every keystroke would otherwise be a real edit:
/// typing "2000" saved 2, 20, 200, 2000 in turn, and a sync tick landing
/// between keystrokes would push a nonsense budget to the other device.
void _onKcalGoalChanged(String value) {
_kcalGoalDebounce?.cancel();
final goal = int.tryParse(value);
if (goal == null || goal <= 0) return;
_pendingKcalGoal = goal;
_kcalGoalDebounce = Timer(
const Duration(milliseconds: 600),
_flushKcalGoal,
);
}
SyncSettings _currentSettings() {
final typed = _tokenController.text.trim();
return SyncSettings(
owner: _ownerController.text.trim(),
repo: _repoController.text.trim(),
// The `_storedToken` side is web-only (the wrapper holds the real
// token), so it is unreachable from a VM test.
token: typed.isEmpty && !SyncSettings.exposesTokenValue
// coverage:ignore-line
? _storedToken
: typed,
clientId: _clientIdController.text.trim(),
);
}
void _showMessage(String message) {
if (!mounted) return;
setState(() => _status = message);
}
/// Runs the OAuth device flow and, on success, fills in the token field.
Future<void> _connectGitHub() async {
var clientId = _clientIdController.text.trim();
if (clientId.isEmpty) {
final entered = await showDialog<String>(
context: context,
builder: (_) => const _ClientIdSetupDialog(),
);
if (entered == null || entered.isEmpty) return;
clientId = entered;
if (!mounted) return;
setState(() => _clientIdController.text = clientId);
await _currentSettings().save();
}
final auth = createDeviceAuth(clientId, httpClient: widget.httpClient);
try {
final device = await auth.requestDeviceCode();
if (!mounted) return;
final token = await showDialog<String>(
context: context,
barrierDismissible: false,
builder: (_) => _DeviceCodeDialog(device: device, auth: auth),
);
if (token != null && token.isNotEmpty) {
setState(() {
_storedToken = token;
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
});
_showMessage('Connected — syncing…');
await _currentSettings().save();
await _syncAfterConnect();
}
} on Exception catch (e) {
_showMessage('Could not start device flow: $e');
} finally {
auth.close();
}
}
/// Runs a sync right after connecting so the device-flow token is proven
/// to work immediately, with clear confirmation either way.
Future<void> _syncAfterConnect() async {
final settings = _currentSettings();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
await runSync(await syncBackend(client));
_showMessage('Connected and synced.');
} on Exception catch (e) {
_showMessage('Connected, but sync failed: $e');
} finally {
client.close();
}
}
Future<void> _save() async {
setState(() => _busy = true);
await _currentSettings().save();
if (!mounted) return;
setState(() => _busy = false);
_showMessage('Saved.');
}
Future<void> _testConnection() async {
setState(() => _busy = true);
final settings = _currentSettings();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
final ok = await client.canAccessRepo();
_showMessage(
ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
);
} on Exception catch (e) {
_showMessage('GitHub connection failed: $e');
} finally {
client.close();
if (mounted) setState(() => _busy = false);
}
}
Future<void> _syncNow() async {
setState(() => _busy = true);
final settings = _currentSettings();
await settings.save();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
await runSync(await syncBackend(client));
_showMessage('Synced.');
} on Exception catch (e) {
_showMessage('Sync failed: $e');
} finally {
client.close();
if (mounted) setState(() => _busy = false);
}
}
/// Requests exemption from OEM battery optimization (MIUI, some Samsung
/// configs), which can otherwise degrade the 15-minute background-check
/// reliability well past its accepted ±15 min target.
Future<void> _requestBatteryExemption() async {
final request =
widget.requestBatteryExemption ??
() => Permission.ignoreBatteryOptimizations.request();
try {
final status = await request();
_showMessage(
status.isGranted
? 'Battery optimization exemption granted.'
: 'Exemption not granted -- notifications may be delayed.',
);
} on Exception catch (e) {
_showMessage('Could not request exemption: $e');
}
}
/// True on the one platform with OEM battery optimization to exempt from.
///
/// Uses [defaultTargetPlatform] rather than `Platform.isAndroid` because
@ -286,293 +122,125 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool get _isAndroid =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
/// Stores the Firebase account in the OS keystore and proves it works.
///
/// Signing in here rather than only saving means a typo surfaces now, on
/// the screen where it can be fixed, instead of as a silently failed
/// background sync hours later.
Future<void> _saveFirebaseAccount() async {
final email = _firebaseEmailController.text.trim();
final password = _firebasePasswordController.text;
if (email.isEmpty || password.isEmpty) {
setState(() => _status = 'Enter the sync account email and password.');
return;
}
setState(() {
_busy = true;
_status = null;
});
try {
await saveAccount(FirebaseAccount(email: email, password: password));
final client = await openFirebase();
if (client == null) {
throw Exception('could not reach Firebase');
}
final reachable = await client.canAccessRemote();
client.close();
if (!mounted) return;
setState(() {
_firebaseConfigured = reachable;
_status = reachable
? 'Firebase connected - syncs now go there first.'
: 'Signed in, but the database refused the read.';
});
} on Object catch (error) {
// Broader than Exception: a missing platform binding raises an Error.
// A half-stored account is worse than none, so forget it.
await clearAccount();
if (!mounted) return;
setState(() {
_firebaseConfigured = false;
_status = 'Firebase sign-in failed: $error';
});
} finally {
if (mounted) setState(() => _busy = false);
}
Future<void> _openSyncSettings() async {
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => SyncSettingsScreen(
accountLoader: widget.accountLoader ?? storedAccount,
accountSaver: widget.accountSaver ?? saveAccount,
accountClearer: widget.accountClearer ?? clearAccount,
sessionProbe: widget.sessionProbe ?? isFirebaseConfigured,
firebaseFactory: widget.firebaseFactory ?? openFirebase,
googleFirebaseFactory:
widget.googleFirebaseFactory ?? openFirebaseWithGoogle,
googleAvailable: widget.googleAvailable ?? googleSignInSupported,
),
),
);
}
/// Forgets the Firebase account, so sync falls back to GitHub alone.
Future<void> _disconnectFirebase() async {
await clearAccount();
_firebaseEmailController.clear();
_firebasePasswordController.clear();
if (!mounted) return;
setState(() {
_firebaseConfigured = false;
_status = 'Firebase disconnected - syncing over GitHub only.';
});
Future<void> _openGitHubMirror() async {
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => GitHubMirrorScreen(httpClient: widget.httpClient),
),
);
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
// Centred and capped at the prose width. On the desktop surface this
// ListView spanned the full ~1366px window, so the explanatory
// paragraphs below ran ~180 characters per line -- roughly twice the
// readable limit (tokens.md rule 21) -- and every field stretched with
// them. Invisible on the phone, where the window is already narrow.
// No title: the gear that opened this screen already names it.
appBar: AppBar(),
// Capped at the prose width so fields do not span a ~1366px window.
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Nutrition', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
// A four-digit number: capped so the field does not read as a
// layout error by spanning the whole column.
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: TextField(
child: IconField(
icon: MacroKind.kcal.icon,
iconColor: MacroKind.kcal.color,
semanticLabel: 'Daily kcal goal',
controller: _kcalGoalController,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: const InputDecoration(
labelText: 'Daily kcal goal',
helperText: 'Shown in the history day summary',
suffixText: 'kcal',
),
onChanged: _onKcalGoalChanged,
),
),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
Text(
'Firebase sync',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Text(
_firebaseConfigured
? 'Connected. Syncs go to Firebase first, and still '
'mirror to GitHub until every device has moved.'
: 'Not connected - syncing over GitHub only. Enter the '
'shared sync account to move this device over. The '
'password is kept in the device keystore, never in '
'the app or the repo.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
// Once connected, the account is shown as read-only text rather
// than as prefilled inputs: an editable email box next to an
// empty password box reads as "you still have to enter this",
// which made a connected device look unconfigured.
if (_firebaseConfigured)
Row(
children: [
const Icon(Icons.cloud_done, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
_firebaseEmailController.text,
style: Theme.of(context).textTheme.bodyMedium,
),
),
TextButton(
onPressed: _busy ? null : _disconnectFirebase,
child: const Text('Disconnect'),
),
],
)
else ...[
TextField(
controller: _firebaseEmailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Sync account email',
),
),
const SizedBox(height: 8),
TextField(
controller: _firebasePasswordController,
obscureText: true,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Sync account password',
),
),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: _busy ? null : _saveFirebaseAccount,
icon: const Icon(Icons.cloud_done),
label: const Text('Connect Firebase'),
),
],
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
// GitHub is a mirror during the cutover, not something to pick:
// its whole configuration lives under "Advanced" so the primary
// path stays a single choice. See CLAUDE.md "Cross-device sync".
ExpansionTile(
title: const Text('Advanced (GitHub mirror)'),
tilePadding: EdgeInsets.zero,
childrenPadding: const EdgeInsets.only(bottom: 8),
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
'Syncs still mirror to GitHub until every device has '
'moved to Firebase. Authorize in your browser — no '
'token to paste.',
style: Theme.of(context).textTheme.bodySmall,
),
),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: _connectGitHub,
icon: const Icon(Icons.login),
label: const Text('Connect GitHub'),
),
),
const SizedBox(height: 16),
TextField(
controller: _ownerController,
decoration: const InputDecoration(
labelText: 'GitHub owner',
),
),
const SizedBox(height: 8),
TextField(
controller: _repoController,
decoration: const InputDecoration(labelText: 'Repo'),
),
const SizedBox(height: 8),
TextField(
controller: _clientIdController,
decoration: const InputDecoration(
labelText: 'OAuth App client id',
helperText: 'Needed for the Connect GitHub button',
),
),
const SizedBox(height: 8),
TextField(
controller: _tokenController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Personal access token (fallback)',
// Both wrapper hints are web-only; a VM test always takes
// the null branch.
// coverage:ignore-start
helperText: SyncSettings.exposesTokenValue
? null
: _storedToken.isEmpty
? 'Stored by the desktop wrapper, never by the '
'browser'
: 'A token is stored by the desktop wrapper; '
'type here only to replace it',
// coverage:ignore-end
helperMaxLines: 2,
),
),
],
),
const LogSoundTile(),
const SizedBox(height: 16),
Wrap(
spacing: 8,
children: [
ElevatedButton(
onPressed: _busy ? null : _save,
child: const Text('Save'),
),
OutlinedButton(
onPressed: _busy ? null : _testConnection,
// Named for what it actually does: _testConnection builds a
// GitHub client and calls canAccessRepo(). It says nothing
// about Firebase, and the bare label implied otherwise.
child: const Text('Test GitHub connection'),
),
ElevatedButton(
onPressed: _busy ? null : _syncNow,
child: const Text('Sync now'),
),
],
),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
Text(
'Notifications',
style: Theme.of(context).textTheme.titleMedium,
..._mealScheduleSection(context),
const KuchniaSettingsSection(),
const SizedBox(height: 24),
const Divider(),
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(
Icons.cloud_sync_outlined,
semanticLabel: 'Sync settings',
),
trailing: const Icon(Icons.chevron_right),
onTap: () => unawaited(_openSyncSettings()),
),
const SizedBox(height: 4),
Text(
_isAndroid
? 'A background check nags you every ~15 min if a '
'meal slot is overdue. Aggressive OEM battery '
'optimization (MIUI, some Samsung configs) can '
'delay this well past 15 min -- request an '
'exemption for reliable nagging.'
: 'A check runs every 5 min while this window is open and '
'notifies you about an overdue meal slot. A browser '
'cannot run anything once the window is closed -- on '
'the PC the real backstop is the diet_guard gate, '
'which locks the screen instead.',
style: Theme.of(context).textTheme.bodySmall,
// End-to-end encryption passphrase: closed lock while the last
// sync found no usable key, so nothing syncs until it is set.
ValueListenableBuilder<bool>(
valueListenable: syncLocked,
builder: (_, locked, _) => ListTile(
contentPadding: EdgeInsets.zero,
leading: E2ePassphraseButton(locked: locked),
),
),
// Legacy mirror: muted tint marks it as the secondary path.
ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(
Icons.code,
color: Theme.of(context).colorScheme.onSurfaceVariant,
semanticLabel: 'Advanced sync (GitHub)',
),
trailing: const Icon(Icons.chevron_right),
onTap: () => unawaited(_openGitHubMirror()),
),
DataBackupRow(
onImported: () => _kcalGoalController.text = AppSettingsService
.dailyKcalGoal
.toString(),
),
// Battery-optimization exemption is Android-only, and
// `permission_handler` has no web implementation at all;
// the row would throw rather than degrade in the browser.
if (_isAndroid) ...[
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: _requestBatteryExemption,
icon: const Icon(Icons.battery_alert),
label: const Text('Disable battery optimization'),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: IconButton.outlined(
onPressed: _requestBatteryExemption,
icon: const Icon(
Icons.battery_alert,
semanticLabel: 'Disable battery optimization',
),
),
),
],
if (_status != null) ...[
const SizedBox(height: 16),
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
Align(alignment: Alignment.centerLeft, child: _status),
],
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
const Align(alignment: Alignment.centerLeft, child: KuhyCredit()),
],
),
),
@ -580,168 +248,3 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
}
/// Dialog shown when "Connect GitHub" is tapped with no OAuth App client id
/// configured yet. Explains what it is, how to get one, and lets the user
/// paste it in directly — rather than leaving them to discover a buried
/// "Advanced" field on their own. Pops the trimmed client id, or null if
/// cancelled.
class _ClientIdSetupDialog extends StatefulWidget {
const _ClientIdSetupDialog();
@override
State<_ClientIdSetupDialog> createState() => _ClientIdSetupDialogState();
}
class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('One-time GitHub setup needed'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Diet Guard signs in via a GitHub OAuth App (no password '
'typed into this app). You only have to set this up once:',
),
const SizedBox(height: 12),
const Text(
'1. On any device, open '
'github.com/settings/developers → "New OAuth App".\n'
'2. Name/Homepage/Callback URL can be anything (device flow '
"doesn't use the callback) — e.g. "
'"Diet Guard" and your GitHub profile URL.\n'
'3. Check "Enable Device Flow", then click "Register '
'application".\n'
"4. Copy the Client ID shown on the app's page and paste it "
'below.',
),
const SizedBox(height: 12),
const Text(
'When you connect below, log in with the GitHub account that '
'has write access to kuhyx/syncs.',
),
const SizedBox(height: 16),
TextField(
controller: _controller,
autofocus: true,
decoration: const InputDecoration(labelText: 'Client ID'),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () {
final id = _controller.text.trim();
if (id.isNotEmpty) Navigator.of(context).pop(id);
},
child: const Text('Continue'),
),
],
);
}
}
/// Dialog shown during the device flow: displays the user code, opens the
/// verification page, and polls until authorized — popping the token (or
/// null if cancelled / failed).
class _DeviceCodeDialog extends StatefulWidget {
const _DeviceCodeDialog({required this.device, required this.auth});
final DeviceCodeResponse device;
final GitHubDeviceAuth auth;
@override
State<_DeviceCodeDialog> createState() => _DeviceCodeDialogState();
}
class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
String? _error;
@override
void initState() {
super.initState();
unawaited(_poll());
}
Future<void> _poll() async {
try {
final token = await widget.auth.pollForToken(widget.device);
if (mounted) Navigator.of(context).pop(token);
} on Exception catch (e) {
if (mounted) setState(() => _error = '$e');
}
}
Future<void> _openPage() async {
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
await launchUrl(
Uri.parse(widget.device.verificationUri),
mode: LaunchMode.externalApplication,
);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Authorize on GitHub'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Enter this code on GitHub:'),
const SizedBox(height: 8),
SelectableText(
widget.device.userCode,
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 16),
if (_error == null)
const Row(
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
SizedBox(width: 12),
Expanded(child: Text('Waiting for authorization…')),
],
)
else
Text(
_error!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton.icon(
onPressed: _openPage,
icon: const Icon(Icons.open_in_new),
label: const Text('Open GitHub & copy code'),
),
],
);
}
}

View File

@ -0,0 +1,220 @@
/// Exercise energy per workout, by every formula the workout data supports.
///
/// Port of `diet_guard/_activity_kcal.py`, gated by the shared
/// `tests/fixtures/body_calc.json`. Every formula returns **net** kcal --
/// energy above resting -- because the measured TDEE adds exercise on top of
/// `BMR x 1.2`, which already pays for the resting hour.
///
/// * **MET** (Compendium 2011): `(MET - 1) x kg x hours`, speed-interpolated
/// for runs and walks; lifting is code 02052 (resistance training) = 5.0.
/// * **ACSM** level-ground equations: net VO2 = 0.2 v (run) / 0.1 v (walk),
/// v in m/min; kcal = VO2 x kg x min x 5 / 1000.
/// * **Per-km**: 0.9 (run) / 0.5 (walk) kcal/kg/km net.
///
/// ACSM and per-km need a distance, so every other session falls back to
/// its MET figure (listed in [SessionKcal.fallback]).
library;
import 'package:diet_guard_app/models/workout_session.dart';
export 'package:diet_guard_app/models/workout_session.dart';
/// Formula names, in display order.
const List<String> activityFormulas = ['MET', 'ACSM', 'Per-km'];
/// Measured activity averages at most the last two full weeks.
const int maxWindowDays = 14;
const List<(double, double)> _runMetByKmh = [
(6.4, 6),
(8, 8.3),
(8.4, 9),
(9.7, 9.8),
(10.8, 10.5),
(11.3, 11),
(12.1, 11.5),
(12.9, 11.8),
(13.8, 12.3),
(14.5, 12.8),
(16.1, 14.5),
(17.7, 16),
(19.3, 19),
(20.9, 19.8),
(22.5, 23),
];
const List<(double, double)> _walkMetByKmh = [
(3.2, 2.8),
(4, 3),
(4.8, 3.5),
(5.6, 4.3),
(6.4, 5),
(7.2, 7),
(8, 8.3),
];
const Map<String, double> _fixedMet = {
'strength': 5,
'run': 8,
'walk': 3.5,
'cycle': 7.5,
'other': 4,
};
const Map<String, double> _acsmSlope = {'run': 0.2, 'walk': 0.1};
const Map<String, double> _netKcalPerKgKm = {'run': 0.9, 'walk': 0.5};
const double _kcalPerLitreO2 = 5;
/// Net kcal of one session per formula; [fallback] names MET stand-ins.
class SessionKcal {
/// Creates a result.
const SessionKcal(this.session, this.kcal, this.fallback);
/// The session measured.
final Session session;
/// Formula name -> net kcal.
final Map<String, double> kcal;
/// Formulas that could not apply and reuse the MET figure.
final Set<String> fallback;
}
double _interpolate(List<(double, double)> table, double kmh) {
if (kmh <= table.first.$1) return table.first.$2;
for (var i = 0; i + 1 < table.length; i++) {
final (x0, y0) = table[i];
final (x1, y1) = table[i + 1];
if (kmh <= x1) return y0 + (y1 - y0) * (kmh - x0) / (x1 - x0);
}
return table.last.$2;
}
double? _speedKmh(Session session) {
final km = session.km;
if (km == null || km <= 0 || session.minutes <= 0) return null;
return km / (session.minutes / 60.0);
}
/// The MET value for [session]: speed-based when possible, else fixed.
double metFor(Session session) {
final kmh = _speedKmh(session);
if (kmh != null && session.kind == 'run') {
return _interpolate(_runMetByKmh, kmh);
}
if (kmh != null && session.kind == 'walk') {
return _interpolate(_walkMetByKmh, kmh);
}
return _fixedMet[session.kind] ?? _fixedMet['other']!;
}
/// Net kcal of [session] for a [weightKg] person, by every formula.
SessionKcal sessionKcal(Session session, double weightKg) {
final hours = session.minutes / 60.0;
final met = (metFor(session) - 1.0) * weightKg * hours;
final kcal = {'MET': met, 'ACSM': met, 'Per-km': met};
final fallback = {'ACSM', 'Per-km'};
final kmh = _speedKmh(session);
final km = session.km;
final slope = _acsmSlope[session.kind];
if (kmh != null && km != null && slope != null) {
final metresPerMin = kmh * 1000.0 / 60.0;
final netVo2 = slope * metresPerMin;
kcal['ACSM'] = netVo2 * weightKg * session.minutes * _kcalPerLitreO2 / 1000;
kcal['Per-km'] = _netKcalPerKgKm[session.kind]! * weightKg * km;
fallback.clear();
}
return SessionKcal(session, kcal, fallback);
}
String _dateKey(DateTime day) {
String two(int v) => v.toString().padLeft(2, '0');
return '${day.year.toString().padLeft(4, '0')}-${two(day.month)}'
'-${two(day.day)}';
}
DateTime _utcDay(DateTime day) => DateTime.utc(day.year, day.month, day.day);
/// How many full past days [dailyExercise] averages over.
///
/// [maxWindowDays], or fewer while the earliest past data (a session or an
/// [extraByDay] key before [today]) is younger than that; 0 when there is no
/// past data at all.
int windowDays(
List<Session> sessions,
DateTime today, [
Map<String, double>? extraByDay,
]) {
final last = _dateKey(today);
final days = [
for (final session in sessions)
if (session.day.compareTo(last) < 0) session.day,
for (final day in (extraByDay ?? const <String, double>{}).keys)
if (day.compareTo(last) < 0) day,
];
if (days.isEmpty) return 0;
final earliest = days.reduce((a, b) => a.compareTo(b) <= 0 ? a : b);
// Whole UTC days, so a DST change cannot shave an hour off the count.
final span = _utcDay(
today,
).difference(DateTime.parse('${earliest}T00:00:00Z')).inDays;
return span < maxWindowDays ? span : maxWindowDays;
}
/// Mean net exercise kcal per day over the full past days before [today].
///
/// The window ends yesterday (today is still in progress) and starts
/// [maxWindowDays] back -- or, while the data is younger than that, on the
/// first day that has any, so a week of history is averaged over that week
/// rather than diluted over 14 days ([windowDays]). The denominator is
/// calendar days within that span: a rest day burns no exercise kcal. With
/// no past data at all, every formula reads 0.
///
/// [extraByDay] (day -> net kcal, e.g. steps outside workouts) is added to
/// every formula alike: it is not a workout any formula could measure.
Map<String, double> dailyExercise(
List<Session> sessions,
double weightKg,
DateTime today, [
Map<String, double>? extraByDay,
]) {
final totals = {for (final name in activityFormulas) name: 0.0};
final span = windowDays(sessions, today, extraByDay);
if (span == 0) return totals;
// Calendar arithmetic via the constructor, not Duration: subtracting N x
// 24 h across a DST change lands on 23:00 of the wrong day.
final first = _dateKey(DateTime(today.year, today.month, today.day - span));
final last = _dateKey(today);
bool inWindow(String day) =>
day.compareTo(first) >= 0 && day.compareTo(last) < 0;
for (final session in sessions) {
if (!inWindow(session.day)) continue;
sessionKcal(session, weightKg).kcal.forEach((name, value) {
totals[name] = totals[name]! + value;
});
}
extraByDay?.forEach((day, kcal) {
if (!inWindow(day)) return;
for (final name in activityFormulas) {
totals[name] = totals[name]! + kcal;
}
});
return totals.map((name, total) => MapEntry(name, total / span));
}
/// The part of every [dailyExercise] mean that [extraByDay] contributes,
/// over the very same window -- so a "steps add N kcal/day (included above)"
/// line always adds up to the total it claims to be part of. Mirrors the
/// steps share computed in `diet_guard/_body_view.py`.
double extraShare(
List<Session> sessions,
DateTime today,
Map<String, double> extraByDay,
) {
final span = windowDays(sessions, today, extraByDay);
if (span == 0) return 0;
final first = _dateKey(DateTime(today.year, today.month, today.day - span));
final last = _dateKey(today);
var sum = 0.0;
extraByDay.forEach((day, kcal) {
if (day.compareTo(first) >= 0 && day.compareTo(last) < 0) sum += kcal;
});
return sum / span;
}

View File

@ -33,6 +33,7 @@ class AppSettingsService {
final DocumentStore _store;
int _dailyKcalGoal = kDefaultDailyKcalGoal;
DateTime? _dailyKcalGoalUpdatedAt;
bool _soundOnLog = true;
/// Returns the configured daily kcal goal, or the default when
/// uninitialised. This is the budget in force *today*; asking what applied
@ -44,6 +45,19 @@ class AppSettingsService {
static DateTime? get dailyKcalGoalUpdatedAt =>
_instance?._dailyKcalGoalUpdatedAt;
/// Whether a logged meal plays the confirm cue; on unless turned off.
///
/// Device-local, deliberately not synced: a phone in a meeting and a PC
/// with speakers want different answers.
static bool get soundOnLog => _instance?._soundOnLog ?? true;
/// Persists [on] without touching the budget's edit stamp, which would
/// otherwise make this device win the next budget merge.
Future<void> setSoundOnLog({required bool on}) async {
_soundOnLog = on;
await _writeToDisk();
}
/// Initialises the singleton against the platform document store (files on
/// Android, IndexedDB in the browser-hosted desktop app).
static Future<AppSettingsService> init() async {
@ -105,6 +119,9 @@ class AppSettingsService {
data['daily_kcal_goal_updated_at'] as String,
);
}
if (data is Map && data['sound_on_log'] is bool) {
_soundOnLog = data['sound_on_log'] as bool;
}
} on Exception {
// Ignore parse errors and keep defaults.
}
@ -160,6 +177,7 @@ class AppSettingsService {
'daily_kcal_goal': _dailyKcalGoal,
'daily_kcal_goal_updated_at': _dailyKcalGoalUpdatedAt
?.toIso8601String(),
'sound_on_log': _soundOnLog,
}),
);
}

View File

@ -30,7 +30,7 @@ void backgroundCheckCallbackDispatcher() {
if (taskName == syncPushTaskName) {
// Return the push's own success flag so a still-offline / failed push
// is retried with backoff rather than silently dropped.
return backgroundSyncPush();
return await backgroundSyncPush();
}
if (taskName == backgroundCheckTaskName) {
await checkAndNotify();

View File

@ -7,11 +7,17 @@ library;
import 'dart:developer';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_attempt.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:http/http.dart' as http;
@ -34,11 +40,33 @@ const String syncPushTaskName = 'diet_guard.sync_push';
/// budget, and applies a merge winner via `AppSettingsService.instance`,
/// which throws if the singleton was never initialised in this isolate.
Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
// Must run here too, and before anything stamps an HLC: a fresh isolate has
// its own static state, so without this `currentSyncDeviceId` falls back to
// the compile-time role constant ('phone') and this tick publishes to
// `devices/phone/` instead of the persisted uuid. That splits the device
// across two directories, and because `sync_state` holds a single
// `pushedRev` with no notion of which identity wrote it, the next
// *foreground* push then sees `unchanged` and skips writing the uuid
// directory entirely.
await initSyncDeviceId();
await LogStorageService.init();
await FoodBankService.init();
await AppSettingsService.init();
// runSync also merges the budget history through this singleton.
await BudgetHistoryService.init();
// A fresh isolate has its own static state, so the schedule must be loaded
// here too -- otherwise the due-slot check in this isolate would fall back
// to the default four meals and nag for checkpoints the user's actual
// schedule does not have.
await MealScheduleService.init();
// Same fresh-isolate reasoning: `_syncKuchniaCredential` no-ops when this
// singleton is uninitialised, so without this a background tick would
// neither publish this device's catering credential nor receive a peer's --
// and on the phone the background tick is most of the syncing there is.
await KuchniaCredentialService.init();
// `syncBody` no-ops without it, and the background tick is when the
// phone ingests the morning weigh-in.
await BodyService.init();
final SyncSettings settings;
try {
settings = await SyncSettings.load();
@ -59,22 +87,18 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
'diet_guard background sync: no backend configured; nothing to push',
level: 900,
);
await SyncHealth.recordUnconfigured();
return true; // nothing to push; don't retry
}
final client = createGitHubClient(settings, httpClient: httpClient);
try {
await runSync(await syncBackend(client));
return true;
} on Exception catch (error, stackTrace) {
// Never silent: this is the only signal that a background push failed.
log(
'diet_guard background sync failed',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return false; // offline / transient error -> retry with backoff
} finally {
client.close();
}
// Never silent: attemptSync records the outcome, the only signal that a
// background push failed. False -> WorkManager retries with backoff.
final landed = await attemptSync(() async {
try {
await runSync(await syncBackend(client));
} finally {
client.close();
}
});
return landed;
}

View File

@ -0,0 +1,216 @@
/// BMI, ideal-weight and resting-metabolism formulas -- pure arithmetic.
///
/// Byte-for-byte port of `diet_guard/_body_calc.py`, gated by the shared
/// `tests/fixtures/body_calc.json` (`test/services/body_parity_test.dart`).
/// Rounding goes through [halfUp], never `.round()`: Dart rounds half away
/// from zero and Python's `round` is banker's, so the bare builtins would
/// print different numbers on the two devices for the same person.
library;
import 'dart:math' as math;
const double _cmPerInch = 2.54;
const double _fiveFeetIn = 60;
/// Adult BMI categories are WHO's and do not apply to anyone still growing.
const int adultAge = 20;
const double _bmiPrimeDivisor = 25;
const double _healthyBmiLow = 18.5;
const double _healthyBmiHigh = 24.9;
const double _targetBmi = 22;
// (upper bound exclusive, label), WHO adult classification.
const List<(double, String)> _bmiBands = [
(16, 'severe thinness'),
(17, 'moderate thinness'),
(18.5, 'mild thinness'),
(25, 'normal'),
(30, 'overweight'),
(35, 'obese class I'),
(40, 'obese class II'),
];
const String _topBand = 'obese class III';
/// The lean-mass formula the calorie table switches to with a body fat %.
const String katchMcArdle = 'Katch-McArdle';
/// Rounds [value] half-up at [digits] decimals, identically to Python.
double halfUp(double value, [int digits = 0]) {
final scale = math.pow(10, digits).toDouble();
return (value * scale + 0.5).floorToDouble() / scale;
}
/// Body metrics that feed every formula.
///
/// Mirrors Python's `_budget_biometrics.Biometrics`.
class Biometrics {
/// Creates a set of body metrics.
const Biometrics({
required this.weightKg,
required this.heightCm,
required this.ageYears,
required this.isMale,
});
/// Body mass in kilograms.
final double weightKg;
/// Height in centimetres.
final double heightCm;
/// Age in completed years.
final double ageYears;
/// True for the male constants.
final bool isMale;
}
/// One named formula's result; [value] is null when it does not apply.
class Formula {
/// Creates a formula result.
const Formula(this.name, this.value);
/// Display name.
final String name;
/// The result, or null when undefined for this person.
final double? value;
}
/// Body-mass index and its readings.
class BmiReport {
/// Creates a report.
const BmiReport({
required this.bmi,
required this.prime,
required this.trefethen,
required this.category,
});
/// Classic BMI, kg / m^2.
final double bmi;
/// BMI divided by 25.
final double prime;
/// Trefethen's "new BMI", 1.3 * kg / m^2.5.
final double trefethen;
/// WHO adult band, or a note that it does not apply (< 20 y).
final String category;
}
/// Mifflin-St Jeor resting metabolic rate, kcal/day.
double mifflinStJeorBmr(Biometrics bio) {
final base = 10.0 * bio.weightKg + 6.25 * bio.heightCm - 5.0 * bio.ageYears;
return bio.isMale ? base + 5.0 : base - 161.0;
}
String _category(double bmi, double ageYears) {
if (ageYears < adultAge) return 'adult categories do not apply under 20';
for (final (upper, label) in _bmiBands) {
if (bmi < upper) return label;
}
return _topBand;
}
/// Returns BMI, BMI Prime, Trefethen's BMI and the WHO category.
BmiReport bmiReport(Biometrics bio) {
final metres = bio.heightCm / 100.0;
final bmi = bio.weightKg / (metres * metres);
return BmiReport(
bmi: bmi,
prime: bmi / _bmiPrimeDivisor,
trefethen: 1.3 * bio.weightKg / math.pow(metres, 2.5),
category: _category(bmi, bio.ageYears),
);
}
double? _perInch(
double inches,
double base,
double perInch, {
required bool defined,
}) => defined ? base + perInch * inches : null;
/// Every ideal-body-weight formula we can evaluate, in kg.
///
/// Only data-backed ones (Devine, its MetLife refits, Peterson); Broca, its
/// derivatives and Hamwi were dropped. The BMI healthy range is
/// [healthyRange], shown with BMI; [idealSummary] averages these.
List<Formula> idealWeights(Biometrics bio) {
final h = bio.heightCm;
final inches = h / _cmPerInch - _fiveFeetIn;
final ok = inches >= 0;
final male = bio.isMale;
final metres = h / 100.0;
return [
Formula('Devine', _perInch(inches, male ? 50 : 45.5, 2.3, defined: ok)),
Formula(
'Robinson',
_perInch(inches, male ? 52 : 49, male ? 1.9 : 1.7, defined: ok),
),
Formula(
'Miller',
_perInch(inches, male ? 56.2 : 53.1, male ? 1.41 : 1.36, defined: ok),
),
Formula(
'Peterson (BMI 22)',
2.2 * _targetBmi + 3.5 * _targetBmi * (metres - 1.5),
),
];
}
/// The weights (kg) at BMI 18.5 and 24.9 for this height.
(double, double) healthyRange(Biometrics bio) {
final metres = bio.heightCm / 100.0;
return (_healthyBmiLow * metres * metres, _healthyBmiHigh * metres * metres);
}
/// `(average, lowest, highest)` of the formulas that apply, or null.
(double, double, double)? idealSummary(List<Formula> formulas) {
final values = [for (final f in formulas) ?f.value];
if (values.isEmpty) return null;
final sum = values.fold<double>(0, (a, b) => a + b);
return (
sum / values.length,
values.reduce(math.min),
values.reduce(math.max),
);
}
/// Resting metabolic rate by every formula, kcal/day.
///
/// Katch-McArdle and Cunningham work from lean mass, so they are null until
/// a body-fat % is logged.
List<Formula> bmrFormulas(Biometrics bio, [double? bodyFatPct]) {
final w = bio.weightKg;
final h = bio.heightCm;
final a = bio.ageYears;
final revised = bio.isMale
? 88.362 + 13.397 * w + 4.799 * h - 5.677 * a
: 447.593 + 9.247 * w + 3.098 * h - 4.330 * a;
final lean = bodyFatPct == null ? null : w * (1.0 - bodyFatPct / 100.0);
return [
Formula('Mifflin-St Jeor', mifflinStJeorBmr(bio)),
Formula('Harris-Benedict (revised 1984)', revised),
Formula(katchMcArdle, lean == null ? null : 370.0 + 21.6 * lean),
Formula('Cunningham', lean == null ? null : 500.0 + 22.0 * lean),
];
}
/// The BMR the calorie table uses: Katch-McArdle with body fat, else Mifflin.
Formula tableBmr(Biometrics bio, double? bodyFatPct) {
final formulas = bmrFormulas(bio, bodyFatPct);
return bodyFatPct != null ? formulas[2] : formulas[0];
}
/// Completed years between [birth] and [today].
int ageOn(DateTime birth, DateTime today) {
var years = today.year - birth.year;
if (today.month < birth.month ||
(today.month == birth.month && today.day < birth.day)) {
years -= 1;
}
return years;
}

View File

@ -0,0 +1,206 @@
/// The daily calorie target for one chosen goal -- the Body screen's top
/// line: "To **lose** **0.5** **kg** / **week** on **Moderate** eat
/// **2019** kcal". Every bold word is a [Goal] choice, remembered and synced
/// (`body_prefs.dart`). **Informational only**: nothing here writes the
/// budget.
///
/// Port of `diet_guard/_body_energy.py`, gated by the shared
/// `tests/fixtures/body_calc.json`. TDEE is the table BMR x an activity
/// factor, or for a "Measured" choice `BMR x 1.2` plus the real mean daily
/// exercise by that formula. Target = `TDEE -/+ kg per day x 7700`; below
/// the 1200 kcal floor it is flagged, never clamped.
library;
import 'package:diet_guard_app/services/activity_kcal.dart';
import 'package:diet_guard_app/services/body_calc.dart';
/// kcal per kg of body fat.
const double kcalPerKg = 7700;
/// The floor below which a target is flagged.
const int minTargetKcal = 1200;
const double _sedentary = 1.2;
/// A "Measured" choice is `measured:<formula>` (MET, ACSM, Per-km).
const String measuredPrefix = 'measured:';
/// Goal directions, in menu order.
const List<String> directions = ['lose', 'maintain', 'gain'];
/// Offered in the amount picker; any other typed number is accepted too.
const List<double> presetAmounts = [0.25, 0.5, 0.75, 1];
/// Kilograms per weight unit.
const Map<String, double> weightUnits = {
'kg': 1,
'lb': 0.45359237,
'g': 0.001,
'st': 6.35029318,
};
/// Days per time unit; a month is the mean Gregorian month.
const Map<String, double> timeUnits = {
'day': 1,
'week': 7,
'month': 30.436875,
'year': 365.2425,
};
/// One selectable activity level and its TDEE multiplier.
class ActivityLevel {
/// Creates a level.
const ActivityLevel(this.key, this.label, this.factor, this.meaning);
/// Stable key.
final String key;
/// Display label.
final String label;
/// BMR multiplier.
final double factor;
/// What the level means, shown in the picker.
final String meaning;
}
/// Every activity level, in display order.
const List<ActivityLevel> activityLevels = [
ActivityLevel('sedentary', 'Sedentary', 1.2, 'little or no exercise'),
ActivityLevel('light', 'Light', 1.375, 'exercise 1-3x a week'),
ActivityLevel('moderate', 'Moderate', 1.55, 'exercise 3-5x a week'),
ActivityLevel('very', 'Very active', 1.725, 'exercise 6-7x a week'),
ActivityLevel('extra', 'Extra active', 1.9, 'training twice a day'),
];
/// Every activity choice, in menu order: the five levels, then measured.
final List<String> activityChoices = [
for (final level in activityLevels) level.key,
for (final name in activityFormulas) '$measuredPrefix$name',
];
/// What the user wants: direction, amount per time, at an activity.
class Goal {
/// Creates a goal.
const Goal(
this.direction,
this.amount,
this.weightUnit,
this.timeUnit,
this.activity,
);
/// `lose`, `maintain` or `gain`.
final String direction;
/// How much, in [weightUnit] per [timeUnit].
final double amount;
/// A [weightUnits] key.
final String weightUnit;
/// A [timeUnits] key.
final String timeUnit;
/// An [activityChoices] entry.
final String activity;
/// Returns a copy with the given parts replaced.
Goal copyWith({
String? direction,
double? amount,
String? weightUnit,
String? timeUnit,
String? activity,
}) => Goal(
direction ?? this.direction,
amount ?? this.amount,
weightUnit ?? this.weightUnit,
timeUnit ?? this.timeUnit,
activity ?? this.activity,
);
/// Signed change in kg/day: positive loses, negative gains.
double kgPerDay() {
if (direction == 'maintain') return 0;
final rate = amount * weightUnits[weightUnit]! / timeUnits[timeUnit]!;
return direction == 'lose' ? rate : -rate;
}
}
/// The goal until the user picks one.
const Goal defaultGoal = Goal('lose', 0.5, 'kg', 'week', 'moderate');
/// The answer to a [Goal], or why there is none.
class Target {
/// Creates a target.
const Target({required this.kcal, required this.tdee, required this.bmrName});
/// Daily target, or null when the goal needs unpublished measured data.
final int? kcal;
/// The maintenance figure it was derived from, when known.
final double? tdee;
/// The resting-burn formula the TDEE scales.
final String bmrName;
/// Whether the target is under the 1200 kcal floor.
bool get belowFloor {
final value = kcal;
return value != null && value < minTargetKcal;
}
}
/// Python's `f"{x:g}"`: six significant digits, trailing zeros dropped.
String formatG(double value) {
if (value == value.truncateToDouble() && value.abs() < 1e15) {
return value.toInt().toString();
}
var text = value.toStringAsPrecision(6);
if (text.contains('.') && !text.contains('e')) {
text = text
.replaceFirst(RegExp(r'0+$'), '')
.replaceFirst(RegExp(r'\.$'), '');
}
return text;
}
/// Menu text for an activity choice, e.g. `Measured (ACSM)`.
String activityLabel(String key) {
if (key.startsWith(measuredPrefix)) {
return 'Measured (${key.substring(measuredPrefix.length)})';
}
for (final level in activityLevels) {
if (level.key == key) return level.label;
}
return key;
}
double? _tdee(double bmr, String activity, Map<String, double>? exercise) {
if (activity.startsWith(measuredPrefix)) {
final kcal = exercise?[activity.substring(measuredPrefix.length)];
return kcal == null ? null : bmr * _sedentary + kcal;
}
for (final level in activityLevels) {
if (level.key == activity) return bmr * level.factor;
}
return null;
}
/// The daily kcal that meets [goal] from a [bmr] (kcal/day).
Target goalTarget(
Goal goal,
double bmr,
String bmrName,
Map<String, double>? exercise,
) {
final tdee = _tdee(bmr, goal.activity, exercise);
if (tdee == null) return Target(kcal: null, tdee: null, bmrName: bmrName);
return Target(
kcal: halfUp(tdee - goal.kgPerDay() * kcalPerKg).toInt(),
tdee: tdee,
bmrName: bmrName,
);
}

View File

@ -0,0 +1,49 @@
/// The calorie goal the user last picked -- remembered and synced.
///
/// Stored as one extra field, `goal`, on the synced `profile` record (its
/// own stamp: saving it never counts as editing birth, height or sex), so the
/// sentence "To lose 0.5 kg / week on Moderate eat ..." reads the same on
/// the PC gate and the phone. Each part is validated on read: an unknown
/// direction, unit or activity falls back to that part of [defaultGoal].
///
/// Port of `diet_guard/_body_prefs.py`.
library;
import 'package:diet_guard_app/services/body_energy.dart';
import 'package:diet_guard_app/services/body_service.dart';
/// The profile field the goal is stored under.
const String goalField = 'goal';
/// The wire/disk form (short keys).
Map<String, Object> goalToJson(Goal goal) => {
'dir': goal.direction,
'amt': goal.amount,
'wu': goal.weightUnit,
'tu': goal.timeUnit,
'act': goal.activity,
};
/// Parses a stored goal part by part, defaulting whatever is unusable.
Goal goalFromJson(Object? raw) {
if (raw is! Map) return defaultGoal;
final dir = raw['dir'];
final amt = raw['amt'];
final wu = raw['wu'];
final tu = raw['tu'];
final act = raw['act'];
return defaultGoal.copyWith(
direction: dir is String && directions.contains(dir) ? dir : null,
amount: amt is num && amt >= 0 ? amt.toDouble() : null,
weightUnit: wu is String && weightUnits.containsKey(wu) ? wu : null,
timeUnit: tu is String && timeUnits.containsKey(tu) ? tu : null,
activity: act is String && activityChoices.contains(act) ? act : null,
);
}
/// The remembered goal (the default until one is saved).
Goal savedGoal(BodyService body) => goalFromJson(body.profileValue(goalField));
/// Remembers (and syncs) [goal].
Future<void> setGoal(BodyService body, Goal goal) =>
body.setProfileFields({goalField: goalToJson(goal)});

View File

@ -0,0 +1,225 @@
/// Persistence for the Body document: profile, weight log, PC workouts.
///
/// A singleton over the platform [DocumentStore], shaped like
/// `MealScheduleService`. Every setter stamps the edited part with "now", so
/// a manual edit outranks an ingested phone weigh-in of the same day in the
/// last-writer-wins merge (`sync_merge_body.dart`). Nothing here touches the
/// budget -- the Body screen is informational only.
///
/// Mirrors the storage half of `diet_guard/_body_store.py`.
library;
import 'dart:convert';
import 'package:diet_guard_app/models/body_document.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/services/activity_kcal.dart';
import 'package:diet_guard_app/services/body_calc.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:flutter/foundation.dart';
/// Singleton owning the `body.json` document.
class BodyService {
BodyService._(this._store);
/// Document name this service owns.
static const documentName = 'body.json';
static BodyService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static BodyService get instance => _instance!;
/// True once [init] (or a test initialiser) has run.
static bool get isInitialized => _instance != null;
final DocumentStore _store;
BodyDocument _doc = const BodyDocument();
/// The whole document, for the sync layer.
BodyDocument get document => _doc;
/// Initialises the singleton against the platform document store.
static Future<BodyService> init() async {
if (_instance != null) return _instance!;
// coverage:ignore-start
final svc = BodyService._(await openDocumentStore());
// coverage:ignore-end
await svc._load();
_instance = svc;
return svc;
}
/// Initialises from [store], for tests.
@visibleForTesting
static Future<BodyService> initForTesting(DocumentStore store) async {
final svc = BodyService._(store);
await svc._load();
_instance = svc;
return svc;
}
/// Drops the singleton, or -- given a [store] -- seeds an empty one over
/// it so a later [init] reuses it instead of reaching the platform store.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : BodyService._(store);
}
Future<void> _load() async {
final raw = await _store.read(documentName);
if (raw == null) return;
try {
_doc = BodyDocument.fromJson(jsonDecode(raw));
} on FormatException {
// A corrupt document reads as empty, like the other services.
}
}
Future<void> _write(BodyDocument doc) async {
_doc = doc;
await _store.write(documentName, jsonEncode(doc.toJson()));
}
/// Birth date as `YYYY-MM-DD`, or null.
String? get birth => _string(profileBirth);
/// Height in cm, or null.
double? get heightCm {
final value = _doc.profile[profileHeight]?.value;
return value is num ? value.toDouble() : null;
}
/// `m` / `f`, or null.
String? get sex {
final value = _string(profileSex);
return value == 'm' || value == 'f' ? value : null;
}
/// Whether birth date, height and sex are all set -- the Body screen then
/// moves the profile card to the bottom.
bool get profileComplete =>
DateTime.tryParse(birth ?? '') != null && heightCm != null && sex != null;
String? _string(String name) {
final value = _doc.profile[name]?.value;
return value is String && value.isNotEmpty ? value : null;
}
/// Sets the given profile fields, each stamped now; others are untouched.
Future<void> setProfile({
String? birth,
double? heightCm,
String? sex,
DateTime? now,
}) => setProfileFields({
profileBirth: ?birth,
profileHeight: ?heightCm,
profileSex: ?sex,
}, now: now);
/// Sets raw profile [fields], each stamped now; others keep their stamps.
Future<void> setProfileFields(
Map<String, Object?> fields, {
DateTime? now,
}) async {
if (fields.isEmpty) return;
final t = isoLocalSeconds(now ?? DateTime.now());
final profile = Map<String, Stamped>.from(_doc.profile);
fields.forEach((name, value) => profile[name] = Stamped(value, t));
await _write(_doc.copyWith(profile: profile));
}
/// A raw profile value, or null.
Object? profileValue(String name) => _doc.profile[name]?.value;
/// Records [kg] for [day] (`YYYY-MM-DD`), stamped now.
Future<void> setWeight(String day, double kg, {DateTime? now}) =>
_putWeight(day, kg, now);
/// Deletes [day]'s weight (a tombstone, so the delete syncs).
Future<void> deleteWeight(String day, {DateTime? now}) =>
_putWeight(day, null, now);
Future<void> _putWeight(String day, double? kg, DateTime? now) async {
final weights = Map<String, WeightEntry>.from(_doc.weights);
weights[day] = WeightEntry(
kg: kg,
src: 'manual',
t: isoLocalSeconds(now ?? DateTime.now()),
);
await _write(_doc.copyWith(weights: weights));
}
/// Records [pct] body fat for [day], stamped now (one decimal, half-up).
Future<void> setBodyFat(String day, double pct, {DateTime? now}) =>
_putBodyFat(day, halfUp(pct, 1), now);
/// Deletes [day]'s body fat (a tombstone, so the delete syncs).
Future<void> deleteBodyFat(String day, {DateTime? now}) =>
_putBodyFat(day, null, now);
Future<void> _putBodyFat(String day, double? pct, DateTime? now) async {
final bodyFat = Map<String, BodyFatEntry>.from(_doc.bodyFat);
bodyFat[day] = BodyFatEntry(
pct: pct,
t: isoLocalSeconds(now ?? DateTime.now()),
);
await _write(_doc.copyWith(bodyFat: bodyFat));
}
/// Non-deleted body fat readings, oldest first, as `(YYYY-MM-DD, %)`.
List<(String, double)> get bodyFatSeries =>
_series(_doc.bodyFat.map((day, entry) => MapEntry(day, entry.pct)));
/// The newest non-deleted body fat %, or null.
(String, double)? get latestBodyFat {
final series = bodyFatSeries;
return series.isEmpty ? null : series.last;
}
/// Applies ingested weigh-ins: each replaces its day only when the local
/// entry is missing or stamped **older**. Returns whether anything changed.
Future<bool> applyCandidates(Map<String, WeightEntry> candidates) async {
final weights = Map<String, WeightEntry>.from(_doc.weights);
var changed = false;
candidates.forEach((day, candidate) {
final local = weights[day];
if (local == null || stampMillis(local.t) < stampMillis(candidate.t)) {
weights[day] = candidate;
changed = true;
}
});
if (changed) await _write(_doc.copyWith(weights: weights));
return changed;
}
/// Replaces the document with a sync merge result.
Future<void> applyMerged(BodyDocument merged) => _write(merged);
/// Non-deleted weights, oldest first, as `(YYYY-MM-DD, kg)`.
List<(String, double)> get weightSeries =>
_series(_doc.weights.map((day, entry) => MapEntry(day, entry.kg)));
static List<(String, double)> _series(Map<String, double?> byDay) {
final days = byDay.keys.toList()..sort();
return [
for (final day in days)
if (byDay[day] case final value?) (day, value),
];
}
/// The newest non-deleted weight, or null.
(String, double)? get latestWeight {
final series = weightSeries;
return series.isEmpty ? null : series.last;
}
/// Workouts the PC published, parsed; null when it never published any.
List<Session>? get sessions {
final activity = _doc.activity;
if (activity == null) return null;
return [for (final raw in activity.sessions) ?Session.fromWire(raw)];
}
}

View File

@ -0,0 +1,30 @@
/// Daily steps (from Health Connect, phone-written) as exercise kcal.
///
/// Only steps above [stepBaseline] count: the `BMR x 1.2` sedentary
/// baseline the measured TDEE starts from already assumes a few thousand
/// steps of ordinary movement. The rest are walking at the per-km rate
/// (0.5 kcal per kg per km, net of resting) over a stride estimated from
/// height. Port of `diet_guard/_body_steps.py`.
library;
import 'package:diet_guard_app/services/body_calc.dart';
/// Steps a day the sedentary baseline already covers.
const int stepBaseline = 4000;
// Stride as a fraction of height (the common pedometer estimate).
const double _strideMale = 0.415;
const double _strideFemale = 0.413;
const double _walkKcalPerKgKm = 0.5;
const double _mPerKm = 1000;
/// Estimated walking stride in metres.
double strideM(Biometrics bio) =>
bio.heightCm / 100.0 * (bio.isMale ? _strideMale : _strideFemale);
/// Net kcal of the steps above the baseline, as walking.
double stepKcal(int steps, Biometrics bio) {
final extra = steps > stepBaseline ? steps - stepBaseline : 0;
final km = extra * strideM(bio) / _mPerKm;
return km * _walkKcalPerKgKm * bio.weightKg;
}

View File

@ -0,0 +1,156 @@
/// The phone's side of the Claude relay: what the sparkle button sends and
/// what comes back.
///
/// The screen only talks to this interface; `claude_relay_firebase.dart` is the
/// real transport (Firebase RTDB, end-to-end encrypted) and
/// `claude_relay_fake.dart` the test double. The wire is
/// `docs/DOCS-claude-relay.md` plus `tests/fixtures/claude_relay_contract.json`.
///
/// A `Stream`, not a `Future`: the PC may be off, so a request can sit
/// [ClaudeRelayQueued] for hours before the same stream delivers
/// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued]
/// does not.
///
/// **The request id is a ULID** (`rtdb_relay` never serves another key shape)
/// and **the entry id is derived from it**: `uuid5(namespace, rid)`, computed
/// here by [claudeEntryId] exactly as the PC does. So the phone knows the id
/// of the entry before Claude has answered, a logged result is checked against
/// it, and undo is a tombstone on that id.
///
/// **Photos are transient input.** `photoJpeg` lives in memory for one send:
/// it is never stored on the phone, never put on a `FoodEntry`, and never part
/// of a synced meal record (`repo_invariants_photo_test.dart` enforces it).
library;
import 'dart:math';
import 'dart:typed_data';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:uuid/uuid.dart';
/// The UUID namespace the PC derives entry ids in (`entry_id_namespace` in the
/// contract fixture).
const claudeEntryNamespace = '5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4';
/// The id of the entry the PC logs for request [requestId].
String claudeEntryId(String requestId) =>
const Uuid().v5(claudeEntryNamespace, requestId);
const _crockford = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
/// A fresh ULID: 48 bits of [now] in ms, then 80 random bits, 26 characters of
/// Crockford base32. [random] is injectable for tests.
String newRequestId({DateTime? now, Random? random}) {
final rng = random ?? Random.secure();
var ms = (now ?? DateTime.now()).millisecondsSinceEpoch;
final out = List<String>.filled(26, '0');
for (var i = 9; i >= 0; i--) {
out[i] = _crockford[ms % 32];
ms ~/= 32;
}
for (var i = 10; i < 26; i++) {
out[i] = _crockford[rng.nextInt(32)];
}
return out.join();
}
/// How the PC picks the slot: the oldest due slot, or the nearest to
/// [ClaudeRelayRequest.slotMinute].
enum ClaudeRelayMode {
/// The phone is in due mode.
due,
/// Nothing is due.
normal,
}
/// One send: the text and/or photo, and the slot the meal belongs to.
class ClaudeRelayRequest {
/// Creates a request; at least one of [text] and [photoJpeg] is non-empty.
const ClaudeRelayRequest({
required this.requestId,
required this.slotMinute,
this.mode = ClaudeRelayMode.normal,
this.text = '',
this.photoJpeg,
});
/// A ULID (see [newRequestId]); the entry id is [claudeEntryId] of it.
final String requestId;
/// The slot minute the phone would log against now (`client_slot_min`).
final int slotMinute;
/// Whether the phone is in due mode.
final ClaudeRelayMode mode;
/// What the user typed, trimmed; may be empty when a photo is attached.
final String text;
/// The photo as a JPEG of at most 1024 px, or null.
final Uint8List? photoJpeg;
}
/// What the relay reports about one [ClaudeRelayRequest].
sealed class ClaudeRelayEvent {
const ClaudeRelayEvent();
}
/// The PC is offline; the request is stored and will run later (not terminal).
final class ClaudeRelayQueued extends ClaudeRelayEvent {
/// Creates the event.
const ClaudeRelayQueued();
}
/// Claude logged the meal (terminal). `entry.id == claudeEntryId(rid)`.
final class ClaudeRelayLogged extends ClaudeRelayEvent {
/// Creates the event for [entry].
const ClaudeRelayLogged(this.entry);
/// The entry the worker wrote.
final FoodEntry entry;
}
/// Sync is locked (no passphrase), so nothing can be sent (terminal).
final class ClaudeRelayLocked extends ClaudeRelayEvent {
/// Creates the event.
const ClaudeRelayLocked();
}
/// The send failed (terminal); [reason] is for logs, never painted.
final class ClaudeRelayFailed extends ClaudeRelayEvent {
/// Creates the event.
const ClaudeRelayFailed(this.reason);
/// Why it failed.
final String reason;
}
/// Sends a meal to Claude through the relay.
abstract interface class ClaudeRelayClient {
/// Sends [request]; the stream carries zero or more [ClaudeRelayQueued]
/// then one terminal event, and never throws (failures are events).
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request);
/// Withdraws [requestId] if no worker has claimed it yet; true when it is
/// gone. False means it was already claimed (or the call failed), and the
/// meal will be logged: the stream keeps listening so the row still shows.
Future<bool> cancel(String requestId);
}
/// The stand-in until a transport is wired: every send fails closed.
class UnconfiguredClaudeRelayClient implements ClaudeRelayClient {
/// Creates the stand-in.
const UnconfiguredClaudeRelayClient();
@override
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) =>
Stream.value(const ClaudeRelayFailed('relay not configured'));
@override
Future<bool> cancel(String requestId) async => true;
}
/// The client the screen uses unless it is handed one; `main.dart` assigns the
/// real transport.
ClaudeRelayClient claudeRelay = const UnconfiguredClaudeRelayClient();

Some files were not shown because too many files have changed in this diff Show More