Compare commits

..

30 Commits

Author SHA1 Message Date
a523b67c4f Bump deps; drop pytest coverage opts
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , 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
Bug-class-check: none — gate policy change (kuhy 2026-11-27)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZDq7ef5JyQd7Rx3Ju
2026-11-28 08:26:18 +01:00
be478a8c81 Drop lint, coverage and line-cap gates
Bug-class-check: none — gate policy change (kuhy 2026-11-27)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZDq7ef5JyQd7Rx3Ju
2026-11-28 08:18:35 +01:00
fab0c937cf overlaying rule to ALL apps that sync and share c…
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: c5ee9e59
2026-11-27 12:38:31 +01:00
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
78 changed files with 2151 additions and 531 deletions

2
.fvmrc
View File

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

View File

@ -1,62 +0,0 @@
name: dependency freshness
# Every dependency on its ecosystem's newest STABLE release, enforced on push
# as well as at commit time. The local pre-commit hook only sees the manifests
# in a commit and can be skipped entirely by a fresh clone that never ran
# `pre-commit install`; this runs `--all` over the whole repo.
#
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
# passes, because `--no-verify` is banned locally and a hook that hard-failed
# on a flaky connection would leave no way to commit. A runner is always
# online, so here an undeterminable answer is a real failure.
#
# Expect this to go red for reasons this repo's commit did not cause: an
# upstream release overnight is enough. That is the chosen behaviour -- the
# alternative is a gate that only notices staleness when someone remembers to
# look.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
dependency-freshness:
name: dependencies on newest stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate lives in the shared utils repo so every repo resolves the
# same "latest stable" the same way. Checking it out beats vendoring a
# copy, which is exactly how a gate and its survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
# "3.x", never a pinned minor: the Python target IS the interpreter the
# gate runs under (registries/toolchain.python_installed), so a runner
# held a release behind this machine reports a repo's `requires-python`
# as excluding "latest" while the same check passes locally. flax-docs-mcp
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Install the gate's two runtime dependencies
run: python -m pip install --upgrade pyyaml packaging
- name: Cache registry lookups
uses: actions/cache@v4
with:
path: ~/.cache/dep-freshness
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
restore-keys: dep-freshness-
- name: Every dependency is on newest stable
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict

View File

@ -1,33 +0,0 @@
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

View File

@ -17,22 +17,16 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- group: mypy
hooks: mypy
skip: ""
- group: pylint
hooks: pylint
skip: ""
- group: rest - group: rest
hooks: "" hooks: ""
skip: mypy,pylint skip: "dependency-freshness"
name: pre-commit (${{ matrix.group }}) name: pre-commit (${{ matrix.group }})
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
# The file-length, md-naming and dependency-freshness hooks delegate to # The file-length and md-naming hooks delegate to the shared gates in
# the shared gates in kuhyx/utils, which a runner does not have at # kuhyx/utils, which a runner does not have at $HOME/src/utils. Only
# $HOME/src/utils. Only the rest group runs them. # the rest group runs them.
- name: Check out the shared gates - name: Check out the shared gates
if: matrix.group == 'rest' if: matrix.group == 'rest'
uses: actions/checkout@v4 uses: actions/checkout@v4
@ -59,9 +53,9 @@ jobs:
# mypy and pylint bring their own hook environments, so they need only # mypy and pylint bring their own hook environments, so they need only
# pre-commit. The rest group's language: system patch-targets hook # pre-commit. The rest group's language: system patch-targets hook
# imports diet_guard and every patched module (requests, gatelock, # imports diet_guard and every patched module (requests, gatelock,
# crdt_sync, freedays, mcp, pydantic), and dependency-freshness needs # crdt_sync, freedays, mcp, pydantic) -- so it keeps the full
# pyyaml and packaging -- so it keeps the full requirements.txt. That # requirements.txt. That install used to run in the one job, with plain
# install used to run in the one job, with plain pip, for ~24 s. # pip, for ~24 s.
- name: Install pre-commit and the system hooks' imports - name: Install pre-commit and the system hooks' imports
run: | run: |
if [[ "${{ matrix.group }}" == rest ]]; then if [[ "${{ matrix.group }}" == rest ]]; then

View File

@ -60,7 +60,7 @@ jobs:
- uses: subosito/flutter-action@v2 - uses: subosito/flutter-action@v2
with: with:
flutter-version: 3.47.9 flutter-version: 3.50.1
channel: stable channel: stable
cache: true cache: true
@ -108,7 +108,9 @@ jobs:
run: | run: |
flutter build apk --release \ flutter build apk --release \
--build-name="${{ steps.ver.outputs.semver }}" \ --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 # Fail closed. `findByName("release") ?: debug` silently falls back to
# the debug key if key.properties is misplaced, producing a green build # the debug key if key.properties is misplaced, producing a green build

View File

@ -25,11 +25,6 @@ repos:
- id: check-merge-conflict - id: check-merge-conflict
- id: detect-private-key - id: detect-private-key
- id: debug-statements - id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
# 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: check-ast
- id: mixed-line-ending - id: mixed-line-ending
args: [--fix=lf] args: [--fix=lf]
@ -57,87 +52,9 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.2 rev: v0.15.2
hooks: hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format - id: ruff-format
types_or: [python, pyi] types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
additional_dependencies:
- types-requests
- repo: https://github.com/pylint-dev/pylint
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
- --jobs=4
additional_dependencies:
- pytest
- requests
# 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.14.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.5#subdirectory=sickdays
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.183
- 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)
- repo: https://github.com/PyCQA/bandit
rev: 1.7.10
hooks:
- id: bandit
args:
- -c
- pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(tests/|.*test.*\.py$)
- repo: local - repo: local
hooks: hooks:
# Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form. # Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form.
@ -165,71 +82,102 @@ repos:
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] 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 - id: ci-mirror-flutter-test-1
name: CI mirror 5 (flutter test 1/6) name: CI mirror 5 (flutter test 1/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/6 entry: bash scripts/ci_mirror.sh flutter-test --shard 0/12
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: ci-mirror-flutter-test-2 - id: ci-mirror-flutter-test-2
name: CI mirror 6 (flutter test 2/6) name: CI mirror 6 (flutter test 2/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 1/6 entry: bash scripts/ci_mirror.sh flutter-test --shard 1/12
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: ci-mirror-flutter-test-3 - id: ci-mirror-flutter-test-3
name: CI mirror 7 (flutter test 3/6) name: CI mirror 7 (flutter test 3/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 2/6 entry: bash scripts/ci_mirror.sh flutter-test --shard 2/12
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: ci-mirror-flutter-test-4 - id: ci-mirror-flutter-test-4
name: CI mirror 8 (flutter test 4/6) name: CI mirror 8 (flutter test 4/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 3/6 entry: bash scripts/ci_mirror.sh flutter-test --shard 3/12
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: ci-mirror-flutter-test-5 - id: ci-mirror-flutter-test-5
name: CI mirror 9 (flutter test 5/6) name: CI mirror 9 (flutter test 5/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 4/6 entry: bash scripts/ci_mirror.sh flutter-test --shard 4/12
language: system language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- id: ci-mirror-flutter-test-6 - id: ci-mirror-flutter-test-6
name: CI mirror 10 (flutter test 6/6) name: CI mirror 10 (flutter test 6/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 5/6 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 language: system
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
stages: [manual] stages: [manual]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- 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 - repo: local
hooks: hooks:
@ -251,29 +199,6 @@ repos:
pass_filenames: false pass_filenames: false
always_run: true always_run: true
require_serial: true require_serial: true
- id: shellcheck
name: shellcheck
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
language: system
types: [shell]
# A PKGBUILD is a makepkg manifest, not a standalone script: it has no
# 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$'
# 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
# unittest.mock.patch fails OPEN: once a refactor moves a name, a patch # unittest.mock.patch fails OPEN: once a refactor moves a name, a patch
# target that still imports redirects nothing, the test passes, and the # target that still imports redirects nothing, the test passes, and the
@ -281,7 +206,7 @@ repos:
# patch target statically so a stale path fails the commit instead. # patch target statically so a stale path fails the commit instead.
- id: patch-targets - id: patch-targets
name: test patch targets resolve name: test patch targets resolve
entry: python3 scripts/check_patch_targets.py entry: python3 scripts/check_patch_targets.py diet_guard
language: system language: system
pass_filenames: false pass_filenames: false
files: ^diet_guard/ files: ^diet_guard/

View File

@ -20,9 +20,10 @@ show adherence, streaks, a YTD tally and weekly/monthly averages, all derived fr
- run: `python -m diet_guard gate --demo` - 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: `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) - test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
- lint: `pre-commit run --all-files` - lint: n/a: dropped (kuhy, 2026-11-27)
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov) - coverage: n/a: dropped (kuhy, 2026-11-27)
- coverage-gaps: `coverage-gaps coverage.lcov` - deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
## Scheduling ## Scheduling
@ -142,6 +143,7 @@ install -e`, so the clone must persist for `git pull` to reach the running servi
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the `test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
existing `budget` record, so devices predating the feature relay them existing `budget` record, so devices predating the feature relay them
untouched. untouched.
- **Offline first**: save locally before any network call; store fetched data on disk (`kuchnia_delivery.json`, both devices).
- **Body data persists and syncs** (profile, weight log, PC workouts) as - **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). `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, - **PC and phone share one source of truth for everything**: food log, budget,
@ -238,10 +240,8 @@ only); the CLI, gate and phone show both.
## Flutter/Dart AI rules ## Flutter/Dart AI rules
_Vendored from [flutter/flutter _Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md) via via `~/.claude/CLAUDE.md`. Re-fetch periodically. Split across five files for the 250-line cap._
`~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically. Split across five files to
stay under the 250-line cap._
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md) - [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md) - [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)

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

@ -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 Then restart Claude Code in this repo and approve the project MCP server
(registered in `.mcp.json`). (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 ## Development
```bash ```bash

View File

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

View File

@ -3,6 +3,9 @@
library; library;
import 'dart:async'; 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/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.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/background_tasks.dart';
@ -10,8 +13,11 @@ 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/budget_history_service.dart';
import 'package:diet_guard_app/services/claude_relay_client.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/claude_relay_firebase.dart';
import 'package:diet_guard_app/services/document_store_factory.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/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.dart'; import 'package:diet_guard_app/services/frame_stats.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.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/kuchnia_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
@ -23,9 +29,27 @@ import 'package:material_ui/material_ui.dart';
Future<void> main() async { Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); 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 // Before anything that stamps an Hlc or syncs: until this resolves, the
// device id falls back to the pre-migration role constant. // 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 LogStorageService.init();
await AppSettingsService.init(); await AppSettingsService.init();
await BudgetHistoryService.init(); await BudgetHistoryService.init();
@ -34,6 +58,8 @@ Future<void> main() async {
await KuchniaCredentialService.init(); await KuchniaCredentialService.init();
await BodyService.init(); await BodyService.init();
await KuchniaQueueService.init(); await KuchniaQueueService.init();
// Offline first: the day's catering dishes survive a restart.
KuchniaAutoLog.instance = KuchniaAutoLog(store: await openDocumentStore());
// The sparkle button's transport; until this line it fails closed. // The sparkle button's transport; until this line it fails closed.
claudeRelay = RtdbClaudeRelay.firebase(); claudeRelay = RtdbClaudeRelay.firebase();
final notifications = await NotificationService.init(); final notifications = await NotificationService.init();
@ -55,19 +81,25 @@ Future<void> main() async {
// coverage:ignore-start // coverage:ignore-start
if (frameStatsEnabled) startFrameStats(); if (frameStatsEnabled) startFrameStats();
// coverage:ignore-end // coverage:ignore-end
runApp(const DietGuardApp()); runApp(DietGuardApp(errors: errors));
} }
/// Root widget for the Diet Guard companion app. /// Root widget for the Diet Guard companion app.
class DietGuardApp extends StatelessWidget { class DietGuardApp extends StatelessWidget {
/// Creates the [DietGuardApp] root widget. /// 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
title: 'Diet Guard', title: 'Diet Guard',
theme: buildAppTheme(), theme: buildAppTheme(),
navigatorObservers: [
if (errors case final errors?) AppErrorsRouteObserver(errors),
],
home: const LogMealScreen(), home: const LogMealScreen(),
); );
} }

View File

@ -23,6 +23,32 @@ class KuchniaDish {
this.dishId = '', this.dishId = '',
}); });
/// Rebuilds a dish stored by [toJson]; throws on a malformed record.
factory KuchniaDish.fromJson(Map<String, Object?> json) => KuchniaDish(
name: json['name']! as String,
kcal: (json['kcal']! as num).toDouble(),
proteinG: (json['protein_g']! as num).toDouble(),
carbsG: (json['carbs_g']! as num).toDouble(),
fatG: (json['fat_g']! as num).toDouble(),
grams: (json['grams']! as num).toDouble(),
priority: json['priority']! as int,
slotLabel: json['slot_label']! as String,
dishId: json['dish_id'] as String? ?? '',
);
/// The stored form; the keys follow the PC's `kuchnia_delivery.json`.
Map<String, Object?> toJson() => {
'name': name,
'kcal': kcal,
'protein_g': proteinG,
'carbs_g': carbsG,
'fat_g': fatG,
'grams': grams,
'priority': priority,
'slot_label': slotLabel,
'dish_id': dishId,
};
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...". /// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
/// ///
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse /// Not `mealName`, which is the slot label ("Kolacja") and would collapse

View File

@ -9,6 +9,7 @@ library;
import 'dart:async'; 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/day_status.dart';
import 'package:diet_guard_app/models/period_average.dart'; import 'package:diet_guard_app/models/period_average.dart';
import 'package:diet_guard_app/screens/history_screen.dart'; import 'package:diet_guard_app/screens/history_screen.dart';
@ -153,7 +154,7 @@ class _CalendarScreenState extends State<CalendarScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (_loading) { if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator())); return const Scaffold(body: WaitWatch.centered('calendar.load'));
} }
return Scaffold( return Scaffold(
appBar: AppBar(), appBar: AppBar(),

View File

@ -8,6 +8,7 @@ library;
import 'dart:async'; 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/models/food_bank_record.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart'; import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
@ -183,7 +184,7 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
], ],
), ),
body: all == null body: all == null
? const Center(child: CircularProgressIndicator()) ? const WaitWatch.centered('food_bank.load')
: _displayed.isEmpty : _displayed.isEmpty
? Center( ? Center(
child: Icon( child: Icon(

View File

@ -8,6 +8,7 @@ library;
import 'dart:async'; 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/firebase_client.dart';
import 'package:diet_guard_app/services/github_client_factory.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_health.dart';
@ -100,7 +101,7 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (_loading) { if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator())); return const Scaffold(body: WaitWatch.centered('github_mirror.load'));
} }
return Scaffold( return Scaffold(
// No title and no explanatory paragraph: the code glyph that opened this // No title and no explanatory paragraph: the code glyph that opened this
@ -161,6 +162,7 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
// it says nothing about Firebase. // it says nothing about Firebase.
IconButton.outlined( IconButton.outlined(
onPressed: _busy ? null : _testConnection, onPressed: _busy ? null : _testConnection,
tooltip: 'Test',
icon: const Icon( icon: const Icon(
Icons.network_check, Icons.network_check,
semanticLabel: 'Test GitHub connection', semanticLabel: 'Test GitHub connection',

View File

@ -7,6 +7,7 @@ library;
import 'dart:async'; 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/models/food_entry.dart';
import 'package:diet_guard_app/screens/edit_entry_screen.dart'; import 'package:diet_guard_app/screens/edit_entry_screen.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
@ -189,7 +190,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
], ],
), ),
body: allEntries == null body: allEntries == null
? const Center(child: CircularProgressIndicator()) ? const WaitWatch.centered('history.load')
: _displayed.isEmpty : _displayed.isEmpty
? Center( ? Center(
child: Icon( child: Icon(

View File

@ -31,7 +31,8 @@ Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
source: source, source: source,
); );
/// The five destination buttons in [LogMealScreen]'s app bar. /// 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 /// 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 /// as a list to be spread into `AppBar.actions`, so the bar's structure and
@ -42,24 +43,31 @@ List<Widget> logMealAppBarActions({
required VoidCallback onCalendar, required VoidCallback onCalendar,
required VoidCallback onSettings, required VoidCallback onSettings,
required VoidCallback onBody, required VoidCallback onBody,
List<Widget> leading = const [],
}) => [ }) => [
...leading,
IconButton( IconButton(
tooltip: 'Body',
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'), icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
onPressed: onBody, onPressed: onBody,
), ),
IconButton( IconButton(
tooltip: 'Foods',
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'), icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'),
onPressed: onFoodBank, onPressed: onFoodBank,
), ),
IconButton( IconButton(
tooltip: 'History',
icon: const Icon(Icons.history, semanticLabel: 'History'), icon: const Icon(Icons.history, semanticLabel: 'History'),
onPressed: onHistory, onPressed: onHistory,
), ),
IconButton( IconButton(
tooltip: 'Calendar',
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'), icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
onPressed: onCalendar, onPressed: onCalendar,
), ),
IconButton( IconButton(
tooltip: 'Sync',
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'), icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
onPressed: onSettings, onPressed: onSettings,
), ),

View File

@ -12,7 +12,6 @@ import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.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/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/pickers/pickers.dart'; import 'package:diet_guard_app/widgets/pickers/pickers.dart';
import 'package:diet_guard_app/widgets/slot_selector_row.dart'; import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:material_ui/material_ui.dart'; import 'package:material_ui/material_ui.dart';
@ -82,36 +81,40 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
onLogDateChanged(); onLogDateChanged();
} }
/// The "When" row: a "Log for later" button, or the picked date with a /// The app bar's date actions: the picker (leftmost icon) and, once a date
/// button to change it and one to clear back to today. /// is picked, a way back to today. A picked date tints the picker gold with
Widget buildWhenRow(BuildContext context) { /// a small dot; no text is painted.
List<Widget> buildDateActions(BuildContext context) {
final date = _futureDate; final date = _futureDate;
final scheme = Theme.of(context).colorScheme; final gold = Theme.of(context).colorScheme.primary;
return Row( return [
children: [
// Today is the default and shows nothing; only a picked date (data)
// is shown, marked by the calendar glyph.
if (date != null) ...[
Icon(
Icons.event,
size: 18,
color: scheme.onSurfaceVariant,
semanticLabel: 'Log date',
),
const SizedBox(width: AppSpacing.xs),
],
Expanded(
child: date == null ? const SizedBox() : Text(localDateKey(date)),
),
IconButton( IconButton(
// Not Icons.calendar_month: the app bar's own "Calendar" nav button // Not Icons.calendar_month: the bar's own "Calendar" nav button uses
// already uses that, and a second one on screen makes // that, and two on screen make `find.byIcon` ambiguous.
// `find.byIcon` ambiguous for widget tests (and taps) alike. icon: Stack(
icon: Icon( clipBehavior: Clip.none,
Icons.date_range, children: [
size: 18, Icon(
Icons.edit_calendar,
color: date == null ? null : gold,
semanticLabel: date == null ? 'Log for later' : 'Change date', 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, onPressed: _pickFutureDate,
), ),
if (date != null) if (date != null)
@ -119,8 +122,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
icon: const Icon(Icons.close, semanticLabel: 'Back to today'), icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
onPressed: resetFutureLog, onPressed: resetFutureLog,
), ),
], ];
);
} }
/// The slot row for a picked future date, else nothing. /// The slot row for a picked future date, else nothing.

View File

@ -22,6 +22,11 @@ mixin LogMealLoggedMixin<T extends StatefulWidget>
/// The rows under the action row, oldest first. /// The rows under the action row, oldest first.
List<LoggedMeal> loggedRows = const []; 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. /// Replaces the rows with [meals]: a new log retires the previous ones.
void showLogged(List<LoggedMeal> meals) { void showLogged(List<LoggedMeal> meals) {
if (mounted) setState(() => loggedRows = meals); if (mounted) setState(() => loggedRows = meals);
@ -57,12 +62,15 @@ mixin LogMealLoggedMixin<T extends StatefulWidget>
// single-flight, so calling super too would let the auto-log run before // single-flight, so calling super too would let the auto-log run before
// the pull finished). Pause still pushes through the sync mixin. // the pull finished). Pause still pushes through the sync mixin.
if (state == AppLifecycleState.resumed) { if (state == AppLifecycleState.resumed) {
unawaited(onOpenedOrResumed()); startOpenChain();
return; return;
} }
super.didChangeAppLifecycleState(state); 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, /// 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. /// pull what other devices logged, then auto-log what is still due.
Future<void> onOpenedOrResumed() async { Future<void> onOpenedOrResumed() async {

View File

@ -90,7 +90,7 @@ class _LogMealScreenState extends State<LogMealScreen>
unawaited(_onDescChanged()); unawaited(_onDescChanged());
// Health first, so a device that stalled earlier says so before a tick. // Health first, so a device that stalled earlier says so before a tick.
unawaited(refreshSyncHealth()); unawaited(refreshSyncHealth());
unawaited(onOpenedOrResumed()); startOpenChain();
} }
@override @override
@ -168,6 +168,8 @@ class _LogMealScreenState extends State<LogMealScreen>
final due = dueMode; final due = dueMode;
// Dimmed while Claude works, but never moved: nothing is added around it. // Dimmed while Claude works, but never moved: nothing is added around it.
final busy = claudeState == ClaudeButtonState.sending; 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; final dim = busy || claudeState == ClaudeButtonState.queued;
return Scaffold( return Scaffold(
appBar: due appBar: due
@ -179,6 +181,7 @@ class _LogMealScreenState extends State<LogMealScreen>
onCalendar: onOpenCalendar, onCalendar: onOpenCalendar,
onSettings: onOpenSettings, onSettings: onOpenSettings,
onBody: onOpenBody, onBody: onOpenBody,
leading: buildDateActions(context),
), ),
), ),
body: SafeArea( body: SafeArea(
@ -187,11 +190,7 @@ class _LogMealScreenState extends State<LogMealScreen>
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (!due) ...[ if (!due) SyncHealthBanner(status: syncHealth),
SyncHealthBanner(status: syncHealth),
buildWhenRow(context),
const SizedBox(height: AppSpacing.sm),
],
buildSlotRow(), buildSlotRow(),
Opacity( Opacity(
opacity: dim ? 0.5 : 1, opacity: dim ? 0.5 : 1,
@ -231,13 +230,14 @@ class _LogMealScreenState extends State<LogMealScreen>
onSend: sendToClaude, onSend: sendToClaude,
onLog: _onLogMeal, onLog: _onLogMeal,
), ),
if (!typing)
for (final meal in loggedRows) for (final meal in loggedRows)
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)), LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
if (_cue != null) ...[ if (_cue != null) ...[
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
_cue!.widget, _cue!.widget,
], ],
if (_progress != null && !due) ...[ if (_progress != null && !due && !typing) ...[
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
TodayProgressCard(progress: _progress!), TodayProgressCard(progress: _progress!),
], ],

View File

@ -8,6 +8,7 @@ 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/github_client_factory.dart';
import 'package:diet_guard_app/services/health_steps.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/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_health.dart';
import 'package:diet_guard_app/services/sync_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/sync_settings.dart';
@ -68,6 +69,7 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
Future<void> autoSync() async { Future<void> autoSync() async {
if (autoSyncing) return; if (autoSyncing) return;
autoSyncing = true; autoSyncing = true;
bool? landed; // null until the sync itself ran
try { try {
final settings = await SyncSettings.load(); final settings = await SyncSettings.load();
// Either backend counts. `isConfigured` means "has a GitHub token", so // Either backend counts. `isConfigured` means "has a GitHub token", so
@ -87,17 +89,19 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
return; return;
} }
final client = createGitHubClient(settings, httpClient: syncHttpClient); final client = createGitHubClient(settings, httpClient: syncHttpClient);
landed = await attemptSync(() async {
try { try {
// Foreground only (this mixin is UI), and never prompts: fresh // Foreground only (this mixin is UI), and never prompts: fresh
// Health Connect steps ride along in this tick's body.json. // Health Connect steps ride along in this tick's body.json.
await refreshSteps(); await refreshSteps();
await runSync(await syncBackend(client)); await runSync(await syncBackend(client));
await SyncHealth.recordSuccess();
} finally { } finally {
client.close(); client.close();
} }
});
if (!mounted) return; if (!mounted) return;
await refreshSlots(); // Outside attemptSync: a refresh error is no sync failure.
if (landed) await refreshSlots();
await refreshSyncHealth(); await refreshSyncHealth();
} on Object catch (error, stackTrace) { } on Object catch (error, stackTrace) {
// Best-effort, but never silent: this swallowed the reason a desktop // Best-effort, but never silent: this swallowed the reason a desktop
@ -110,7 +114,9 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
error: error, error: error,
stackTrace: stackTrace, stackTrace: stackTrace,
); );
await SyncHealth.recordFailure(); // 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(); if (mounted) await refreshSyncHealth();
} finally { } finally {
autoSyncing = false; autoSyncing = false;

View File

@ -15,6 +15,7 @@
/// encrypted either. /// encrypted either.
library; 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_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.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/services/kuchnia_import.dart';
@ -188,9 +189,12 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
IconButton.outlined( IconButton.outlined(
onPressed: canFetch && !_busy ? _fetch : null, onPressed: canFetch && !_busy ? _fetch : null,
icon: _busy icon: _busy
? const SizedBox.square( ? const WaitWatch(
operation: 'kuchnia.sync',
child: SizedBox.square(
dimension: 20, dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(strokeWidth: 2),
),
) )
: const Icon( : const Icon(
Icons.local_shipping_outlined, Icons.local_shipping_outlined,

View File

@ -27,6 +27,7 @@ import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:kuhy_credit/kuhy_credit.dart';
import 'package:material_ui/material_ui.dart'; import 'package:material_ui/material_ui.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:sync_settings_ui/sync_settings_ui.dart'; import 'package:sync_settings_ui/sync_settings_ui.dart';
@ -50,8 +51,7 @@ class SettingsScreen extends StatefulWidget {
this.firebaseFactory, this.firebaseFactory,
}); });
/// Injectable HTTP client for the linked [GitHubMirrorScreen]; tests pass /// HTTP client for the linked [GitHubMirrorScreen]; tests pass [MockClient].
/// a [MockClient].
final http.Client? httpClient; final http.Client? httpClient;
/// Injectable battery-optimization-exemption request; tests pass a fake. /// Injectable battery-optimization-exemption request; tests pass a fake.
@ -71,14 +71,10 @@ class SettingsScreen extends StatefulWidget {
/// Reads the stored Firebase account. Injected for the same reason as /// Reads the stored Firebase account. Injected for the same reason as
/// [googleFirebaseFactory]: the keystore is a platform channel. /// [googleFirebaseFactory]: the keystore is a platform channel.
/// ///
/// Deliberately backed by [storedAccount], not [loadAccount]: the shared /// Backed by [storedAccount], not [loadAccount]: the shared screen reads
/// `SyncSettingsScreen` uses this single closure both to display the /// the account back right after a Google sign-in, and [loadAccount]'s
/// status and to read back the account right after a Google sign-in. /// desktop fallback throws on Android (seen on the phone as "Google sign-in
/// [loadAccount]'s desktop-wrapper fallback resolves to `file:///` on /// failed"). See the keystore-only read in [firebase_backend.dart].
/// Android and throws -- verified on the phone, where it turned a
/// successful sign-in into "Google sign-in failed". `storedAccount` is the
/// keystore-only read [firebase_backend.dart] documents for exactly this
/// read-back case.
final Future<FirebaseAccount?> Function()? accountLoader; final Future<FirebaseAccount?> Function()? accountLoader;
/// Persists the account. See [accountLoader]. /// Persists the account. See [accountLoader].
@ -241,6 +237,10 @@ class _SettingsScreenState extends State<SettingsScreen>
const SizedBox(height: 16), const SizedBox(height: 16),
Align(alignment: Alignment.centerLeft, child: _status), Align(alignment: Alignment.centerLeft, child: _status),
], ],
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
const Align(alignment: Alignment.centerLeft, child: KuhyCredit()),
], ],
), ),
), ),

View File

@ -15,6 +15,7 @@ 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/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/log_storage_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/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_device_id.dart';
import 'package:diet_guard_app/services/sync_health.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_service.dart';
@ -90,21 +91,14 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
return true; // nothing to push; don't retry return true; // nothing to push; don't retry
} }
final client = createGitHubClient(settings, httpClient: httpClient); final client = createGitHubClient(settings, httpClient: httpClient);
// 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 { try {
await runSync(await syncBackend(client)); await runSync(await syncBackend(client));
await SyncHealth.recordSuccess();
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,
);
await SyncHealth.recordFailure();
return false; // offline / transient error -> retry with backoff
} finally { } finally {
client.close(); client.close();
} }
});
return landed;
} }

View File

@ -13,16 +13,21 @@
/// An undone dish keeps its tombstone, so it is never logged a second time. /// An undone dish keeps its tombstone, so it is never logged a second time.
/// ///
/// The fetch is a third-party login, so the day's dishes are cached in memory /// The fetch is a third-party login, so the day's dishes are cached in memory
/// and a failed or empty fetch is retried at most every [retryAfter]. /// and in `store` (`kuchnia_delivery.json`), so a restart or an outage still
/// has them (offline first); a failed or empty fetch is retried at most every
/// [retryAfter].
/// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean /// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean
/// fetch of the day it returns nothing, and slots that fall due later would /// fetch of the day it returns nothing, and slots that fall due later would
/// never see their dish. /// never see their dish.
library; library;
import 'dart:convert';
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/kuchnia_dish.dart'; import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_fill.dart'; import 'package:diet_guard_app/services/kuchnia_fill.dart';
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart'; import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart'; import 'package:diet_guard_app/services/kuchnia_import.dart';
@ -44,6 +49,7 @@ class KuchniaAutoLog {
DeliveryFetch? fetch, DeliveryFetch? fetch,
DateTime Function()? now, DateTime Function()? now,
this.retryAfter = const Duration(minutes: 10), this.retryAfter = const Duration(minutes: 10),
this.store,
}) : _fetch = fetch ?? refreshDelivery, }) : _fetch = fetch ?? refreshDelivery,
_now = now ?? DateTime.now; _now = now ?? DateTime.now;
@ -53,6 +59,12 @@ class KuchniaAutoLog {
/// Minimum gap between fetches that found nothing or failed. /// Minimum gap between fetches that found nothing or failed.
final Duration retryAfter; final Duration retryAfter;
/// Keeps the day's dishes across restarts; null keeps them in memory only.
final DocumentStore? store;
/// The document [store] holds the last fetched delivery in.
static const documentName = 'kuchnia_delivery.json';
final DeliveryFetch _fetch; final DeliveryFetch _fetch;
final DateTime Function() _now; final DateTime Function() _now;
String? _cachedDay; String? _cachedDay;
@ -94,14 +106,56 @@ class KuchniaAutoLog {
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async { Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
if (_cachedDay == dayKey) return _cachedDishes; if (_cachedDay == dayKey) return _cachedDishes;
final stored = await _readStored(dayKey);
if (stored.isNotEmpty) {
_cachedDay = dayKey;
return _cachedDishes = stored;
}
final last = _lastEmptyFetch; final last = _lastEmptyFetch;
if (last != null && _now().difference(last) < retryAfter) return const []; if (last != null && _now().difference(last) < retryAfter) return const [];
final result = await _fetch(today); final result = await _fetch(today);
if (result.ok && result.dishes.isNotEmpty) { if (result.ok && result.dishes.isNotEmpty) {
_cachedDay = dayKey; _cachedDay = dayKey;
await _writeStored(dayKey, result.dishes);
return _cachedDishes = result.dishes; return _cachedDishes = result.dishes;
} }
_lastEmptyFetch = _now(); _lastEmptyFetch = _now();
return const []; return const [];
} }
Future<List<KuchniaDish>> _readStored(String dayKey) async {
final target = store;
if (target == null) return const [];
try {
final raw = await target.read(documentName);
if (raw == null) return const [];
final data = jsonDecode(raw);
if (data is! Map<String, Object?> || data['day'] != dayKey) {
return const [];
}
final dishes = data['dishes'];
if (dishes is! List) return const [];
return [
for (final item in dishes)
if (item is Map<String, Object?>) KuchniaDish.fromJson(item),
];
} on Object {
// A missing, foreign or malformed file is "nothing stored": fetch again.
return const [];
}
}
Future<void> _writeStored(String dayKey, List<KuchniaDish> dishes) async {
final target = store;
if (target == null) return;
final body = {
'day': dayKey,
'dishes': [for (final dish in dishes) dish.toJson()],
};
try {
await target.write(documentName, jsonEncode(body));
} on Exception {
// Best-effort: an unsaved delivery only costs a refetch after a restart.
}
}
} }

View File

@ -0,0 +1,42 @@
/// Runs one sync and records its outcome for the "not syncing" banner.
///
/// The banner said "Not syncing" on a phone whose sync looked fine, and the
/// release build keeps no log that could say why (see `sync_health.dart`).
/// So a failure here also goes to the board through the app-wide reporter:
/// the next one files its own ticket with the exception that caused it.
/// Inside a WorkManager isolate no reporter is installed, so a background
/// failure is only recorded, not filed.
///
/// Only the sync itself is timed in: screen refreshes after a landed sync
/// run outside, so their errors never mark a working sync as failed.
library;
import 'dart:developer';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show AppErrors;
import 'package:diet_guard_app/services/sync_health.dart';
/// Runs [sync]; records success, or failure plus a `sync.failed` report.
///
/// Returns whether the sync landed. Never throws.
Future<bool> attemptSync(Future<void> Function() sync) async {
try {
await sync();
} on Object catch (error, stackTrace) {
log(
'diet_guard sync failed',
level: 1000,
error: error,
stackTrace: stackTrace,
);
AppErrors.instance?.reporter.report(
'sync.failed',
error,
stack: stackTrace,
);
await SyncHealth.recordFailure();
return false;
}
await SyncHealth.recordSuccess();
return true;
}

View File

@ -8,6 +8,7 @@
/// send or log. /// send or log.
library; library;
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:material_ui/material_ui.dart'; import 'package:material_ui/material_ui.dart';
@ -127,11 +128,14 @@ class MealActionRow extends StatelessWidget {
); );
Widget _claudeFace() => switch (claude) { Widget _claudeFace() => switch (claude) {
ClaudeButtonState.sending => const SizedBox( ClaudeButtonState.sending => const WaitWatch(
operation: 'claude.estimate',
child: SizedBox(
width: 24, width: 24,
height: 24, height: 24,
child: CircularProgressIndicator(strokeWidth: 3), child: CircularProgressIndicator(strokeWidth: 3),
), ),
),
ClaudeButtonState.queued => const Icon( ClaudeButtonState.queued => const Icon(
Icons.hourglass_top, Icons.hourglass_top,
semanticLabel: 'Waiting for the PC', semanticLabel: 'Waiting for the PC',

View File

@ -123,6 +123,7 @@ class MealTimeDropdown extends StatelessWidget {
), ),
), ),
IconButton( IconButton(
tooltip: 'Time',
icon: const Icon( icon: const Icon(
Icons.schedule, Icons.schedule,
semanticLabel: 'Type or pick an exact time', semanticLabel: 'Type or pick an exact time',

View File

@ -5,10 +5,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: android_file_picker name: android_file_picker
sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b" sha256: ec3cf2a2c7a9b2bd56747e85f80efdd994e563049dfb0981a23903acfdd58cb5
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.5" version: "2.2.0"
archive: archive:
dependency: transitive dependency: transitive
description: description:
@ -157,20 +157,20 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
path: crdt_sync_dart path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.1" ref: "crdt_sync_dart-v0.14.2"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.14.1" version: "0.14.2"
crdt_sync_flutter: crdt_sync_flutter:
dependency: "direct main" dependency: "direct main"
description: description:
path: crdt_sync_flutter path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.8.3" ref: "crdt_sync_flutter-v0.9.2"
resolved-ref: "6e3f86ef0d73ba45db975bf03915fecce8a60f98" resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.8.3" version: "0.9.2"
cross_file: cross_file:
dependency: transitive dependency: transitive
description: description:
@ -207,11 +207,11 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
path: data_transfer_flutter path: data_transfer_flutter
ref: "data_transfer_flutter-v0.2.2" ref: "data_transfer_flutter-v0.2.4"
resolved-ref: eef7af4c86837ee82891493587ff3456297e5dea resolved-ref: "5c2effe7d1148830c9e273e47a272791dc17509e"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.2.2" version: "0.2.4"
dbus: dbus:
dependency: transitive dependency: transitive
description: description:
@ -280,10 +280,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: file_picker name: file_picker
sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86" sha256: "5b99250437a4d34ee2cdc0686924452103540eaa1c248094b63f07f9d7216f6c"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "13.3.3" version: "13.4.1"
file_picker_darwin: file_picker_darwin:
dependency: transitive dependency: transitive
description: description:
@ -296,18 +296,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: file_picker_linux name: file_picker_linux
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b" sha256: cf3889644e8e54551f5c3a4f98b6b6ef5f0ef85c07d2a0c1a969538983be2f9b
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.4" version: "2.0.5"
file_picker_platform_interface: file_picker_platform_interface:
dependency: transitive dependency: transitive
description: description:
name: file_picker_platform_interface name: file_picker_platform_interface
sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20" sha256: a2ef71c4628f92a4471d424576e3bf7042b40a2683c9f9a0e3033a7fc7f7763c
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.2.0" version: "4.3.0"
file_picker_web: file_picker_web:
dependency: transitive dependency: transitive
description: description:
@ -392,10 +392,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: fl_chart name: fl_chart
sha256: "9f11b0b87a6b1843f5ca666ade4a62c08da1a6b7f9efeb91bb2c6f3fa6e31a9a" sha256: "19e4b58179f77b0858ddb9f2db321394e466cba7b2b918b0af7abd79754a1de9"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.3.1" version: "1.3.2"
flutter: flutter:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
@ -413,10 +413,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: flutter_local_notifications name: flutter_local_notifications
sha256: fac349e7361f80591a0cedff03548f807282c9faee9fc6192763166e5f81def2 sha256: "2b7579556c117b535ef83835798a7f3c4003dc892a888a4a99f2107bca7b6675"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "23.0.2" version: "23.0.4"
flutter_local_notifications_linux: flutter_local_notifications_linux:
dependency: transitive dependency: transitive
description: description:
@ -542,10 +542,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: health name: health
sha256: "8dd9625c9c26379a5753ad24c33af1d3dc5ce1f36f19c03e17c676c2f8fdbb80" sha256: "683d15fdde49a942bacce871faf3090bda3c1f5dad995725337aeb1dfd348e6d"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "13.3.2" version: "14.0.0"
hooks: hooks:
dependency: transitive dependency: transitive
description: description:
@ -682,6 +682,15 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.12.0" version: "4.12.0"
kuhy_credit:
dependency: "direct main"
description:
path: "kuhy_credit/flutter"
ref: "kuhy-credit-v0.3.2"
resolved-ref: adeb40f68e1d6c701da43e396fc46bffa3ef10c7
url: "https://github.com/kuhyx/utils"
source: git
version: "0.3.2"
leak_tracker: leak_tracker:
dependency: transitive dependency: transitive
description: description:
@ -778,6 +787,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.2.0"
package_info_plus:
dependency: transitive
description:
name: package_info_plus
sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908"
url: "https://pub.dev"
source: hosted
version: "10.2.2"
package_info_plus_platform_interface:
dependency: transitive
description:
name: package_info_plus_platform_interface
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
url: "https://pub.dev"
source: hosted
version: "4.1.0"
path: path:
dependency: "direct main" dependency: "direct main"
description: description:
@ -1051,11 +1076,11 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
path: sync_settings_ui path: sync_settings_ui
ref: "sync_settings_ui-v0.8.3" ref: "sync_settings_ui-v0.8.6"
resolved-ref: dde5566b2c6eb38a8e1e58a4252925f3baca8ad1 resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.8.3" version: "0.8.6"
synchronized: synchronized:
dependency: transitive dependency: transitive
description: description:

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go." description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none' publish_to: 'none'
version: 1.0.177+1 version: 1.0.197+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2
@ -12,13 +12,13 @@ dependencies:
crdt_sync: crdt_sync:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.1 ref: crdt_sync_dart-v0.14.2
path: crdt_sync_dart path: crdt_sync_dart
# Keystore-backed end-to-end encryption open + the passphrase lock button. # Keystore-backed end-to-end encryption open + the passphrase lock button.
crdt_sync_flutter: crdt_sync_flutter:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: crdt_sync_flutter-v0.8.3 ref: crdt_sync_flutter-v0.9.2
path: crdt_sync_flutter path: crdt_sync_flutter
crypto: 3.0.8 crypto: 3.0.8
cryptography: 2.9.0 cryptography: 2.9.0
@ -27,12 +27,12 @@ dependencies:
data_transfer_flutter: data_transfer_flutter:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.2 ref: data_transfer_flutter-v0.2.4
path: data_transfer_flutter path: data_transfer_flutter
fl_chart: 1.3.1 fl_chart: 1.3.2
flutter: flutter:
sdk: flutter sdk: flutter
flutter_local_notifications: 23.0.2 flutter_local_notifications: 23.0.4
flutter_secure_storage: 11.2.0 flutter_secure_storage: 11.2.0
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure # One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
@ -48,11 +48,16 @@ dependencies:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: google_account_token-v0.1.0 ref: google_account_token-v0.1.0
path: google_account_token path: google_account_token
health: 13.3.2 health: 14.0.0
http: 1.6.0 http: 1.6.0
idb_shim: 2.11.3 idb_shim: 2.11.3
# Camera/gallery photo as transient input to Claude (never stored or synced). # Camera/gallery photo as transient input to Claude (never stored or synced).
image_picker: 1.2.4 image_picker: 1.2.4
kuhy_credit:
git:
url: https://github.com/kuhyx/utils
ref: kuhy-credit-v0.3.2
path: kuhy_credit/flutter
material_ui: 1.11.1 material_ui: 1.11.1
path: 1.9.1 path: 1.9.1
path_provider: 2.1.6 path_provider: 2.1.6
@ -66,7 +71,7 @@ dependencies:
sync_settings_ui: sync_settings_ui:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.8.3 ref: sync_settings_ui-v0.8.6
path: sync_settings_ui path: sync_settings_ui
url_launcher: 6.3.3 url_launcher: 6.3.3
uuid: 4.6.0 uuid: 4.6.0

View File

@ -0,0 +1,27 @@
import 'package:diet_guard_app/screens/log_meal_actions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('logMealAppBarActions tooltips name each icon', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: logMealAppBarActions(
onFoodBank: () {},
onHistory: () {},
onCalendar: () {},
onSettings: () {},
onBody: () {},
),
),
),
),
);
for (final label in ['Body', 'Foods', 'History', 'Calendar', 'Sync']) {
expect(find.byTooltip(label), findsOneWidget, reason: label);
}
});
}

View File

@ -5,7 +5,8 @@
/// A word is two or more letters in a row. Allowed without listing: numbers, /// A word is two or more letters in a row. Allowed without listing: numbers,
/// punctuation, single letters, unit symbols next to a figure ([unitTokens]) /// punctuation, single letters, unit symbols next to a figure ([unitTokens])
/// and the method acronyms kept as DOUBT rows (`MET`). Content (food names, /// and the method acronyms kept as DOUBT rows (`MET`). Content (food names,
/// workout labels, typed values) is passed per test as [content]. /// workout labels, typed values) is passed per test as [content]. One-word
/// tooltips naming an icon are exempt (textgate one-word-tooltip exception).
library; library;
import 'package:material_ui/material_ui.dart'; import 'package:material_ui/material_ui.dart';
@ -16,11 +17,15 @@ const Set<String> unitTokens = {'kcal', 'kg', 'cm', 'lb', 'st', 'MET'};
final RegExp _word = RegExp('[A-Za-z]{2,}'); final RegExp _word = RegExp('[A-Za-z]{2,}');
/// A one-word tooltip naming an icon (textgate exception, 2026-11-22).
final RegExp _oneWordTooltip = RegExp(r'^[A-Za-z][A-Za-z-]{0,19}$');
/// Every painted string in the current tree (one per [RichText] / tooltip). /// Every painted string in the current tree (one per [RichText] / tooltip).
List<String> paintedStrings(WidgetTester tester) => [ List<String> paintedStrings(WidgetTester tester) => [
for (final w in tester.widgetList<RichText>(find.byType(RichText))) for (final w in tester.widgetList<RichText>(find.byType(RichText)))
w.text.toPlainText(includePlaceholders: false), w.text.toPlainText(includePlaceholders: false),
for (final w in tester.widgetList<Tooltip>(find.byType(Tooltip))) ?w.message, for (final w in tester.widgetList<Tooltip>(find.byType(Tooltip)))
if (w.message case final m? when !_oneWordTooltip.hasMatch(m)) m,
]; ];
/// The words in [text] that are neither units nor part of [content]. /// The words in [text] that are neither units nor part of [content].

View File

@ -65,13 +65,20 @@ void main() {
// GitHubMirrorScreen loads its settings via a fire-and-forget Future in // GitHubMirrorScreen loads its settings via a fire-and-forget Future in
// initState that Flutter's frame scheduler does not track -- same pitfall // initState that Flutter's frame scheduler does not track -- same pitfall
// as HistoryScreen/LogMealScreen. // as HistoryScreen/LogMealScreen.
Future<void> settle(WidgetTester tester) async { // [until]: keep pumping (max 5 s) until it is found -- a sync tick's real
// I/O outlasts the fixed 200 ms on a loaded machine.
Future<void> settle(WidgetTester tester, {Finder? until}) async {
tester.view.physicalSize = const Size(800, 1400); tester.view.physicalSize = const Size(800, 1400);
tester.view.devicePixelRatio = 1.0; tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.view.resetDevicePixelRatio);
final deadline = DateTime.now().add(const Duration(seconds: 5));
do {
await Future<void>.delayed(const Duration(milliseconds: 200)); await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} while (until != null &&
until.evaluate().isEmpty &&
DateTime.now().isBefore(deadline));
} }
/// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth /// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth
@ -167,7 +174,7 @@ void main() {
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Sync now')); await tester.tap(controlByLabel('Sync now'));
await settle(tester); await settle(tester, until: cueLabelled('Synced.'));
expect(cueLabelled('Synced.'), findsOneWidget); expect(cueLabelled('Synced.'), findsOneWidget);
}); });
@ -197,7 +204,7 @@ void main() {
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Sync now')); await tester.tap(controlByLabel('Sync now'));
await settle(tester); await settle(tester, until: cueLabelled('Synced.'));
expect(cueLabelled('Synced.'), findsOneWidget); expect(cueLabelled('Synced.'), findsOneWidget);
final status = await SyncHealth.read(); final status = await SyncHealth.read();
@ -228,7 +235,7 @@ void main() {
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Sync now')); await tester.tap(controlByLabel('Sync now'));
await settle(tester); await settle(tester, until: cueOfKind(CueKind.error));
expect(cueOfKind(CueKind.error), findsOneWidget); expect(cueOfKind(CueKind.error), findsOneWidget);
}); });

View File

@ -47,7 +47,7 @@ void main() {
Future<void> open(WidgetTester tester) async { Future<void> open(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settleOpen(tester);
} }
testWidgets('opening in due mode logs the due dishes with no tap', ( testWidgets('opening in due mode logs the due dishes with no tap', (
@ -72,7 +72,11 @@ void main() {
await tester.runAsync(() async { await tester.runAsync(() async {
await open(tester); await open(tester);
await tester.tap(byIconLabel('Undo').first); await tester.tap(byIconLabel('Undo').first);
await settle(tester); await settleUntil(
tester,
() async =>
(await LogStorageService.instance.todayEntries()).length == 1,
);
expect(find.byIcon(Icons.restaurant), findsOneWidget); expect(find.byIcon(Icons.restaurant), findsOneWidget);
var live = await LogStorageService.instance.todayEntries(); var live = await LogStorageService.instance.todayEntries();
expect(live.map((e) => e.desc), ['Danie 2']); expect(live.map((e) => e.desc), ['Danie 2']);
@ -130,7 +134,7 @@ void main() {
(state as WidgetsBindingObserver).didChangeAppLifecycleState( (state as WidgetsBindingObserver).didChangeAppLifecycleState(
AppLifecycleState.resumed, AppLifecycleState.resumed,
); );
await settle(tester); await settleOpen(tester);
final entries = await LogStorageService.instance.todayEntries(); final entries = await LogStorageService.instance.todayEntries();
expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']); expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']);

View File

@ -38,7 +38,7 @@ void main() {
Future<void> open(WidgetTester tester) async { Future<void> open(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(home: LogMealScreen(relay: relay))); await tester.pumpWidget(MaterialApp(home: LogMealScreen(relay: relay)));
await settle(tester); await settleOpen(tester);
} }
testWidgets('the request id is a ULID and the mode follows due mode', ( testWidgets('the request id is a ULID and the mode follows due mode', (
@ -75,7 +75,12 @@ void main() {
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log meal')); await tester.tap(controlByLabel('Log meal'));
await settle(tester); await settleUntil(
tester,
() async =>
relay.cancelled.isNotEmpty &&
byIconLabel('Ask Claude').evaluate().isNotEmpty,
);
expect(relay.cancelled, [relay.sent.single.requestId]); expect(relay.cancelled, [relay.sent.single.requestId]);
expect(byIconLabel('Ask Claude'), findsOneWidget); expect(byIconLabel('Ask Claude'), findsOneWidget);
@ -88,7 +93,12 @@ void main() {
_claudeEntry(claudeEntryId(relay.sent.single.requestId)), _claudeEntry(claudeEntryId(relay.sent.single.requestId)),
), ),
); );
await settle(tester); await settleUntil(
tester,
() async =>
(await LogStorageService.instance.todayEntries()).length ==
(claimed ? 2 : 1),
);
final live = await LogStorageService.instance.todayEntries(); final live = await LogStorageService.instance.todayEntries();
expect(live, hasLength(claimed ? 2 : 1)); expect(live, hasLength(claimed ? 2 : 1));
}); });

View File

@ -54,7 +54,7 @@ void main() {
await open(tester); await open(tester);
expect(find.byType(AppBar), findsNothing); expect(find.byType(AppBar), findsNothing);
expect(find.byType(SyncHealthBanner), findsNothing); expect(find.byType(SyncHealthBanner), findsNothing);
expect(find.byIcon(Icons.date_range), findsNothing); expect(find.byIcon(Icons.edit_calendar), findsNothing);
expect(find.byType(ChoiceChip), findsNothing); expect(find.byType(ChoiceChip), findsNothing);
expect(find.byIcon(Icons.playlist_add_check), findsNothing); expect(find.byIcon(Icons.playlist_add_check), findsNothing);
// What stays: field, six macro fields, the three buttons. // What stays: field, six macro fields, the three buttons.
@ -71,7 +71,7 @@ void main() {
await tester.runAsync(() async { await tester.runAsync(() async {
await open(tester); await open(tester);
expect(find.byType(AppBar), findsOneWidget); expect(find.byType(AppBar), findsOneWidget);
expect(find.byIcon(Icons.date_range), findsOneWidget); expect(find.byIcon(Icons.edit_calendar), findsOneWidget);
expect(find.byType(ChoiceChip), findsNothing); expect(find.byType(ChoiceChip), findsNothing);
expect(find.byIcon(Icons.playlist_add_check), findsNothing); expect(find.byIcon(Icons.playlist_add_check), findsNothing);
expect(byIconLabel('Photo'), findsOneWidget); expect(byIconLabel('Photo'), findsOneWidget);

View File

@ -122,7 +122,9 @@ void main() {
), ),
); );
await settle(tester); await settle(tester);
expect(find.byIcon(Icons.undo), findsOneWidget); // The logged row collapses while the keyboard is up (no cover by
// keyboard); log_meal_keyboard_test.dart covers it coming back.
expect(find.byIcon(Icons.undo), findsNothing);
// Still due (12:00 is open): the screen stays in due mode. // Still due (12:00 is open): the screen stays in due mode.
expect(find.byType(AppBar), findsNothing); expect(find.byType(AppBar), findsNothing);
await fillWorstCase(tester); await fillWorstCase(tester);

View File

@ -0,0 +1,170 @@
/// kuhy's hard rule, 2026-11-17: NO COVER BY KEYBOARD EVER. With the keyboard
/// open the today-progress card and the logged rows collapse, so the field,
/// suggestions, macro fields and action row all sit above it with no scroll.
/// Also the date picker's move into the app bar and its picked-date tint.
library;
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
import 'package:diet_guard_app/widgets/meal_action_row.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import '../label_finders.dart';
import 'log_meal_test_support.dart';
const double _dpr = 2.625;
void _phone(WidgetTester tester, {required double keyboardPx}) {
tester.view
..physicalSize = const Size(1080, 2400)
..devicePixelRatio = _dpr
..padding = const FakeViewPadding(top: 132, bottom: 63)
..viewPadding = const FakeViewPadding(top: 132, bottom: 63)
..viewInsets = FakeViewPadding(bottom: keyboardPx);
}
double _maxScroll(WidgetTester tester) => tester
.state<ScrollableState>(
find
.descendant(
of: find.byType(SingleChildScrollView),
matching: find.byType(Scrollable),
)
.first,
)
.position
.maxScrollExtent;
/// Every widget the form shows ends above the keyboard, the action row is
/// tappable, and nothing scrolls.
void _expectAboveKeyboard(WidgetTester tester, double keyboardPx) {
final keyboardTop = (2400 - keyboardPx) / _dpr;
for (final type in <Type>[
TextField,
MealActionRow,
LoggedMealRow,
TodayProgressCard,
]) {
for (final e in find.byType(type).evaluate()) {
final box = e.renderObject! as RenderBox;
final bottom = box.localToGlobal(Offset(0, box.size.height)).dy;
expect(bottom, lessThanOrEqualTo(keyboardTop), reason: '$type covered');
}
}
expect(controlByLabel('Log meal').hitTestable(), findsOneWidget);
expect(controlByLabel('Photo').hitTestable(), findsOneWidget);
expect(_maxScroll(tester), 0, reason: 'the form scrolls');
}
void main() {
late Future<void> Function() restore;
setUp(() async => restore = await isolateLogScreenState());
tearDown(() => restore());
Future<void> open(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester);
}
Future<void> fillWorstCase(WidgetTester tester, String name) async {
await tester.enterText(find.byType(TextField).at(0), name);
final worst = ['1250', '2400', '1234', '1234', '1234', '1234'];
for (var i = 0; i < worst.length; i++) {
await tester.enterText(find.byType(TextField).at(i + 1), worst[i]);
}
await settle(tester);
}
for (final kb in [840.0, 1050.0]) {
testWidgets('normal mode, keyboard $kb px: nothing under it', (
tester,
) async {
addTearDown(tester.view.reset);
_phone(tester, keyboardPx: 0);
await tester.runAsync(() async {
await open(tester);
await fillWorstCase(tester, 'kurczak z ryzem');
await tester.tap(controlByLabel('Log meal'));
await settle(tester);
// Keyboard closed: the card and the logged row are both there.
expect(find.byType(TodayProgressCard), findsOneWidget);
expect(find.byType(LoggedMealRow), findsOneWidget);
_phone(tester, keyboardPx: kb);
await fillWorstCase(tester, 'kurczak');
expect(find.byType(TodayProgressCard), findsNothing);
expect(find.byType(LoggedMealRow), findsNothing);
_expectAboveKeyboard(tester, kb);
_phone(tester, keyboardPx: 0);
await settle(tester);
expect(find.byType(LoggedMealRow), findsOneWidget);
});
});
testWidgets('due mode, keyboard $kb px: nothing under it', (tester) async {
addTearDown(tester.view.reset);
_phone(tester, keyboardPx: kb);
pinLogMealClock(13);
await tester.runAsync(() async {
await open(tester);
await fillWorstCase(tester, 'kurczak z ryzem');
expect(find.byType(AppBar), findsNothing);
_expectAboveKeyboard(tester, kb);
});
});
}
group('date picker in the app bar', () {
Color tint(WidgetTester tester) {
final icon = find.byIcon(Icons.edit_calendar);
return tester.widget<Icon>(icon).color ??
IconTheme.of(tester.element(icon)).color!;
}
testWidgets('leftmost action; no row above the field', (tester) async {
await tester.runAsync(() async {
await open(tester);
final date = find.byIcon(Icons.edit_calendar);
expect(
find.descendant(of: find.byType(AppBar), matching: date),
findsOneWidget,
);
expect(find.byIcon(Icons.date_range), findsNothing);
final x = tester.getCenter(date).dx;
for (final other in [Icons.monitor_weight, Icons.settings]) {
expect(x, lessThan(tester.getCenter(find.byIcon(other)).dx));
}
});
});
testWidgets('a picked future date tints the icon gold with a dot', (
tester,
) async {
await tester.runAsync(() async {
await open(tester);
final gold = Theme.of(
tester.element(find.byType(AppBar)),
).colorScheme.primary;
const badge = ValueKey<String>('log-date-badge');
expect(tint(tester), isNot(gold));
expect(find.byKey(badge), findsNothing);
await tester.tap(controlByLabel('Log for later'));
await settle(tester);
await tester.tap(controlByLabel('Confirm'));
await settle(tester);
expect(tint(tester), gold);
expect(find.byKey(badge), findsOneWidget);
final dates = find.textContaining(RegExp(r'^\d{4}-\d{2}-\d{2}$'));
expect(dates, findsNothing, reason: 'no painted date');
await tester.tap(controlByLabel('Back to today'));
await settle(tester);
expect(find.byKey(badge), findsNothing);
});
});
});
}

View File

@ -68,7 +68,7 @@ void main() {
await settle(tester); await settle(tester);
final tomorrowKey = localDateKey(tomorrow()); final tomorrowKey = localDateKey(tomorrow());
expect(find.text(tomorrowKey), findsOneWidget); expect(byIconLabel('Change date'), findsOneWidget);
final firstSlot = daySlots(MealScheduleService.current).first; final firstSlot = daySlots(MealScheduleService.current).first;
await tester.tap(find.text(slotLabel(firstSlot))); await tester.tap(find.text(slotLabel(firstSlot)));
@ -91,7 +91,7 @@ void main() {
expect(future.time.startsWith(tomorrowKey), isTrue); expect(future.time.startsWith(tomorrowKey), isTrue);
// Back to logging for today. // Back to logging for today.
expect(find.text(tomorrowKey), findsNothing); expect(byIconLabel('Change date'), findsNothing);
expect(controlByLabel('Log for later'), findsOneWidget); expect(controlByLabel('Log for later'), findsOneWidget);
}); });
}, },
@ -133,12 +133,12 @@ void main() {
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Confirm')); await tester.tap(controlByLabel('Confirm'));
await settle(tester); await settle(tester);
expect(find.text(localDateKey(tomorrow())), findsOneWidget); expect(byIconLabel('Change date'), findsOneWidget);
await tester.tap(controlByLabel('Back to today')); await tester.tap(controlByLabel('Back to today'));
await settle(tester); await settle(tester);
expect(find.text(localDateKey(tomorrow())), findsNothing); expect(byIconLabel('Change date'), findsNothing);
expect(controlByLabel('Log for later'), findsOneWidget); expect(controlByLabel('Log for later'), findsOneWidget);
}); });
}); });

View File

@ -4,6 +4,8 @@ library;
import 'dart:io'; import 'dart:io';
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart'; import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
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/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/document_store_io.dart'; import 'package:diet_guard_app/services/document_store_io.dart';
@ -51,3 +53,28 @@ Future<void> settle(WidgetTester tester) async {
await Future<void>.delayed(const Duration(milliseconds: 200)); await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
/// Waits for the screen's open-or-resume chain (sync, slots, catering
/// auto-log) to finish, then [settle]s.
Future<void> settleOpen(WidgetTester tester) async {
final state = tester.state(find.byType(LogMealScreen));
await (state as LogMealLoggedMixin).openChain;
await settle(tester);
}
/// [settle]s, then keeps pumping until [done] holds or [timeout] passes.
///
/// For chains a tap starts and nothing exposes: real file I/O outlasts the
/// fixed sleep in [settle] when the machine is loaded.
Future<void> settleUntil(
WidgetTester tester,
Future<bool> Function() done, {
Duration timeout = const Duration(seconds: 5),
}) async {
final deadline = DateTime.now().add(timeout);
await settle(tester);
while (!await done() && DateTime.now().isBefore(deadline)) {
await Future<void>.delayed(const Duration(milliseconds: 50));
await tester.pumpAndSettle();
}
}

View File

@ -10,6 +10,7 @@ import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/foodbank_service.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/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:kuhy_credit/kuhy_credit.dart';
import 'package:material_ui/material_ui.dart'; import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
@ -224,4 +225,17 @@ void main() {
}); });
}, },
); );
testWidgets('shows the KuhyCredit logo at the bottom', (tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);
// Scroll to the bottom where KuhyCredit is placed.
await tester.ensureVisible(find.byType(KuhyCredit, skipOffstage: false));
await tester.pumpAndSettle();
expect(find.byType(KuhyCredit, skipOffstage: false), findsOneWidget);
});
});
} }

View File

@ -0,0 +1,123 @@
// The auto-log keeps the day's delivery on disk: offline first.
//
// A restart, or the caterer's panel being down, must not cost the dishes
// already fetched today. These tests pass an in-memory store as the disk.
import 'dart:convert';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:flutter_test/flutter_test.dart';
import '../kuchnia_fill_support.dart';
KuchniaDish _dish(int n) => KuchniaDish(
name: 'D$n',
kcal: 100.0 * n,
proteinG: 10,
carbsG: 20,
fatG: 5,
grams: 300,
priority: n,
slotLabel: 'Obiad',
dishId: '${1000 + n}',
);
/// A disk that is full: every write fails.
class _FullStore implements DocumentStore {
@override
Future<String?> read(String name) async => null;
@override
Future<void> write(String name, String contents) async =>
throw Exception('disk');
}
void main() {
late int fetches;
late DateTime clock;
setUp(() {
freshStorage();
fetches = 0;
final today = DateTime.now();
clock = DateTime(today.year, today.month, today.day, 13);
});
KuchniaAutoLog autoLog(DocumentStore store, KuchniaRefresh result) =>
KuchniaAutoLog(
store: store,
fetch: (day) async {
fetches++;
return result;
},
now: () => clock,
);
const down = KuchniaRefresh(reason: 'down');
final delivered = KuchniaRefresh(dishes: [_dish(1), _dish(2)]);
test('a restart with the panel down still logs the stored dish', () async {
final store = MemoryStore();
await autoLog(store, delivered).logDue([960]);
expect(fetches, 1);
final written = await autoLog(store, down).logDue([480]);
expect(fetches, 1, reason: 'the stored delivery answers, no refetch');
expect(written.map((e) => e.desc), ['D1']);
});
test('a stored delivery of another day is ignored', () async {
final store = MemoryStore();
store.documents[KuchniaAutoLog.documentName] = jsonEncode({
'day': '1999-01-01',
'dishes': [_dish(1).toJson()],
});
expect(await autoLog(store, down).logDue([480]), isEmpty);
expect(fetches, 1);
});
test('a malformed stored document is ignored', () async {
final store = MemoryStore();
for (final raw in [
'not json',
'[]',
jsonEncode({'day': localDateKey(clock), 'dishes': 'x'}),
jsonEncode({
'day': localDateKey(clock),
'dishes': [
{'name': 'D1'},
],
}),
]) {
store.documents[KuchniaAutoLog.documentName] = raw;
expect(await autoLog(store, down).logDue([480]), isEmpty, reason: raw);
}
expect(fetches, 4);
});
test('non-map items in a stored delivery are skipped', () async {
final store = MemoryStore();
store.documents[KuchniaAutoLog.documentName] = jsonEncode({
'day': localDateKey(clock),
'dishes': [1, _dish(1).toJson()],
});
final written = await autoLog(store, down).logDue([480]);
expect(written.map((e) => e.desc), ['D1']);
expect(fetches, 0);
});
test('a failing disk does not break logging', () async {
final written = await autoLog(_FullStore(), delivered).logDue([480]);
expect(written.map((e) => e.desc), ['D1']);
});
test('toJson and fromJson round-trip every field', () {
final dish = _dish(3);
final back = KuchniaDish.fromJson(dish.toJson());
expect(back.toJson(), dish.toJson());
final noId = Map<String, Object?>.of(dish.toJson())..remove('dish_id');
expect(KuchniaDish.fromJson(noId).dishId, '');
});
}

View File

@ -0,0 +1,58 @@
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show AppErrors, AppErrorsConfig, ErrorQueue;
import 'package:diet_guard_app/services/sync_attempt.dart';
import 'package:diet_guard_app/services/sync_health.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _config = AppErrorsConfig(
app: 'diet-guard',
repo: 'kuhyx/diet-guard',
package: 'diet_guard_app',
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late ErrorQueue queue;
setUp(() async {
SharedPreferences.setMockInitialValues({});
queue = await ErrorQueue.open(await SharedPreferences.getInstance());
AppErrors.instance = AppErrors.forTest(_config, queue);
});
tearDown(() => AppErrors.instance = null);
test('a sync that lands records success and reports nothing', () async {
expect(await attemptSync(() async {}), isTrue);
final status = await SyncHealth.read();
expect(status.lastSuccess, isNotNull);
expect(status.failureKind, isNull);
expect(queue.entries, isEmpty);
});
test('a failed sync records the failure and files its cause', () async {
final ok = await attemptSync(() async => throw StateError('locked'));
expect(ok, isFalse);
final status = await SyncHealth.read();
expect(status.failureKind, SyncFailureKind.failed);
final entry = queue.entries.single;
expect(entry.kind, 'sync.failed');
expect(entry.error, contains('locked'));
});
test('without installed reporting a failure is still recorded', () async {
AppErrors.instance = null;
expect(await attemptSync(() async => throw StateError('x')), isFalse);
expect((await SyncHealth.read()).failureKind, SyncFailureKind.failed);
});
test('a later success clears the failure (the banner goes away)', () async {
await attemptSync(() async => throw StateError('offline'));
await attemptSync(() async {});
final status = await SyncHealth.read();
expect(status.failureKind, isNull);
expect(status.message, isNull);
});
}

View File

@ -18,7 +18,6 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons --> <!-- iOS meta tags & icons -->
<meta name="mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes">

View File

@ -5,7 +5,6 @@
"display": "standalone", "display": "standalone",
"background_color": "#0175C2", "background_color": "#0175C2",
"theme_color": "#0175C2", "theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary", "orientation": "portrait-primary",
"prefer_related_applications": false, "prefer_related_applications": false,
"icons": [ "icons": [

View File

@ -2,10 +2,4 @@
# entries are predicates: they clear themselves when the blocker moves, so # entries are predicates: they clear themselves when the blocker moves, so
# they carry no `expires`; everything else is discretionary and expires. # they carry no `expires`; everything else is discretionary and expires.
exceptions: exceptions: []
- ecosystem: toolchain
package: flutter
pinned: "3.47.9"
reason: local toolchain /opt/flutter is 3.47.9; fleet-wide Flutter 3.50 bump is separate work
blocked_by: local-toolchain
expires: "2026-11-26"

View File

@ -6,12 +6,10 @@ Examples:
python -m diet_guard ate "two slices of pizza" --grams 240 python -m diet_guard ate "two slices of pizza" --grams 240
python -m diet_guard ate "protein shake" --kcal 180 python -m diet_guard ate "protein shake" --kcal 180
python -m diet_guard status python -m diet_guard status
python -m diet_guard averages
python -m diet_guard undo python -m diet_guard undo
The daily budget lives outside the repo (so it is never exposed online) but is ``status`` and each log print the calories left of the day's budget (kept
shown freely on this machine: ``status`` and each log print how many calories outside the repo) and which meal slots still need logging.
are left of the day's budget, plus which meal slots still need logging.
""" """
from __future__ import annotations from __future__ import annotations
@ -19,6 +17,7 @@ from __future__ import annotations
import sys import sys
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from diet_guard import _errors
from diet_guard._budget import ( from diet_guard._budget import (
BudgetFileCorruptError, BudgetFileCorruptError,
BudgetNotInitializedError, BudgetNotInitializedError,
@ -247,4 +246,5 @@ def main(argv: list[str] | None = None) -> int:
A process exit code (0 on success). A process exit code (0 on success).
""" """
args = parse_args(sys.argv[1:] if argv is None else argv) args = parse_args(sys.argv[1:] if argv is None else argv)
_errors.install()
return _COMMANDS[args.command](args) return _COMMANDS[args.command](args)

View File

@ -3,6 +3,12 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import Final
RANK_DIET_GUARD: Final = 130
"""gatelock arbitration rank: after the tutor (150), before focus-guard (128)
and LeetCode (125) (``DOCS-lock-order.md``, kuhy 2026-11-21). A literal, not
``gatelock.RANK_DIET_GUARD`` (100), so no gatelock release is needed."""
# --- Daily target ----------------------------------------------------------- # --- Daily target -----------------------------------------------------------
# There is deliberately NO budget number here. It is computed once from # There is deliberately NO budget number here. It is computed once from
@ -165,6 +171,10 @@ KUCHNIA_SYNCED_CREDENTIAL_FILE: Path = (
KUCHNIA_LAST_IMPORT_FILE: Path = ( KUCHNIA_LAST_IMPORT_FILE: Path = (
Path.home() / ".config" / "diet_guard" / "kuchnia_last_import" Path.home() / ".config" / "diet_guard" / "kuchnia_last_import"
) )
# The last successfully-fetched delivery, so a panel outage can fall back to
# it instead of a blank import. Under DATA_DIR, not ~/.config: it is a cache,
# regenerable on the next successful fetch.
KUCHNIA_DELIVERY_CACHE_FILE: Path = DATA_DIR / "kuchnia_delivery.json"
KUCHNIA_TIMEOUT_SECONDS: float = 8.0 KUCHNIA_TIMEOUT_SECONDS: float = 8.0
# Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request # Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request
# timeout alone would permit ~32s against a slow provider. # timeout alone would permit ~32s against a slow provider.

45
diet_guard/_errors.py Normal file
View File

@ -0,0 +1,45 @@
"""Error and slow-wait reporting for the diet gate (utils DOCS-app-errors.md).
``install`` runs once from the CLI entry point: uncaught, thread and Tk
callback errors, and a Tk loop frozen over 1 s, go to the app-errors spool,
from which the PC's ingest files a board ticket. Only the CLI installs it, so
tests that build a gate window never touch the real spool. The Flutter app
reports separately, as ``diet-guard``.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from gatelock import error_report
from gatelock.error_report import watch_stalls
if TYPE_CHECKING:
import tkinter as tk
APP = "diet-guard-gate"
REPO = "kuhyx/diet-guard"
@dataclass
class _Slot:
"""Holds the process's reporter once installed."""
reporter: error_report.Reporter | None = None
#: The installed reporter (``SLOT.reporter``); None until ``install``.
SLOT = _Slot()
def install() -> error_report.Reporter:
"""Hook this process's errors once; return the reporter."""
SLOT.reporter = error_report.install(APP, REPO)
return SLOT.reporter
def watch(root: tk.Misc) -> None:
"""Report ``root``'s freezes over 1 s, once ``install`` has run."""
if SLOT.reporter is not None:
watch_stalls(root, SLOT.reporter)

View File

@ -34,7 +34,6 @@ Building ``MealGate`` spans several sibling modules (the 250-line limit):
:mod:`._gatelock_mealflow` the submit/log flow, dashboard, callback errors and :mod:`._gatelock_mealflow` the submit/log flow, dashboard, callback errors and
pull-it-in buttons (``_GateMealFlow`` + ``_PullFlows``); :mod:`._gatelock_calendar` pull-it-in buttons (``_GateMealFlow`` + ``_PullFlows``); :mod:`._gatelock_calendar`
the tab -- calendar, streaks, YTD tally (:mod:`._daystatus`), budget editing. the tab -- calendar, streaks, YTD tally (:mod:`._daystatus`), budget editing.
``MealGate`` wires these together and owns the ``gatelock.LockWindow``.
""" """
from __future__ import annotations from __future__ import annotations
@ -43,7 +42,6 @@ import sys
import tkinter as tk import tkinter as tk
from gatelock import ( from gatelock import (
RANK_DIET_GUARD,
Arbiter, Arbiter,
GateRoot, GateRoot,
LockConfig, LockConfig,
@ -52,12 +50,15 @@ from gatelock import (
wait_for_turn, wait_for_turn,
) )
from diet_guard import _errors
from diet_guard._constants import RANK_DIET_GUARD
from diet_guard._gate import due_slots from diet_guard._gate import due_slots
from diet_guard._gatelock_calendar import _GateCalendar, make_calendar_vars from diet_guard._gatelock_calendar import _GateCalendar, make_calendar_vars
from diet_guard._gatelock_core import _GateState from diet_guard._gatelock_core import _GateState
from diet_guard._gatelock_credit import arm_credit_watch from diet_guard._gatelock_credit import arm_credit_watch
from diet_guard._gatelock_groups import GateWidgetsGroup from diet_guard._gatelock_groups import GateWidgetsGroup
from diet_guard._gatelock_lockfile import acquire_gate_lock, release_gate_lock from diet_guard._gatelock_lockfile import acquire_gate_lock, release_gate_lock
from diet_guard._gatelock_logo import place_logo
from diet_guard._gatelock_peerpull import arm_peer_pull from diet_guard._gatelock_peerpull import arm_peer_pull
from diet_guard._gatelock_ui import GateCallbacks, make_vars from diet_guard._gatelock_ui import GateCallbacks, make_vars
from diet_guard._hold import watch_hold from diet_guard._hold import watch_hold
@ -127,8 +128,7 @@ class MealGate(_GateCalendar):
self.root = GateRoot() self.root = GateRoot()
self.root.on_callback_error = self.on_callback_error self.root.on_callback_error = self.on_callback_error
self.root.title("Diet Gate") # OS-level app name: the one kept noun self.root.title("Diet Gate") # OS-level app name: the one kept noun
# No colour overrides: LockConfig's defaults are the design-system palette # No colour overrides: LockConfig defaults are the palette (one drifted).
# and _gatelock_ui reads them too (an override drifted once).
config = LockConfig( config = LockConfig(
mode="soft" if demo_mode else "hard", mode="soft" if demo_mode else "hard",
app_name="diet_guard", app_name="diet_guard",
@ -172,9 +172,9 @@ class MealGate(_GateCalendar):
monitor the user is actually looking at. monitor the user is actually looking at.
""" """
widgets = self._build_tabs(parent, self._callbacks) widgets = self._build_tabs(parent, self._callbacks)
place_logo(parent)
self._widgets.add(widgets, surface.output_name) self._widgets.add(widgets, surface.output_name)
# An output coming back mid-lock gets its bindings too; tk's bind # A returning output gets its bindings; re-wiring the rest is a no-op.
# replaces rather than stacks, so re-wiring the others is a no-op.
self._wire_events() self._wire_events()
def teardown_surface(self, surface: SurfaceInfo) -> None: def teardown_surface(self, surface: SurfaceInfo) -> None:
@ -215,6 +215,7 @@ class MealGate(_GateCalendar):
def run(self) -> None: def run(self) -> None:
"""Run the Tk loop (a hold or a meal logged elsewhere closes it), VT-safe.""" """Run the Tk loop (a hold or a meal logged elsewhere closes it), VT-safe."""
watch_hold(self.root, self.close) watch_hold(self.root, self.close)
_errors.watch(self.root) # here, not at build: the turn wait is no stall
if not self.demo_mode: # a demo owes a synthetic slot: it would self-close if not self.demo_mode: # a demo owes a synthetic slot: it would self-close
arm_credit_watch( arm_credit_watch(
self.root, lambda: self._pending, self._reconcile_after_fetch self.root, lambda: self._pending, self._reconcile_after_fetch

View File

@ -0,0 +1,27 @@
"""The kuhy logo in a corner of each gate surface (shared ``kuhy_credit``).
Uses the Tk widget from kuhy_credit (kuhy-credit-v0.3.0). A click opens the
credit panel; the site opens only on a further click, so the lock cannot be
escaped by accident. This module imports tkinter and builds widgets, so it
belongs in ``_GATE_TK_MODULES`` (see ``_gatelock_layout``).
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from kuhy_credit.tk import KuhyCredit
if TYPE_CHECKING:
import tkinter as tk
__all__ = ["place_logo"]
_MARGIN = 16
def place_logo(parent: tk.Misc) -> KuhyCredit:
"""Overlay the logo on ``parent``'s bottom-right corner."""
credit = KuhyCredit(parent, theme="dark")
credit.place(relx=1, rely=1, x=-_MARGIN, y=-_MARGIN, anchor="se")
return credit

View File

@ -0,0 +1,112 @@
"""Off-thread plumbing for the lock screen's food lookup.
The lookup used to run on the Tk thread. A food missing from the bank falls
through to an Open Food Facts request (8 s timeout), so the fullscreen lock
froze while it ran: a 1.5 s ``tk.mainloop`` stall was reported (c890f31a).
Same rules as :mod:`._gatelock_fetch`: the worker touches no widget and never
calls ``after`` (Tcl is not thread-safe); it only ``put``s its result on a
queue, and a poll scheduled on the Tk thread picks it up.
"""
from __future__ import annotations
import logging
import queue
import threading
from typing import TYPE_CHECKING
from diet_guard._gatelock_fetch import FETCH_POLL_MS
from diet_guard._resolve import lookup_candidates
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Callable
from tkinter import Misc
from diet_guard._estimator import Nutrition
Candidates = list[tuple[str, Nutrition]]
__all__ = ["LookupRunner", "start_lookup"]
_logger = logging.getLogger(__name__)
def start_lookup(
lookup: Callable[[str], Candidates],
description: str,
) -> queue.Queue[Candidates]:
"""Run ``lookup(description)`` on a daemon thread; return the result queue.
Daemon so a hung request can never keep the process alive after the window
is gone -- the gate is a ``Type=oneshot`` unit and must exit.
"""
result: queue.Queue[Candidates] = queue.Queue(maxsize=1)
def _worker() -> None:
"""Runs OFF the Tk thread. Touches no widget, by construction."""
candidates: Candidates = []
try:
candidates = lookup(description)
# An unreadable bank or a malformed OFF payload; network errors are
# already caught inside ``off_candidates``.
except OSError, ValueError, KeyError, TypeError:
_logger.exception("food lookup failed")
finally:
# Always feed the queue, so the poll never waits forever and the
# form never stays busy. An empty result asks for a manual kcal.
result.put(candidates)
threading.Thread(target=_worker, daemon=True).start()
return result
class LookupRunner:
"""One food lookup at a time, collected on the Tk thread.
The window stays live while a lookup runs, so the user can log the meal by
hand and move on. A result for a food no longer in the description box is
dropped: applied late, it would fill the next slot with the wrong macros.
"""
def __init__(
self,
root: Misc,
on_result: Callable[[Candidates], None],
current: Callable[[], str],
) -> None:
"""Bind the runner to the Tk root, the result handler and the live text.
Args:
root: The gate's Tk root (schedules the poll).
on_result: Fills the form from the candidates, on the Tk thread.
current: Returns the description box's text right now.
"""
self._root = root
self._on_result = on_result
self._current = current
self._result: queue.Queue[Candidates] | None = None
self._description = ""
def start(self, description: str) -> bool:
"""Start a lookup; return False, starting nothing, if one is running."""
if self._result is not None:
return False
self._result = start_lookup(lookup_candidates, description)
self._description = description
self._root.after(FETCH_POLL_MS, self.poll)
return True
def poll(self) -> None:
"""On the Tk thread: hand a finished result over, else poll again."""
result = self._result
if result is None:
return
try:
candidates = result.get_nowait()
except queue.Empty:
self._root.after(FETCH_POLL_MS, self.poll)
return
self._result = None
if self._current() == self._description:
self._on_result(candidates)

View File

@ -18,8 +18,8 @@ from diet_guard._budget_derived import protein_target_g
from diet_guard._foodbank import remember_food from diet_guard._foodbank import remember_food
from diet_guard._gatelock_delivery import _PullFlows from diet_guard._gatelock_delivery import _PullFlows
from diet_guard._gatelock_fillall import RECONCILE_LABELS, FillAllFlow, FillHooks from diet_guard._gatelock_fillall import RECONCILE_LABELS, FillAllFlow, FillHooks
from diet_guard._gatelock_lookup import LookupRunner
from diet_guard._gatelock_ui import ERR, FG, UNIT_GRAMS from diet_guard._gatelock_ui import ERR, FG, UNIT_GRAMS
from diet_guard._resolve import lookup_candidates
from diet_guard._slots import slot_label from diet_guard._slots import slot_label
from diet_guard._state import entry_kcal, log_meal from diet_guard._state import entry_kcal, log_meal
from diet_guard._state_today import ( from diet_guard._state_today import (
@ -45,6 +45,9 @@ _DASH_DESC_WIDTH = 22
class _GateMealFlow(_PullFlows): class _GateMealFlow(_PullFlows):
"""Submit/lookup/log flow for a logged food.""" """Submit/lookup/log flow for a logged food."""
#: The off-thread food lookup, made on first use (it needs ``root``).
_lookup: LookupRunner | None = None
# -- slot walk ------------------------------------------------------------ # -- slot walk ------------------------------------------------------------
def _clear_inputs(self) -> None: def _clear_inputs(self) -> None:
@ -111,16 +114,19 @@ class _GateMealFlow(_PullFlows):
self._record(description, nutrition) self._record(description, nutrition)
def _begin_lookup(self, description: str) -> None: def _begin_lookup(self, description: str) -> None:
"""Step 1: look the food up, fill the label fields, offer alternatives. """Step 1: look the food up off the Tk thread; fill the form on return.
Nothing is logged here -- the user must see and confirm the filled Nothing is logged here -- the user must see and confirm the filled
values (a second submit) before they are recorded. The food is looked values (a second submit) before they are recorded. A second submit
up at its natural basis (per 100 g / serving); the amount eaten scales while a lookup runs is ignored.
it, so the lookup never bakes in a portion.
""" """
if self._lookup is None:
self._lookup = LookupRunner(self.root, self._finish_lookup, self._get_desc)
if self._lookup.start(description):
self._set_status(g.BUSY) self._set_status(g.BUSY)
self.root.update_idletasks()
candidates = lookup_candidates(description) def _finish_lookup(self, candidates: list[tuple[str, Nutrition]]) -> None:
"""Fill the label fields and offer alternatives, or ask for kcal."""
if not candidates: if not candidates:
# Not found: the kcal field takes focus, the cue names it. # Not found: the kcal field takes focus, the cue names it.
self._set_status(f"{g.ERROR} {g.source_glyph('')} kcal", error=True) self._set_status(f"{g.ERROR} {g.source_glyph('')} kcal", error=True)

View File

@ -52,9 +52,14 @@ _logger = logging.getLogger(__name__)
FETCH_TIMEOUT_S = 5.0 FETCH_TIMEOUT_S = 5.0
#: Names served lazily by ``__getattr__`` (read statically by
#: scripts/check_patch_targets.py when the catering client cannot import).
_LAZY_ATTRS = ("refresh_delivery",)
def __getattr__(name: str) -> object: def __getattr__(name: str) -> object:
"""Resolve the deferred catering import on first attribute access.""" """Resolve the deferred catering import on first attribute access."""
if name != "refresh_delivery": if name not in _LAZY_ATTRS:
msg = f"module {__name__!r} has no attribute {name!r}" msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg) raise AttributeError(msg)
return import_module("diet_guard._kuchnia_import").refresh_delivery return import_module("diet_guard._kuchnia_import").refresh_delivery

View File

@ -0,0 +1,85 @@
"""A local cache of the last successfully-fetched Kuchnia delivery.
Offline first: the panel is a third party that goes down, and a day's
delivery, once fetched, must stay usable without it. This module owns that
cache: :func:`save_delivery` after a successful fetch, :func:`load_delivery`
when the panel fails or the day was already fetched.
Every failure mode is "no cache": a missing file, bad JSON, another day's
delivery, or a half-written record all mean "fetch again", which is always
safe. The phone keeps the same file (``KuchniaAutoLog.store``).
"""
from __future__ import annotations
import dataclasses
import json
import logging
from typing import TYPE_CHECKING
from diet_guard import _constants
from diet_guard._kuchnia_parse import Dish
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Sequence
from datetime import date
_LOGGER = logging.getLogger(__name__)
def load_delivery(day: date) -> list[Dish]:
"""Return the dishes cached for ``day``'s delivery, or ``[]``.
Any unreadable, malformed or foreign-day cache is treated as "no cache"
rather than an error: the caller falls back to the panel fetch, which is
strictly better than a stale import.
"""
path = _constants.KUCHNIA_DELIVERY_CACHE_FILE
try:
if not path.exists():
return []
raw = path.read_text()
except OSError:
return []
try:
data = json.loads(raw)
except json.JSONDecodeError:
return []
if not isinstance(data, dict) or data.get("day") != day.isoformat():
return []
dishes = data.get("dishes")
if not isinstance(dishes, list):
return []
out: list[Dish] = []
for item in dishes:
if not isinstance(item, dict):
continue
try:
out.append(Dish(**item))
except TypeError:
continue
return out
def save_delivery(day: date, dishes: Sequence[Dish]) -> None:
"""Persist ``day``'s delivery so a later outage can still import it.
Best-effort: a write failure only costs the fallback, so it is logged
and swallowed, never raised into the import path. The write goes to a
sibling ``.tmp`` and is atomically renamed, so a half-written file can
never poison :func:`load_delivery`.
"""
path = _constants.KUCHNIA_DELIVERY_CACHE_FILE
payload = json.dumps(
{
"day": day.isoformat(),
"dishes": [dataclasses.asdict(d) for d in dishes],
}
)
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(payload)
tmp.replace(path)
except OSError:
_LOGGER.warning("could not save the kitchen delivery cache")

View File

@ -24,6 +24,7 @@ from typing import TYPE_CHECKING
from diet_guard._foodbank_manual import add_manual_entry, read_manual_bank from diet_guard._foodbank_manual import add_manual_entry, read_manual_bank
from diet_guard._kuchnia_client import PanelSession from diet_guard._kuchnia_client import PanelSession
from diet_guard._kuchnia_config import last_import_day, record_import_day from diet_guard._kuchnia_config import last_import_day, record_import_day
from diet_guard._kuchnia_delivery_cache import load_delivery, save_delivery
from diet_guard._kuchnia_errors import KuchniaError from diet_guard._kuchnia_errors import KuchniaError
from diet_guard._kuchnia_orders import fetch_dishes from diet_guard._kuchnia_orders import fetch_dishes
@ -90,16 +91,22 @@ def refresh_delivery(day: date) -> tuple[list[Dish], str | None]:
day: The delivery date to fetch. day: The delivery date to fetch.
Returns: Returns:
``(dishes, None)`` on success, or ``([], reason)`` when the catering ``(dishes, None)`` on success. On a panel outage, the cached
panel could not be read. Callers surface the reason and carry on. delivery for ``day`` when one exists ``(cached, None)``, otherwise
``([], reason)`` with the failure reason so callers can surface it
and carry on.
""" """
try: try:
session = PanelSession() session = PanelSession()
session.authenticate() session.authenticate()
dishes = fetch_dishes(session, day) dishes = fetch_dishes(session, day)
except KuchniaError as exc: except KuchniaError as exc:
if cached := load_delivery(day):
return cached, None
return [], str(exc) return [], str(exc)
bank_dishes(dishes) bank_dishes(dishes)
if dishes:
save_delivery(day, dishes)
return dishes, None return dishes, None
@ -123,12 +130,13 @@ def refresh_delivery_once(day: date) -> tuple[list[Dish], str | None]:
day: The delivery date to fetch. day: The delivery date to fetch.
Returns: Returns:
``([], None)`` when today was already fetched -- "nothing new", not an ``(cached, None)`` when today was already fetched -- ``cached`` is the
saved delivery for the day (possibly empty), "nothing new", not an
error. Otherwise whatever :func:`refresh_delivery` returns. error. Otherwise whatever :func:`refresh_delivery` returns.
""" """
stamp = day.isoformat() stamp = day.isoformat()
if last_import_day() == stamp: if last_import_day() == stamp:
return [], None return load_delivery(day), None
dishes, reason = refresh_delivery(day) dishes, reason = refresh_delivery(day)
if reason is None and dishes: if reason is None and dishes:
# Only a fetch that found dishes counts: an outage, or a walk that # Only a fetch that found dishes counts: an outage, or a walk that

View File

@ -202,6 +202,8 @@ def fake_tk() -> Iterator[None]:
with ExitStack() as stack: with ExitStack() as stack:
for module in _GATE_TK_MODULES: for module in _GATE_TK_MODULES:
stack.enter_context(patch.object(module, "tk", _FAKE_TK)) stack.enter_context(patch.object(module, "tk", _FAKE_TK))
# The logo is a real Canvas subclass; it cannot take a fake parent.
stack.enter_context(patch.object(_gatelock, "place_logo"))
stack.enter_context(patch.object(_gatelock_calendar, "ttk", _FAKE_TTK)) stack.enter_context(patch.object(_gatelock_calendar, "ttk", _FAKE_TTK))
stack.enter_context(patch.object(_gatelock_calendar_ui, "ttk", _FAKE_TTK)) stack.enter_context(patch.object(_gatelock_calendar_ui, "ttk", _FAKE_TTK))
# The schedule row's HH:MM spinboxes are ttk widgets; left real, they # The schedule row's HH:MM spinboxes are ttk widgets; left real, they

View File

@ -151,6 +151,12 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE", "diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE",
tmp_path / "kuchnia_last_import", tmp_path / "kuchnia_last_import",
), ),
# The outage fallback cache: without this a refresh_delivery test that
# saves one lands in the real DATA_DIR.
patch(
"diet_guard._constants.KUCHNIA_DELIVERY_CACHE_FILE",
tmp_path / "kuchnia_delivery.json",
),
# The catering fetch is a third network entry point. Patched at each # The catering fetch is a third network entry point. Patched at each
# call site, so a test importing `refresh_delivery` directly still # call site, so a test importing `refresh_delivery` directly still
# exercises the real helper. # exercises the real helper.

View File

@ -27,6 +27,7 @@ from unittest.mock import patch
import pytest import pytest
from diet_guard import _errors
from diet_guard._estimator import Nutrition from diet_guard._estimator import Nutrition
# Importing these fixtures IS their registration: pytest discovers fixtures # Importing these fixtures IS their registration: pytest discovers fixtures
@ -113,6 +114,15 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]:
stack.enter_context( stack.enter_context(
patch.dict(os.environ, {"HOLDS_DATA": str(tmp_path / "holds.json")}) patch.dict(os.environ, {"HOLDS_DATA": str(tmp_path / "holds.json")})
) )
# gatelock hooks a process once; a reporter already in INSTALLED makes
# install() return it untouched, so no hook is set and every report
# lands in this test's folder, never the real app-errors spool.
spool = tmp_path / "app-errors-spool"
rep = _errors.error_report.Reporter(_errors.APP, _errors.REPO, spool=spool)
stack.enter_context(
patch.object(_errors.error_report.INSTALLED, "reporter", rep)
)
stack.enter_context(patch.object(_errors.SLOT, "reporter", None))
yield yield

View File

@ -0,0 +1,103 @@
"""CLI contract of ``scripts/check_patch_targets.py``: the package is an argument.
Other guard repos adopt the script by copying it into their own ``scripts/``,
so each case copies it into a scratch repo next to a scratch package and runs
it there as a subprocess -- the same shape an adopter gets. ``scripts/`` sits
outside coverage ``source``, so the subprocess run is the whole check.
"""
from __future__ import annotations
from pathlib import Path
import shutil
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "scripts" / "check_patch_targets.py"
GOOD = 'from unittest import mock\nmock.patch("pkg_a.mod.VALUE", 1)\n'
STALE = 'from unittest import mock\nmock.patch("pkg_a.mod.GONE", 1)\n'
def _run(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
"""Run the script with ``args`` from ``cwd``, as the pre-commit hook does."""
return subprocess.run(
[sys.executable, str(cwd / "scripts" / SCRIPT.name), *args],
cwd=cwd,
capture_output=True,
text=True,
check=False,
timeout=30,
)
def _scratch_repo(tmp_path: Path, test_source: str, tests_dir: str) -> Path:
"""A repo with ``scripts/``, package ``pkg_a`` and one test file."""
(tmp_path / "scripts").mkdir()
shutil.copy(SCRIPT, tmp_path / "scripts" / SCRIPT.name)
pkg = tmp_path / "pkg_a"
pkg.mkdir()
(pkg / "__init__.py").write_text("")
(pkg / "mod.py").write_text("VALUE = 0\n")
tests = tmp_path / tests_dir
tests.mkdir(parents=True, exist_ok=True)
(tests / "test_x.py").write_text(test_source)
return tmp_path
def test_missing_package_argument_is_a_usage_error(tmp_path: Path) -> None:
"""No silent default: a bare run fails loudly instead of checking nothing."""
repo = _scratch_repo(tmp_path, GOOD, "pkg_a/tests")
result = _run(repo)
assert result.returncode == 2
assert "usage:" in result.stderr
assert "package" in result.stderr
def test_good_target_in_named_package_passes(tmp_path: Path) -> None:
"""A resolvable target in ``<package>/tests`` exits 0 silently."""
repo = _scratch_repo(tmp_path, GOOD, "pkg_a/tests")
result = _run(repo, "pkg_a")
assert (result.returncode, result.stderr) == (0, "")
def test_stale_target_in_named_package_fails(tmp_path: Path) -> None:
"""A target that no longer resolves names its file and line, and exits 1."""
repo = _scratch_repo(tmp_path, STALE, "pkg_a/tests")
result = _run(repo, "pkg_a")
assert result.returncode == 1
assert (
"pkg_a/tests/test_x.py:2: patch target does not resolve: pkg_a.mod.GONE"
in result.stderr
)
def test_tests_root_override_is_the_directory_checked(tmp_path: Path) -> None:
"""``--tests-root`` replaces ``<package>/tests``, which may then not exist."""
repo = _scratch_repo(tmp_path, STALE, "elsewhere")
assert _run(repo, "pkg_a").returncode == 1 # default root is missing
result = _run(repo, "pkg_a", "--tests-root", "elsewhere")
assert result.returncode == 1
assert "elsewhere/test_x.py:2:" in result.stderr
def test_real_tree_passes_with_diet_guard_argument() -> None:
"""The hook's own invocation is green on this repo."""
result = subprocess.run(
[sys.executable, str(SCRIPT), "diet_guard"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
timeout=60,
)
assert (result.returncode, result.stderr) == (0, "")
def test_sibling_prefix_package_is_not_checked(tmp_path: Path) -> None:
"""``pkg_a`` does not own ``pkg_ab``: a bare string prefix is not a package."""
other = 'from unittest import mock\nmock.patch("pkg_ab.mod.GONE", 1)\n'
repo = _scratch_repo(tmp_path, other, "pkg_a/tests")
result = _run(repo, "pkg_a")
assert (result.returncode, result.stderr) == (0, "")

View File

@ -0,0 +1,65 @@
"""The gate's error reporting: installed once by the CLI, into the shared spool."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from diet_guard import _cli, _errors, _gatelock
from diet_guard._gatelock import MealGate
from diet_guard.tests._gate_fixtures import fake_tk
if TYPE_CHECKING:
from pathlib import Path
import pytest
def test_install_keeps_the_reporter_and_writes_the_spool(tmp_path: Path) -> None:
"""The CLI's install names the gate app and its repo in every report."""
rep = _errors.install()
assert _errors.SLOT.reporter is rep
assert rep.app == "diet-guard-gate"
rep.report("uncaught.python", ValueError("deliberate"))
line = (tmp_path / "app-errors-spool" / "diet-guard-gate.jsonl").read_text()
entry = json.loads(line)
assert entry["repo"] == "kuhyx/diet-guard"
assert entry["error"] == "ValueError: deliberate"
def test_cli_main_installs_before_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
"""Every CLI run hooks errors, the gate's included."""
install = MagicMock()
monkeypatch.setattr(_errors, "install", install)
monkeypatch.setitem(_cli._COMMANDS, "status", lambda _args: 0)
assert _cli.main(["status"]) == 0
install.assert_called_once_with()
def _run(gate: MealGate) -> None:
"""Run the gate's start-up with its Tk loop stubbed out."""
with (
patch.object(gate, "_lock", MagicMock()),
patch.object(_gatelock, "watch_hold"),
):
gate.run()
def test_gate_watches_stalls_once_installed(monkeypatch: pytest.MonkeyPatch) -> None:
"""A gate built after install reports its own freezes."""
reporter = MagicMock()
monkeypatch.setattr(_errors.SLOT, "reporter", reporter)
with patch.object(_errors, "watch_stalls") as watch, fake_tk():
gate = MealGate(demo_mode=True)
watch.assert_not_called() # the turn wait while building is no stall
_run(gate)
watch.assert_called_once_with(gate.root, reporter)
assert _gatelock._errors is _errors
def test_gate_skips_the_watch_without_a_reporter() -> None:
"""A gate built outside the CLI (tests, imports) never starts a watch."""
with patch.object(_errors, "watch_stalls") as watch, fake_tk():
_run(MealGate(demo_mode=True))
watch.assert_not_called()

View File

@ -0,0 +1,35 @@
"""The kuhy logo sits in the bottom-right corner of every gate surface."""
from __future__ import annotations
import os
import tkinter as tk
from typing import TYPE_CHECKING
from kuhy_credit.tk import KuhyCredit
import pytest
from diet_guard._gatelock_logo import place_logo
if TYPE_CHECKING:
from pytest_xvfb import Xvfb
def test_place_logo_anchors_bottom_right(xvfb: Xvfb | None) -> None:
# Real Tk, so only ever on pytest-xvfb's private display -- never the user's.
if xvfb is None:
pytest.skip("needs pytest-xvfb's private display")
assert os.environ["DISPLAY"] == f":{xvfb.display}"
root = tk.Tk()
try:
root.withdraw()
frame = tk.Frame(root)
credit = place_logo(frame)
assert isinstance(credit, KuhyCredit)
assert credit.master is frame
info = credit.place_info()
assert info["anchor"] == "se"
assert (info["relx"], info["rely"]) == ("1", "1")
assert (info["x"], info["y"]) == ("-16", "-16")
finally:
root.destroy()

View File

@ -0,0 +1,160 @@
"""Tests for the off-thread food lookup of MealGate.
Covers :mod:`._gatelock_lookup` (``start_lookup``, ``LookupRunner``) and the
two ``_GateMealFlow`` methods that use it. The functional fake ``tk`` widgets
and the ``gate`` fixture live in ``conftest.py``.
"""
from __future__ import annotations
import queue
import threading
import time
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from diet_guard import _gatelock_glyphs as g
from diet_guard import _gatelock_lookup
from diet_guard._gatelock_fetch import FETCH_POLL_MS
from diet_guard._gatelock_lookup import LookupRunner, start_lookup
from diet_guard.tests.conftest import _nutrition
if TYPE_CHECKING:
import pytest
from diet_guard._estimator import Nutrition
from diet_guard._gatelock import MealGate
Candidates = list[tuple[str, Nutrition]]
def _failing_lookup(_desc: str) -> Candidates:
msg = "bad payload"
raise ValueError(msg)
class TestStartLookup:
"""The worker thread always feeds its queue."""
def test_puts_result(self) -> None:
"""A finished lookup's candidates land on the queue."""
found = [("apple", _nutrition(95, 100))]
assert start_lookup(lambda _d: found, "apple").get(timeout=5) == found
def test_failure_puts_empty_and_logs(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A failing lookup is logged and still answers, with no candidates."""
with caplog.at_level("ERROR"):
assert start_lookup(_failing_lookup, "x").get(timeout=5) == []
assert any("food lookup failed" in r.message for r in caplog.records)
class TestLookupRunner:
"""One lookup at a time, collected by a Tk-side poll."""
def test_start_schedules_poll(self) -> None:
"""Starting a lookup schedules the poll and reports it started."""
root = MagicMock()
runner = LookupRunner(root, MagicMock(), lambda: "apple")
with patch.object(_gatelock_lookup, "start_lookup", return_value=queue.Queue()):
assert runner.start("apple") is True
root.after.assert_called_once_with(FETCH_POLL_MS, runner.poll)
def test_second_start_while_running_is_ignored(self) -> None:
"""A second submit during a lookup starts nothing."""
runner = LookupRunner(MagicMock(), MagicMock(), lambda: "slow")
with patch.object(
_gatelock_lookup, "start_lookup", return_value=queue.Queue()
) as start:
runner.start("first")
assert runner.start("second") is False
start.assert_called_once()
def test_poll_reschedules_until_done(self) -> None:
"""An empty queue polls again; a result goes to the handler once."""
root, on_result = MagicMock(), MagicMock()
runner = LookupRunner(root, on_result, lambda: "apple")
pending: queue.Queue[Candidates] = queue.Queue()
with patch.object(_gatelock_lookup, "start_lookup", return_value=pending):
runner.start("apple")
runner.poll()
assert root.after.call_count == 2
on_result.assert_not_called()
pending.put([])
runner.poll()
on_result.assert_called_once_with([])
runner.poll() # nothing in flight any more: a stray poll is a no-op
assert root.after.call_count == 2
on_result.assert_called_once()
def test_start_does_not_wait_for_the_lookup(self) -> None:
"""The Tk thread returns at once while the lookup is still running."""
release = threading.Event()
def slow_lookup(desc: str) -> Candidates:
release.wait(5)
return [(desc, _nutrition())]
runner = LookupRunner(MagicMock(), MagicMock(), lambda: "slow")
began = time.perf_counter()
with patch.object(_gatelock_lookup, "lookup_candidates", slow_lookup):
runner.start("slow")
assert time.perf_counter() - began < 0.1
result = runner._result
assert result is not None
assert result.empty()
release.set()
assert result.get(timeout=5)[0][0] == "slow"
class TestGateLookup:
"""Step one of a submit: the gate fills the form from a lookup."""
def _lookup(self, gate: MealGate, found: Candidates) -> None:
"""Run ``_begin_lookup`` with a ready result, then collect it."""
ready: queue.Queue[Candidates] = queue.Queue()
ready.put(found)
gate._set_desc("apple")
with patch.object(_gatelock_lookup, "start_lookup", return_value=ready):
gate._begin_lookup("apple")
assert gate._vars.status.get() == g.BUSY
assert gate._lookup is not None
gate._lookup.poll()
def test_no_candidates(self, gate: MealGate) -> None:
"""No match asks for a manual value."""
self._lookup(gate, [])
assert gate._vars.status.get().startswith(g.ERROR)
def test_single_candidate(self, gate: MealGate) -> None:
"""A single match fills the fields and invites review."""
self._lookup(gate, [("apple", _nutrition(95, 100))])
assert gate._vars.status.get().startswith(g.OK)
assert g.TIMES not in gate._vars.status.get()
def test_multiple_candidates(self, gate: MealGate) -> None:
"""Several matches invite picking another."""
self._lookup(gate, [("a", _nutrition(95, 100)), ("b", _nutrition(120, 100))])
assert gate._vars.status.get().endswith(f" {g.TIMES}2")
def test_second_submit_keeps_busy_status(self, gate: MealGate) -> None:
"""A submit during a lookup neither restarts it nor touches the status."""
with patch.object(_gatelock_lookup, "start_lookup", return_value=queue.Queue()):
gate._begin_lookup("apple")
gate._set_status("other")
gate._begin_lookup("apple")
assert gate._vars.status.get() == "other"
def test_result_for_a_food_no_longer_typed_is_dropped(self, gate: MealGate) -> None:
"""A late result never fills the form for whatever the user moved on to."""
pending: queue.Queue[Candidates] = queue.Queue()
gate._set_desc("apple")
with patch.object(_gatelock_lookup, "start_lookup", return_value=pending):
gate._begin_lookup("apple")
gate._clear_inputs() # the meal was logged by hand; the form moved on
pending.put([("apple", _nutrition(95, 100))])
assert gate._lookup is not None
gate._lookup.poll()
assert gate._widgets.macros.kcal.get() == ""
assert gate._get_desc() == ""

View File

@ -1,8 +1,9 @@
"""Tests for the nutrition model, lookup, and meal-building flow of MealGate. """Tests for the nutrition model and meal-building flow of MealGate.
Covers :mod:`._gatelock_nutrition` (reference -> total maths, suggestions, Covers :mod:`._gatelock_nutrition` (reference -> total maths, suggestions,
unit toggling) and :mod:`._gatelock_mealflow` (submit/lookup/record, the unit toggling) and :mod:`._gatelock_mealflow` (submit/record, the
dashboard, and multi-item meals). The functional fake ``tk`` widgets and the dashboard, and multi-item meals). Lookup tests moved to
:mod:`test_gatelock_lookup`. The functional fake ``tk`` widgets and the
``gate`` fixture live in ``conftest.py`` and are shared with ``gate`` fixture live in ``conftest.py`` and are shared with
:mod:`test_gatelock`. :mod:`test_gatelock`.
""" """
@ -156,41 +157,6 @@ class TestSubmit:
submit.assert_called_once() submit.assert_called_once()
class TestLookup:
"""Step one: filling the form from a lookup."""
def test_no_candidates(self, gate: MealGate) -> None:
"""No match asks for a manual value."""
gate._set_desc("nonsense")
with patch.object(_gatelock_mealflow, "lookup_candidates", return_value=[]):
gate._begin_lookup("nonsense")
assert gate._vars.status.get().startswith(g.ERROR)
def test_single_candidate(self, gate: MealGate) -> None:
"""A single match fills the fields and invites review."""
with patch.object(
_gatelock_mealflow,
"lookup_candidates",
return_value=[("apple", _nutrition(95, 100))],
):
gate._begin_lookup("apple")
assert gate._vars.status.get().startswith(g.OK)
assert g.TIMES not in gate._vars.status.get()
def test_multiple_candidates(self, gate: MealGate) -> None:
"""Several matches invite picking another."""
with patch.object(
_gatelock_mealflow,
"lookup_candidates",
return_value=[
("a", _nutrition(95, 100)),
("b", _nutrition(120, 100)),
],
):
gate._begin_lookup("apple")
assert gate._vars.status.get().endswith(f"{g.TIMES}2")
class TestRecord: class TestRecord:
"""Logging a meal and advancing the slot walk.""" """Logging a meal and advancing the slot walk."""

View File

@ -0,0 +1,155 @@
"""The Kuchnia delivery cache: an outage falls back to the last fetched day.
Every on-disk write in these tests lands in the conftest-redirected tmp
state; the two ``pathlib`` patches below are the only fault injection.
"""
from __future__ import annotations
from contextlib import contextmanager
import dataclasses
from datetime import date
import json
from typing import TYPE_CHECKING
from unittest.mock import Mock, patch
from diet_guard import _constants
from diet_guard._kuchnia_config import record_import_day
from diet_guard._kuchnia_delivery_cache import load_delivery, save_delivery
from diet_guard._kuchnia_errors import KuchniaError
from diet_guard._kuchnia_import import refresh_delivery, refresh_delivery_once
from diet_guard._kuchnia_parse import Dish
if TYPE_CHECKING:
from collections.abc import Iterator
DAY = date(2026, 11, 27)
def _dish() -> Dish:
return Dish("Osobiste danie", 300.0, 10.0, 20.0, 2.0, 250.0, 1, "obiad")
def _write_cache(payload: object) -> None:
_constants.KUCHNIA_DELIVERY_CACHE_FILE.write_text(json.dumps(payload))
# --- load_delivery ----------------------------------------------------------
def test_save_then_load_round_trip() -> None:
save_delivery(DAY, [_dish()])
assert load_delivery(DAY) == [_dish()]
def test_load_missing_file() -> None:
assert load_delivery(DAY) == []
def test_load_wrong_day() -> None:
save_delivery(DAY, [_dish()])
assert load_delivery(date(2026, 11, 28)) == []
def test_load_malformed_json() -> None:
_constants.KUCHNIA_DELIVERY_CACHE_FILE.write_text("not json")
assert load_delivery(DAY) == []
def test_load_top_level_not_a_dict() -> None:
_write_cache([])
assert load_delivery(DAY) == []
def test_load_dishes_not_a_list() -> None:
_write_cache({"day": DAY.isoformat(), "dishes": "nope"})
assert load_delivery(DAY) == []
def test_load_skips_non_dict_items() -> None:
_write_cache(
{
"day": DAY.isoformat(),
"dishes": [42, dataclasses.asdict(_dish())],
}
)
assert load_delivery(DAY) == [_dish()]
def test_load_skips_unknown_key_items() -> None:
_write_cache(
{
"day": DAY.isoformat(),
"dishes": [{"bogus_key": 1}, dataclasses.asdict(_dish())],
}
)
assert load_delivery(DAY) == [_dish()]
def test_load_oserror_on_read() -> None:
save_delivery(DAY, [_dish()])
with patch("pathlib.Path.read_text", side_effect=OSError("io")):
assert load_delivery(DAY) == []
def test_save_oserror_on_write() -> None:
with patch("pathlib.Path.write_text", side_effect=OSError("io")):
save_delivery(DAY, [_dish()]) # must not raise
assert not _constants.KUCHNIA_DELIVERY_CACHE_FILE.exists()
# --- refresh_delivery -------------------------------------------------------
@contextmanager
def _patched_fetch(**mock_kwargs: object) -> Iterator[Mock]:
"""Patch the panel login and the dish walk; yield the ``fetch_dishes`` mock."""
with (
patch("diet_guard._kuchnia_import.PanelSession", return_value=Mock()),
patch("diet_guard._kuchnia_import.fetch_dishes", **mock_kwargs) as fetch,
):
yield fetch
def test_refresh_delivery_success_saves_cache() -> None:
with _patched_fetch(return_value=[_dish()]):
dishes, reason = refresh_delivery(DAY)
assert dishes == [_dish()]
assert reason is None
assert load_delivery(DAY) == [_dish()]
def test_refresh_delivery_outage_falls_back_to_cache() -> None:
save_delivery(DAY, [_dish()])
with _patched_fetch(side_effect=KuchniaError("down")):
dishes, reason = refresh_delivery(DAY)
assert dishes == [_dish()]
assert reason is None
def test_refresh_delivery_outage_without_cache_reports_reason() -> None:
with _patched_fetch(side_effect=KuchniaError("down")):
dishes, reason = refresh_delivery(DAY)
assert dishes == []
assert reason == "down"
def test_refresh_delivery_success_with_no_dishes_skips_cache() -> None:
with _patched_fetch(return_value=[]):
dishes, reason = refresh_delivery(DAY)
assert dishes == []
assert reason is None
assert load_delivery(DAY) == []
# --- refresh_delivery_once --------------------------------------------------
def test_refresh_delivery_once_after_import_day_reads_cache() -> None:
record_import_day(DAY.isoformat())
save_delivery(DAY, [_dish()])
with patch("diet_guard._kuchnia_import.fetch_dishes") as fetch:
dishes, reason = refresh_delivery_once(DAY)
fetch.assert_not_called()
assert dishes == [_dish()]
assert reason is None

View File

@ -0,0 +1,34 @@
"""The rank this repo publishes matches its row in ``DOCS-lock-order.md``.
kuhy fixed the order of every lock on 2026-11-21 (workout, book, tutor, diet,
focus, LeetCode last). Each repo keeps the rank as its own literal, so this
test is what stops one repo drifting out of that order on its own.
"""
from __future__ import annotations
from pathlib import Path
import re
from diet_guard._constants import RANK_DIET_GUARD
_DOCS = Path(__file__).resolve().parents[2] / "DOCS-lock-order.md"
_ROW = re.compile(r"^\| (\d+) \| [^|]+ \| (\w+) \| (\d+) \| [^|]+ \|$")
def _documented_ranks() -> dict[str, int]:
"""Map each gatelock app in the DOCS table to its rank."""
rows = (_ROW.match(line) for line in _DOCS.read_text().splitlines())
return {m[2]: int(m[3]) for m in rows if m}
def test_the_rank_is_the_one_in_the_lock_order_table() -> None:
"""A rank changed here without the table (or back) fails."""
assert _documented_ranks()["diet_guard"] == RANK_DIET_GUARD
def test_the_table_orders_the_locks_by_falling_rank() -> None:
"""Rows run strongest first, and no two locks share a rank."""
ranks = list(_documented_ranks().values())
assert ranks == sorted(ranks, reverse=True)
assert len(set(ranks)) == len(ranks)

View File

@ -0,0 +1,86 @@
"""scripts/test_changed.sh runs flutter like a CI-mirror shard does.
A bare ``flutter test`` on the shared /tmp stalled a 3-file run to 67 s under
the build queue (2026-11-21, perf.heavybuild) while the same files take ~4 s
alone; the shards fixed that with a private TMPDIR and two isolates, and the
targeted runner must do the same.
"""
from __future__ import annotations
import os
from pathlib import Path
import shutil
import subprocess
REPO = Path(__file__).resolve().parents[2]
GIT = shutil.which("git") or "git"
BASH = shutil.which("bash") or "bash"
FAKE_FLUTTER = """#!/bin/bash
printf 'TMPDIR=%s\\n' "${TMPDIR:-}" >> "$FLUTTER_LOG"
printf 'ARGS=%s\\n' "$*" >> "$FLUTTER_LOG"
"""
def _shared_tmp(tmp_path: Path) -> Path:
"""Stand-in for the machine-wide /tmp the caller would pass down."""
shared = tmp_path / "shared-tmp"
shared.mkdir(exist_ok=True)
return shared
def _git(cwd: Path, *args: str) -> None:
subprocess.run([GIT, *args], cwd=cwd, check=True, capture_output=True)
def _run_test_changed(tmp_path: Path) -> dict[str, str]:
repo = tmp_path / "repo"
(repo / "scripts").mkdir(parents=True)
(repo / "app" / "test").mkdir(parents=True)
shutil.copy(REPO / "scripts" / "test_changed.sh", repo / "scripts")
_git(repo, "init", "-q")
_git(
repo,
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-q",
"--allow-empty",
"-m",
"init",
)
(repo / "app" / "test" / "a_test.dart").write_text("void main() {}\n")
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
fake = bin_dir / "flutter"
fake.write_text(FAKE_FLUTTER)
fake.chmod(0o755)
log = tmp_path / "flutter.log"
env = {
**os.environ,
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"FLUTTER_LOG": str(log),
"TMPDIR": str(_shared_tmp(tmp_path)),
}
subprocess.run(
[BASH, "scripts/test_changed.sh"],
cwd=repo,
env=env,
check=True,
capture_output=True,
)
return dict(line.split("=", 1) for line in log.read_text().splitlines())
def test_flutter_gets_a_private_tmpdir_that_is_removed(tmp_path: Path) -> None:
seen = _run_test_changed(tmp_path)
assert seen["TMPDIR"] not in {"", str(_shared_tmp(tmp_path))}
assert not Path(seen["TMPDIR"]).exists()
def test_flutter_runs_two_isolates_on_the_changed_file(tmp_path: Path) -> None:
seen = _run_test_changed(tmp_path)
assert "--concurrency=2" in seen["ARGS"]
assert "test/a_test.dart" in seen["ARGS"]

View File

@ -3,7 +3,7 @@
The phone sends a food description and/or a photo. A worker on the PC runs The phone sends a food description and/or a photo. A worker on the PC runs
Claude on kuhy's Max subscription, **logs the meal at once (no review)** and Claude on kuhy's Max subscription, **logs the meal at once (no review)** and
answers the phone. Transport is Firebase RTDB through the shared answers the phone. Transport is Firebase RTDB through the shared
`rtdb_relay` package (`kuhyx/utils`, tag `rtdb-relay-v0.1.1`), the same wire `rtdb_relay` package (`kuhyx/utils`, tag `rtdb-relay-v0.2.0`), the same wire
format as the tutor app. No VPN, no open port, only kuhy's Google account. format as the tutor app. No VPN, no open port, only kuhy's Google account.
This file is the contract both halves build against. The fixture This file is the contract both halves build against. The fixture

View File

@ -40,8 +40,10 @@ from the phone; `FillAllFlow` stays as the tested plan logic.
undo plus the next resume would log the dish again. undo plus the next resume would log the dish again.
- **The fetch is cached.** `KuchniaQueueService.refreshOnce` returns nothing - **The fetch is cached.** `KuchniaQueueService.refreshOnce` returns nothing
after the day's first clean fetch, so a slot falling due at 12:00 would never after the day's first clean fetch, so a slot falling due at 12:00 would never
see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and retries a see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and in
failed or empty fetch at most every 10 minutes (a login per try). `kuchnia_delivery.json` (offline first: a restart or a panel outage still has
them), and retries a failed or empty fetch at most every 10 minutes (a login
per try). The PC keeps the same file (`_kuchnia_delivery_cache.py`).
- Each logged dish shows as a row: restaurant glyph, name, kcal and macro - Each logged dish shows as a row: restaurant glyph, name, kcal and macro
dots, a 48 dp undo. One publish per batch (`publishAfterLog`). dots, a 48 dp undo. One publish per batch (`publishAfterLog`).
- Unverified: whether `deliveryMealId` is stable across fetches on the live - Unverified: whether `deliveryMealId` is stable across fetches on the live

View File

@ -22,7 +22,7 @@ Until the first read of today's log the screen draws neither (no app-bar flash).
No slot picker. Due mode: both the check and the sparkle target the **oldest No slot picker. Due mode: both the check and the sparkle target the **oldest
due slot** (`dueSlots.first`). Normal mode: `slotForLog` (nearest). The integer due slot** (`dueSlots.first`). Normal mode: `slotForLog` (nearest). The integer
slot maths in `models/slot.dart` is untouched. A *future* date (the date row, slot maths in `models/slot.dart` is untouched. A *future* date (the app bar's date icon,
normal mode only) keeps its own slot row, because it has no due slots to derive normal mode only) keeps its own slot row, because it has no due slots to derive
from. from.
@ -42,6 +42,19 @@ every state and `maxScrollExtent == 0`. Macro values of four digits must paint
whole at 16 sp or more (`macro_input_row_test.dart` measures the digits; a whole at 16 sp or more (`macro_input_row_test.dart` measures the digits; a
`Row` of `Expanded` fields clips them without any exception). `Row` of `Expanded` fields clips them without any exception).
## Date picker and the keyboard
- The "log for later" picker is the **leftmost app bar icon** (`Icons.edit_calendar`,
`buildDateActions` in `log_meal_future_mixin.dart`); there is no date row above
the field. A picked future date tints it gold (theme primary) with a small
dot (`log-date-badge`) and adds a close icon back to today. No date text.
- **NO COVER BY KEYBOARD EVER** (kuhy): while `viewInsetsOf(context).bottom > 0`
the today-progress card and the logged rows are not built; they return when
the keyboard closes. Field, suggestions, macros and action row sit fully
above the keyboard with `maxScrollExtent == 0`, in normal and due mode, for
a 320 dp and a 400 dp keyboard (`log_meal_keyboard_test.dart`). Do not fix
an overflow by scrolling content under the keyboard.
## Logged rows and undo ## Logged rows and undo
After a Claude, check or catering log, a row (origin glyph, name, kcal and macro After a Claude, check or catering log, a row (origin glyph, name, kcal and macro

View File

@ -0,0 +1,45 @@
# Patch-target gate (`scripts/check_patch_targets.py`)
`mock.patch("pkg.module.NAME", ...)` fails open. When a refactor moves `NAME`, the old path still
imports, the patch redirects nothing, and the test stays green while it writes to real user state.
The script reads every test file, finds each literal `patch("<package>....")` target, and exits 1
when a target no longer resolves.
## Usage
Run it from the repo root:
```bash
python3 scripts/check_patch_targets.py PACKAGE [--tests-root DIR]
```
- `PACKAGE` is required. The script checks only targets inside it (`pkg` or `pkg.*`; `pkg_other`
is not `pkg`). It has no default, because a silent default would check the wrong package and
pass, which is the fail-open shape the gate exists to catch.
- `--tests-root` defaults to `PACKAGE/tests`.
- The package must be a flat package at the repo root (`./PACKAGE/__init__.py`). There is no
`src/` layout support yet.
- Exit codes: `0` clean, `1` stale targets (each printed as `file:line: patch target does not
resolve: ...`), a package that will not import or a missing tests root, `2` usage error.
## Adopting it in another guard repo
Copy `scripts/check_patch_targets.py` into the repo's `scripts/`, then add this hook to
`.pre-commit-config.yaml` under a `repo: local` block:
```yaml
- id: patch-targets
name: test patch targets resolve
entry: python3 scripts/check_patch_targets.py <your_package>
language: system
pass_filenames: false
files: ^<your_package>/
```
The script puts the repo root on `sys.path` itself, so the hook works on a CI runner that never
installed the package.
## Follow-up: a shared copy
Each adopter copies the script today. Moving it to a shared `~/src/utils/patch_targets/` package
is a separate follow-up, done once a second repo actually adopts it.

View File

@ -19,6 +19,9 @@ and `test_gate_no_words_static.py` (Tk gate), `app/test/no_words_*_test.dart`
|---|---|---| |---|---|---|
| `app/lib/main.dart` | `Diet Guard` | `MaterialApp.title`: task switcher and tab name | | `app/lib/main.dart` | `Diet Guard` | `MaterialApp.title`: task switcher and tab name |
| `diet_guard/_gatelock.py` | `Diet Gate` | window title, an identifier under override-redirect | | `diet_guard/_gatelock.py` | `Diet Gate` | window title, an identifier under override-redirect |
| `app/android/app/src/main/AndroidManifest.xml` | `DietGuard` | `android:label`: launcher name |
| `app/desktop/install_desktop_entry.sh` | `DietGuard`, `Diet logging and budget companion` | `.desktop` Name and Comment: app-menu entry |
| `packaging/aur/PKGBUILD` | `DietGuard`, `Diet logging and budget companion` | `.desktop` Name and Comment in the AUR package |
The launcher label and notification channel (`DietGuard`) live in The launcher label and notification channel (`DietGuard`) live in
`AndroidManifest.xml` and `notification_backend_io.dart`; a due-slot `AndroidManifest.xml` and `notification_backend_io.dart`; a due-slot

View File

@ -4,16 +4,17 @@ version = "1.0.0"
description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking" description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking"
requires-python = ">=3.14" requires-python = ">=3.14"
dependencies = [ dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock", "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync", "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", "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds", "holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays", "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
"claude-agent-sdk==0.2.183", "claude-agent-sdk==0.2.189",
"defusedxml==0.7.1", "defusedxml==0.7.1",
"httpx==0.28.1", "httpx==0.29.0",
"requests==2.34.2", "requests==2.34.2",
"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay", "rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.3#subdirectory=rtdb_relay",
] ]
# Optional extras. The `mcp` group is ONLY needed by the MCP server # Optional extras. The `mcp` group is ONLY needed by the MCP server
@ -23,6 +24,9 @@ dependencies = [
# to import the MCP SDK. # to import the MCP SDK.
[project.optional-dependencies] [project.optional-dependencies]
mcp = ["mcp==2.3.0"] mcp = ["mcp==2.3.0"]
# Test-only: the property tests (test_claude_log.py) need it; same pin as
# requirements.txt.
dev = ["hypothesis==6.170.23"]
# Without this, setuptools' flat-layout auto-discovery treats the Flutter # Without this, setuptools' flat-layout auto-discovery treats the Flutter
# app/ directory as a second top-level package and refuses to build. # app/ directory as a second top-level package and refuses to build.
@ -174,10 +178,6 @@ addopts = [
"--strict-markers", "--strict-markers",
"--strict-config", "--strict-config",
"-ra", "-ra",
"--cov=diet_guard",
"--cov-branch",
"--cov-report=term-missing",
"--cov-report=lcov",
] ]
filterwarnings = [ filterwarnings = [
"error", "error",
@ -203,7 +203,6 @@ omit = [
] ]
[tool.coverage.report] [tool.coverage.report]
fail_under = 100
show_missing = true show_missing = true
skip_covered = false skip_covered = false
exclude_lines = [ exclude_lines = [

View File

@ -1,20 +1,21 @@
# Diet Guard — runtime + development dependencies # Diet Guard — runtime + development dependencies
# Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below. # Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below.
bandit==1.9.4 bandit==1.9.4
claude-agent-sdk==0.2.183 claude-agent-sdk==0.2.189
codespell==2.4.3 codespell==2.4.3
coverage==7.17.3 coverage==7.17.5
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
defusedxml==0.7.1 defusedxml==0.7.1
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
httpx==0.28.1 httpx==0.29.0
hypothesis==6.170.15 hypothesis==6.170.23
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
mcp==2.3.0 mcp==2.3.0
mypy==2.4.1 mypy==2.4.1
pre-commit==4.7.0 pre-commit==4.7.0
pydantic==2.14.3 pydantic==2.14.4
pylint==4.1.4 pylint==4.1.4
pytest==9.2.0 pytest==9.2.0
pytest-cov==7.1.0 pytest-cov==7.1.0
@ -23,6 +24,6 @@ pytest-sugar==1.1.1
pytest-xdist==3.8.0 pytest-xdist==3.8.0
pytest-xvfb==3.1.1 pytest-xvfb==3.1.1
requests==2.34.2 requests==2.34.2
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.3#subdirectory=rtdb_relay
ruff==0.17.5 ruff==0.17.6
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays

View File

@ -10,12 +10,20 @@ suite writes to the real ``~/.local/share/diet_guard``, which
That is why this gate exists rather than a note in CLAUDE.md: the failure it That is why this gate exists rather than a note in CLAUDE.md: the failure it
guards against is silent and green, so only a static check catches it. guards against is silent and green, so only a static check catches it.
Usage: Usage (from the repo root):
python3 scripts/check_patch_targets.py python3 scripts/check_patch_targets.py PACKAGE [--tests-root DIR]
``PACKAGE`` is required: only patch targets starting with it are checked, and
a silent default would be the same fail-open shape this script guards
against. ``--tests-root`` defaults to ``PACKAGE/tests``. Only flat packages
at the repo root are supported. Adopting it in another repo:
docs/DOCS-patch-targets.md. A shared ``~/src/utils/patch_targets/`` package is
a separate follow-up, once a second repo actually adopts this script.
""" """
from __future__ import annotations from __future__ import annotations
import argparse
import ast import ast
import importlib import importlib
import pathlib import pathlib
@ -25,12 +33,6 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator
#: Only paths into this package are checked; a patch of `requests` or `tk` is
#: not ours to validate.
PACKAGE = "diet_guard"
TESTS_ROOT = pathlib.Path(PACKAGE) / "tests"
# Running this as `python3 scripts/check_patch_targets.py` puts *scripts/* on # Running this as `python3 scripts/check_patch_targets.py` puts *scripts/* on
# sys.path, not the repo root -- so `import diet_guard` fails unless the # sys.path, not the repo root -- so `import diet_guard` fails unless the
# package happens to be installed. It is not, on a CI runner that only # package happens to be installed. It is not, on a CI runner that only
@ -40,8 +42,19 @@ TESTS_ROOT = pathlib.Path(PACKAGE) / "tests"
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]: def _in_package(dotted: str, package: str) -> bool:
"""Yield ``(file, lineno, dotted_target)`` for every literal patch target.""" """Whether ``dotted`` is ``package`` or inside it (``pkg`` is not ``pkg_a``)."""
return dotted == package or dotted.startswith(f"{package}.")
def patch_targets(
root: pathlib.Path, package: str
) -> Iterator[tuple[pathlib.Path, int, str]]:
"""Yield ``(file, lineno, dotted_target)`` for each literal target in ``package``.
Only paths into ``package`` are checked; a patch of ``requests`` or ``tk``
is not ours to validate.
"""
for path in sorted(root.rglob("*.py")): for path in sorted(root.rglob("*.py")):
tree = ast.parse(path.read_text(), str(path)) tree = ast.parse(path.read_text(), str(path))
for node in ast.walk(tree): for node in ast.walk(tree):
@ -54,15 +67,30 @@ def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]
if ( if (
isinstance(first, ast.Constant) isinstance(first, ast.Constant)
and isinstance(first.value, str) and isinstance(first.value, str)
and first.value.startswith(PACKAGE) and _in_package(first.value, package)
): ):
yield path, node.lineno, first.value yield path, node.lineno, first.value
def _third_party_missing(exc: ImportError) -> bool: def _third_party_missing(exc: ImportError, package: str) -> bool:
"""Whether ``exc`` is a missing dependency, not a missing diet_guard module.""" """Whether ``exc`` is a missing dependency, not a missing ``package`` module."""
missing = getattr(exc, "name", None) or "" missing = getattr(exc, "name", None) or ""
return isinstance(exc, ModuleNotFoundError) and not missing.startswith(PACKAGE) return isinstance(exc, ModuleNotFoundError) and not _in_package(missing, package)
def _lazy_names(value: ast.expr | None) -> list[str]:
"""The names a PEP 562 ``_LAZY_ATTRS`` table (dict keys or a tuple) serves."""
if isinstance(value, ast.Dict):
items: list[ast.expr | None] = list(value.keys)
elif isinstance(value, (ast.Tuple, ast.List, ast.Set)):
items = list(value.elts)
else:
return []
return [
i.value
for i in items
if isinstance(i, ast.Constant) and isinstance(i.value, str)
]
def defined_statically(parts: list[str], split: int) -> bool: def defined_statically(parts: list[str], split: int) -> bool:
@ -81,6 +109,8 @@ def defined_statically(parts: list[str], split: int) -> bool:
elif isinstance(node, (ast.Assign, ast.AnnAssign)): elif isinstance(node, (ast.Assign, ast.AnnAssign)):
targets = node.targets if isinstance(node, ast.Assign) else [node.target] targets = node.targets if isinstance(node, ast.Assign) else [node.target]
names = [t.id for t in targets if isinstance(t, ast.Name)] names = [t.id for t in targets if isinstance(t, ast.Name)]
if "_LAZY_ATTRS" in names:
names += _lazy_names(node.value)
elif isinstance(node, (ast.Import, ast.ImportFrom)): elif isinstance(node, (ast.Import, ast.ImportFrom)):
names = [(a.asname or a.name).split(".")[0] for a in node.names] names = [(a.asname or a.name).split(".")[0] for a in node.names]
else: else:
@ -90,7 +120,7 @@ def defined_statically(parts: list[str], split: int) -> bool:
return False return False
def resolves(dotted: str) -> bool: def resolves(dotted: str, package: str) -> bool:
"""Whether ``dotted`` names a real attribute reachable from a real module. """Whether ``dotted`` names a real attribute reachable from a real module.
Tries the longest importable module prefix first, then walks the remaining Tries the longest importable module prefix first, then walks the remaining
@ -105,7 +135,7 @@ def resolves(dotted: str) -> bool:
# worker's `rtdb_relay`, absent from the system python this hook # worker's `rtdb_relay`, absent from the system python this hook
# runs under) still has a source file: check the name statically # runs under) still has a source file: check the name statically
# rather than call a present target stale. # rather than call a present target stale.
if _third_party_missing(exc) and defined_statically(parts, split): if _third_party_missing(exc, package) and defined_statically(parts, split):
return True return True
continue continue
obj: object = module obj: object = module
@ -117,10 +147,25 @@ def resolves(dotted: str) -> bool:
return False return False
def main() -> int: def _parse_args(argv: list[str] | None) -> argparse.Namespace:
"""``package`` (required, no default) and ``--tests-root``."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("package", help="top-level package whose targets to check")
parser.add_argument(
"--tests-root",
type=pathlib.Path,
help="directory of tests to scan (default: PACKAGE/tests)",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Report every unresolvable patch target; return 1 if any were found.""" """Report every unresolvable patch target; return 1 if any were found."""
if not TESTS_ROOT.is_dir(): args = _parse_args(argv)
sys.stderr.write(f"Error: {TESTS_ROOT} not found; run from the repo root.\n") package: str = args.package
tests_root: pathlib.Path = args.tests_root or pathlib.Path(package) / "tests"
if not tests_root.is_dir():
sys.stderr.write(f"Error: {tests_root} not found; run from the repo root.\n")
return 1 return 1
# Distinguish "this target moved" from "the package will not import at # Distinguish "this target moved" from "the package will not import at
@ -128,10 +173,10 @@ def main() -> int:
# target reports stale at once, which reads like a catastrophic refactor # target reports stale at once, which reads like a catastrophic refactor
# and hides the real error (a missing dependency, a syntax error). # and hides the real error (a missing dependency, a syntax error).
try: try:
importlib.import_module(PACKAGE) importlib.import_module(package)
except ImportError as exc: except ImportError as exc:
sys.stderr.write( sys.stderr.write(
f"Error: cannot import {PACKAGE} ({exc}); every patch target would " f"Error: cannot import {package} ({exc}); every patch target would "
f"be reported stale. Fix the import first -- this is an environment " f"be reported stale. Fix the import first -- this is an environment "
f"problem, not a stale patch target.\n", f"problem, not a stale patch target.\n",
) )
@ -139,8 +184,8 @@ def main() -> int:
stale = [ stale = [
(path, lineno, target) (path, lineno, target)
for path, lineno, target in patch_targets(TESTS_ROOT) for path, lineno, target in patch_targets(tests_root, package)
if not resolves(target) if not resolves(target, package)
] ]
for path, lineno, target in stale: for path, lineno, target in stale:
sys.stderr.write(f"{path}:{lineno}: patch target does not resolve: {target}\n") sys.stderr.write(f"{path}:{lineno}: patch target does not resolve: {target}\n")

View File

@ -147,7 +147,10 @@ run_flutter_gates() {
} }
# Bucket I of N of the app's test files (every N-th, sorted), so the N buckets # Bucket I of N of the app's test files (every N-th, sorted), so the N buckets
# partition the suite exactly. Each bucket stays under the 60 s action cap. # partition the suite exactly. Each bucket stays under the 60 s action cap:
# at 6 buckets of 25 files one took 39 s alone and 63-67 s when the machine
# was busy (2026-11-21), so there are 12 (about 13 files each). Add hooks,
# not files per hook, when the suite grows; a lone file costs about 3 s.
run_flutter_test_shard() { run_flutter_test_shard() {
[[ ${1:-} =~ ^([0-9]+)/([1-9][0-9]*)$ ]] || fail "flutter-test --shard wants I/N, got '${1:-}'" [[ ${1:-} =~ ^([0-9]+)/([1-9][0-9]*)$ ]] || fail "flutter-test --shard wants I/N, got '${1:-}'"
local index=${BASH_REMATCH[1]} total=${BASH_REMATCH[2]} hooks i=0 file local index=${BASH_REMATCH[1]} total=${BASH_REMATCH[2]} hooks i=0 file
@ -164,7 +167,18 @@ run_flutter_test_shard() {
done < <(find "$APP_DIR/test" -name '*_test.dart' | LC_ALL=C sort) done < <(find "$APP_DIR/test" -name '*_test.dart' | LC_ALL=C sort)
((${#files[@]} > 0)) || fail "flutter test shard $index/$total has no test files" ((${#files[@]} > 0)) || fail "flutter test shard $index/$total has no test files"
log "flutter test shard $index/$total (${#files[@]} files)" log "flutter test shard $index/$total (${#files[@]} files)"
(cd "$APP_DIR" && flutter_clean_env test "${files[@]}") || fail "flutter test shard $index/$total" # A private TMPDIR per shard: on the shared /tmp a shard stalled at ~2 s of
# CPU for 15+ minutes (2026-11-21, held a build slot past 60 s) while the
# same shard with its own TMPDIR finished in well under a minute.
# Two test isolates, not flutter's default of one per spare core: at the
# default a shard peaked at 3.9 GiB and was OOM-killed inside capped.sh's
# 2 GiB scope; at 4 it still hit 2 GiB and was killed now and then; at 2
# it peaks at 1.8 GiB and runs in ~22 s (2026-11-21).
local tmp status=0 concurrency=${FLUTTER_TEST_CONCURRENCY:-2}
tmp="$(mktemp -d "${XDG_CACHE_HOME:-$HOME/.cache}/diet-guard-flutter-test.XXXXXX")"
(cd "$APP_DIR" && TMPDIR="$tmp" flutter_clean_env test --concurrency="$concurrency" "${files[@]}") || status=$?
rm -rf -- "$tmp"
((status == 0)) || fail "flutter test shard $index/$total"
} }
# No phase argument (or pytest options) runs everything, exactly as CI does. # No phase argument (or pytest options) runs everything, exactly as CI does.

49
scripts/deploy.sh Executable file
View File

@ -0,0 +1,49 @@
#!/bin/bash
# ============================================================================
# Deploy main everywhere it runs on this PC, then prove it.
#
# 1. Pull the durable clone the gate timer runs from (editable install).
# 2. Reinstall it into system Python's user site: diet-guard-gate.service
# runs /usr/bin/python, not a venv (CLAUDE.md, the 2026-06-19 outage).
# 3. Rebuild and reinstall the desktop app package (app/install_arch.sh).
# 4. Restart the long-running Claude worker so it loads the new code (the
# gate is a oneshot timer and picks it up on its next tick).
#
# The phone APK ships through CI (release-apk.yml) and phone_deploy.sh.
# Idempotent; exits non-zero unless every health check passes.
# ============================================================================
set -euo pipefail
readonly REPO="$HOME/src/diet-guard"
readonly PY=/usr/bin/python3
fail() {
echo "deploy: $*" >&2
exit 1
}
git -C "$REPO" pull --ff-only
"$PY" -m pip install --user --break-system-packages -q -e "$REPO"
(cd "$REPO/app" && bash install_arch.sh)
readonly WORKER=diet-guard-claude.service
worker_on=false
if systemctl --user is-enabled --quiet "$WORKER"; then
worker_on=true
systemctl --user restart "$WORKER"
fi
# Health: the gate's own interpreter imports the code the timer will run...
"$PY" -c 'import diet_guard._cli, diet_guard._errors, diet_guard._gatelock' \
|| fail "system python cannot import the gate"
systemctl --user is-enabled --quiet diet-guard-gate.timer \
|| fail "diet-guard-gate.timer is not enabled"
if "$worker_on"; then
sleep 3 # a worker that crashes on import dies within a second or two
systemctl --user is-active --quiet "$WORKER" || fail "$WORKER did not stay up"
fi
# ...and the desktop package is the version this checkout builds.
want="$(sed -n 's/^version:[[:space:]]*\([^+]*\).*/\1/p' "$REPO/app/pubspec.yaml")"
have="$(pacman -Q diet-guard-app | awk '{print $2}')"
[[ "$have" == "$want-1" ]] || fail "desktop app is $have, want $want-1"
echo "deploy: ok (gate imports, timer enabled, worker restarted=$worker_on, desktop app $have)"

View File

@ -22,8 +22,16 @@ pytest_run() {
} }
# Dart changes map to app/test/<name>_test.dart; any other app/ change runs the app suite. # Dart changes map to app/test/<name>_test.dart; any other app/ change runs the app suite.
# A private TMPDIR and two isolates, as each ci_mirror.sh shard does: on the
# shared /tmp a 3-file run stalled to 67 s in the build queue (2026-11-21)
# against ~4 s alone, and the default isolate count overruns capped.sh's 2 GiB.
flutter_run() { flutter_run() {
(cd app && flutter test --reporter=compact "$@") local tmp status=0
tmp="$(mktemp -d "${XDG_CACHE_HOME:-$HOME/.cache}/diet-guard-flutter-test.XXXXXX")"
(cd app && TMPDIR="$tmp" flutter test --reporter=compact \
--concurrency="${FLUTTER_TEST_CONCURRENCY:-2}" "$@") || status=$?
rm -rf -- "$tmp"
return "$status"
} }
if grep -qs testmon pyproject.toml requirements*.txt; then if grep -qs testmon pyproject.toml requirements*.txt; then