Compare commits

..

20 Commits

Author SHA1 Message Date
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
55 changed files with 1504 additions and 247 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

@ -25,14 +25,14 @@ jobs:
skip: "" skip: ""
- group: rest - group: rest
hooks: "" hooks: ""
skip: mypy,pylint skip: mypy,pylint,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 +59,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

View File

@ -114,7 +114,8 @@ repos:
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync - 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.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays - sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay - rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.184 - claude-agent-sdk==0.2.184
- httpx==0.28.1 - httpx==0.28.1
@ -174,48 +175,96 @@ repos:
require_serial: true require_serial: true
stages: [manual] 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
@ -281,7 +330,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

@ -143,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,

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

@ -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.9.1-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-all.zip

View File

@ -13,9 +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/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';
@ -56,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();

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

@ -162,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

@ -47,22 +47,27 @@ List<Widget> logMealAppBarActions({
}) => [ }) => [
...leading, ...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

@ -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

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

@ -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

@ -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

@ -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.9.1" ref: "crdt_sync_flutter-v0.9.2"
resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5" resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.9.1" 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.3" ref: "data_transfer_flutter-v0.2.4"
resolved-ref: bb2f92f459283a29ad4864cf37704cc5f749cc6d resolved-ref: "5c2effe7d1148830c9e273e47a272791dc17509e"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.2.3" 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: c3780977700b8962c3b9b6a9aa4e2c988956893d70d4a4fa2d7adf4ec9b9eaee sha256: "5b99250437a4d34ee2cdc0686924452103540eaa1c248094b63f07f9d7216f6c"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "13.4.0" version: "13.4.1"
file_picker_darwin: file_picker_darwin:
dependency: transitive dependency: transitive
description: description:
@ -296,10 +296,10 @@ 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:
@ -413,10 +413,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: flutter_local_notifications name: flutter_local_notifications
sha256: "7d37d69ded3028af4f22531a0097a3baa478a384dff2e23e873707c93df3b704" sha256: "2b7579556c117b535ef83835798a7f3c4003dc892a888a4a99f2107bca7b6675"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "23.0.3" 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:
@ -1067,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.4" ref: "sync_settings_ui-v0.8.6"
resolved-ref: "15ef5b44f186cea0ab163cc88cb8743c51d58247" resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.8.4" 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.182+1 version: 1.0.194+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.9.1 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.3 ref: data_transfer_flutter-v0.2.4
path: data_transfer_flutter path: data_transfer_flutter
fl_chart: 1.3.1 fl_chart: 1.3.1
flutter: flutter:
sdk: flutter sdk: flutter
flutter_local_notifications: 23.0.3 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.4 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

@ -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

@ -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

@ -3,9 +3,11 @@
# they carry no `expires`; everything else is discretionary and expires. # they carry no `expires`; everything else is discretionary and expires.
exceptions: exceptions:
- ecosystem: toolchain - ecosystem: pypi
package: flutter package: httpx
pinned: "3.47.9" pinned: 0.28.1
reason: local toolchain /opt/flutter is 3.47.9; fleet-wide Flutter 3.50 bump is separate work reason: >-
blocked_by: local-toolchain rtdb-relay 0.2.2 (its newest release) pins httpx 0.28.1 exactly, so pip
expires: "2026-11-26" refuses 0.29.0 next to it. rtdb-relay is the Claude relay transport, so
httpx waits for it.
blocked_by: transitive:rtdb-relay@0.2.2

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.

View File

@ -42,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 +51,14 @@ from gatelock import (
) )
from diet_guard import _errors 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:

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

@ -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

@ -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,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

@ -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

@ -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.16.0#subdirectory=gatelock", "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#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.184", "claude-agent-sdk==0.2.189",
"defusedxml==0.7.1", "defusedxml==0.7.1",
"httpx==0.28.1", "httpx==0.28.1",
"requests==2.34.2", "requests==2.34.2",
"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay", "rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.2#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
@ -25,7 +26,7 @@ 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 # Test-only: the property tests (test_claude_log.py) need it; same pin as
# requirements.txt. # requirements.txt.
dev = ["hypothesis==6.170.15"] dev = ["hypothesis==6.170.17"]
# 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.

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.184 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.16.0#subdirectory=gatelock gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#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.28.1
hypothesis==6.170.15 hypothesis==6.170.17
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.2.1#subdirectory=rtdb_relay rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.2#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,15 @@ 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]: def _lazy_names(value: ast.expr | None) -> list[str]:
@ -107,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
@ -122,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
@ -134,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
@ -145,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",
) )
@ -156,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.

View File

@ -6,6 +6,8 @@
# 2. Reinstall it into system Python's user site: diet-guard-gate.service # 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). # 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). # 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. # The phone APK ships through CI (release-apk.yml) and phone_deploy.sh.
# Idempotent; exits non-zero unless every health check passes. # Idempotent; exits non-zero unless every health check passes.
@ -24,14 +26,24 @@ fail() {
git -C "$REPO" pull --ff-only git -C "$REPO" pull --ff-only
"$PY" -m pip install --user --break-system-packages -q -e "$REPO" "$PY" -m pip install --user --break-system-packages -q -e "$REPO"
(cd "$REPO/app" && bash install_arch.sh) (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... # 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' \ "$PY" -c 'import diet_guard._cli, diet_guard._errors, diet_guard._gatelock' \
|| fail "system python cannot import the gate" || fail "system python cannot import the gate"
systemctl --user is-enabled --quiet diet-guard-gate.timer \ systemctl --user is-enabled --quiet diet-guard-gate.timer \
|| fail "diet-guard-gate.timer is not enabled" || 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. # ...and the desktop package is the version this checkout builds.
want="$(sed -n 's/^version:[[:space:]]*\([^+]*\).*/\1/p' "$REPO/app/pubspec.yaml")" want="$(sed -n 's/^version:[[:space:]]*\([^+]*\).*/\1/p' "$REPO/app/pubspec.yaml")"
have="$(pacman -Q diet-guard-app | awk '{print $2}')" have="$(pacman -Q diet-guard-app | awk '{print $2}')"
[[ "$have" == "$want-1" ]] || fail "desktop app is $have, want $want-1" [[ "$have" == "$want-1" ]] || fail "desktop app is $have, want $want-1"
echo "deploy: ok (gate imports, timer enabled, desktop app $have)" 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