Compare commits

..

No commits in common. "main" and "v1.0.193" have entirely different histories.

20 changed files with 225 additions and 517 deletions

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

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

View File

@ -17,9 +17,15 @@ jobs:
fail-fast: false
matrix:
include:
- group: mypy
hooks: mypy
skip: ""
- group: pylint
hooks: pylint
skip: ""
- group: rest
hooks: ""
skip: "dependency-freshness"
skip: mypy,pylint,dependency-freshness
name: pre-commit (${{ matrix.group }})
steps:
- uses: actions/checkout@v4

View File

@ -25,6 +25,11 @@ repos:
- id: check-merge-conflict
- id: detect-private-key
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
# Shared fakes and fixtures, not test modules. Split out of conftest.py
# and test_sync.py only because those files passed the 250-line cap.
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -52,9 +57,88 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.2
hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format
types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
additional_dependencies:
- types-requests
- repo: https://github.com/pylint-dev/pylint
rev: v3.3.2
hooks:
- id: pylint
# pre-commit itself runs on 3.15 and `python3` resolves to it; this
# pylint's --jobs=4 pickles with dill, which crashes there
# (no `co_lnotab`). The repo targets 3.14.
language_version: python3.14
args:
- --rcfile=pyproject.toml
- --fail-under=10
- --jobs=4
additional_dependencies:
- pytest
- requests
# Kept in step with pyproject.toml: pip refuses two different
# direct URLs for one distribution, so any pin that drifts from
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
- claude-agent-sdk==0.2.184
- httpx==0.28.1
- mcp>=2,<3
- pydantic
- defusedxml==0.7.1
# Test suites intentionally use patterns (protected-access, magic-value
# comparisons) that don't belong in the source-code 10/10 gate.
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
- repo: https://github.com/PyCQA/bandit
rev: 1.7.10
hooks:
- id: bandit
args:
- -c
- pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(tests/|.*test.*\.py$)
- repo: local
hooks:
# Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form.
@ -82,6 +166,14 @@ repos:
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-analyze
name: CI mirror 4 (flutter analyze)
entry: bash scripts/ci_mirror.sh flutter-analyze
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-flutter-test-1
name: CI mirror 5 (flutter test 1/12)
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/12
@ -179,6 +271,15 @@ repos:
require_serial: true
stages: [manual]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- id: codespell
args:
- --skip=*.json,*.lock,.git,__pycache__,.venv
# Devine: the 1974 ideal-body-weight formula's author, not "define".
- --ignore-words-list=devine
- repo: local
hooks:
# Fails a commit that still points crdt_sync at a local path. Local
@ -199,6 +300,29 @@ repos:
pass_filenames: false
always_run: true
require_serial: true
- id: shellcheck
name: shellcheck
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
language: system
types: [shell]
# A PKGBUILD is a makepkg manifest, not a standalone script: it has no
# shebang (SC2148) and its variables are read by makepkg rather than by
# the file itself (SC2034). namcap is what actually lints these.
exclude: '^packaging/aur/PKGBUILD$'
# The shared 250-line cap. Checks only the files in the commit, so an
# unrelated commit never breaks; exits 1 rather than warning. No
# baseline and no allowlist -- those are suppressions. The exemption
# list (generated/vendored/data files) lives with the checker in
# ~/src/utils/file_length/config.py so the gate and the survey cannot
# disagree.
#
# Deliberately unfiltered: no types_or and no files. The cap applies to
# Dart and prose too, and a type filter here is what would silently
# exempt the whole Flutter app and every .md.
- id: file-length
name: file length <= 250 lines
entry: scripts/check_file_length.sh
language: system
# unittest.mock.patch fails OPEN: once a refactor moves a name, a patch
# target that still imports redirects nothing, the test passes, and the

View File

@ -20,10 +20,10 @@ show adherence, streaks, a YTD tally and weekly/monthly averages, all derived fr
- run: `python -m diet_guard gate --demo`
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
- test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
- lint: n/a: dropped (kuhy, 2026-11-27)
- coverage: n/a: dropped (kuhy, 2026-11-27)
- lint: `pre-commit run --all-files`
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
- deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
- coverage-gaps: `coverage-gaps coverage.lcov`
## Scheduling
@ -143,7 +143,6 @@ 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
existing `budget` record, so devices predating the feature relay them
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.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,

View File

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

View File

@ -13,11 +13,9 @@ import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/claude_relay_client.dart';
import 'package:diet_guard_app/services/claude_relay_firebase.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/firebase_client.dart' show openFirebase;
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/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_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -58,8 +56,6 @@ Future<void> main() async {
await KuchniaCredentialService.init();
await BodyService.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.
claudeRelay = RtdbClaudeRelay.firebase();
final notifications = await NotificationService.init();

View File

@ -23,32 +23,6 @@ class KuchniaDish {
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...".
///
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse

View File

@ -13,21 +13,16 @@
/// 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
/// 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].
/// and a failed or empty fetch is retried at most every [retryAfter].
/// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean
/// fetch of the day it returns nothing, and slots that fall due later would
/// never see their dish.
library;
import 'dart:convert';
import 'package:diet_guard_app/models/food_entry.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/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_flow.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
@ -49,7 +44,6 @@ class KuchniaAutoLog {
DeliveryFetch? fetch,
DateTime Function()? now,
this.retryAfter = const Duration(minutes: 10),
this.store,
}) : _fetch = fetch ?? refreshDelivery,
_now = now ?? DateTime.now;
@ -59,12 +53,6 @@ class KuchniaAutoLog {
/// Minimum gap between fetches that found nothing or failed.
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 DateTime Function() _now;
String? _cachedDay;
@ -106,56 +94,14 @@ class KuchniaAutoLog {
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
if (_cachedDay == dayKey) return _cachedDishes;
final stored = await _readStored(dayKey);
if (stored.isNotEmpty) {
_cachedDay = dayKey;
return _cachedDishes = stored;
}
final last = _lastEmptyFetch;
if (last != null && _now().difference(last) < retryAfter) return const [];
final result = await _fetch(today);
if (result.ok && result.dishes.isNotEmpty) {
_cachedDay = dayKey;
await _writeStored(dayKey, result.dishes);
return _cachedDishes = result.dishes;
}
_lastEmptyFetch = _now();
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

@ -157,20 +157,20 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.2"
resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
ref: "crdt_sync_dart-v0.14.1"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
url: "https://github.com/kuhyx/utils"
source: git
version: "0.14.2"
version: "0.14.1"
crdt_sync_flutter:
dependency: "direct main"
description:
path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.9.2"
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
ref: "crdt_sync_flutter-v0.9.1"
resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.9.2"
version: "0.9.1"
cross_file:
dependency: transitive
description:
@ -392,10 +392,10 @@ packages:
dependency: "direct main"
description:
name: fl_chart
sha256: "19e4b58179f77b0858ddb9f2db321394e466cba7b2b918b0af7abd79754a1de9"
sha256: "9f11b0b87a6b1843f5ca666ade4a62c08da1a6b7f9efeb91bb2c6f3fa6e31a9a"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
version: "1.3.1"
flutter:
dependency: "direct main"
description: flutter
@ -413,10 +413,10 @@ packages:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "2b7579556c117b535ef83835798a7f3c4003dc892a888a4a99f2107bca7b6675"
sha256: "7d37d69ded3028af4f22531a0097a3baa478a384dff2e23e873707c93df3b704"
url: "https://pub.dev"
source: hosted
version: "23.0.4"
version: "23.0.3"
flutter_local_notifications_linux:
dependency: transitive
description:
@ -1076,11 +1076,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.8.6"
resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
ref: "sync_settings_ui-v0.8.5"
resolved-ref: abfb596d7ce2f28acfefbd55e7b3227257325261
url: "https://github.com/kuhyx/utils"
source: git
version: "0.8.6"
version: "0.8.5"
synchronized:
dependency: transitive
description:

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.197+1
version: 1.0.193+1
environment:
sdk: ^3.12.2
@ -12,13 +12,13 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.2
ref: crdt_sync_dart-v0.14.1
path: crdt_sync_dart
# Keystore-backed end-to-end encryption open + the passphrase lock button.
crdt_sync_flutter:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_flutter-v0.9.2
ref: crdt_sync_flutter-v0.9.1
path: crdt_sync_flutter
crypto: 3.0.8
cryptography: 2.9.0
@ -29,10 +29,10 @@ dependencies:
url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.4
path: data_transfer_flutter
fl_chart: 1.3.2
fl_chart: 1.3.1
flutter:
sdk: flutter
flutter_local_notifications: 23.0.4
flutter_local_notifications: 23.0.3
flutter_secure_storage: 11.2.0
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
@ -71,7 +71,7 @@ dependencies:
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.8.6
ref: sync_settings_ui-v0.8.5
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0

View File

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

@ -2,4 +2,12 @@
# entries are predicates: they clear themselves when the blocker moves, so
# they carry no `expires`; everything else is discretionary and expires.
exceptions: []
exceptions:
- ecosystem: gittag
package: kuhy-credit
pinned: 0.3.1
reason: >-
sickdays 0.5.8 (its newest release) pins kuhy-credit 0.3.1 exactly, so
pip refuses 0.3.2 next to it. Taking 0.3.2 means holding sickdays back
instead; sickdays is the dependency the gate actually runs.
blocked_by: transitive:sickdays@0.5.8

View File

@ -171,10 +171,6 @@ KUCHNIA_SYNCED_CREDENTIAL_FILE: Path = (
KUCHNIA_LAST_IMPORT_FILE: Path = (
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
# Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request
# timeout alone would permit ~32s against a slow provider.

View File

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

View File

@ -151,12 +151,6 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE",
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
# call site, so a test importing `refresh_delivery` directly still
# exercises the real helper.

View File

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

@ -40,10 +40,8 @@ from the phone; `FillAllFlow` stays as the tested plan logic.
undo plus the next resume would log the dish again.
- **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
see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and in
`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`).
see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and retries a
failed or empty fetch at most every 10 minutes (a login per try).
- Each logged dish shows as a row: restaurant glyph, name, kcal and macro
dots, a 48 dp undo. One publish per batch (`publishAfterLog`).
- Unverified: whether `deliveryMealId` is stable across fetches on the live

View File

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

View File

@ -1,17 +1,17 @@
# Diet Guard — runtime + development dependencies
# Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below.
bandit==1.9.4
claude-agent-sdk==0.2.189
claude-agent-sdk==0.2.187
codespell==2.4.3
coverage==7.17.5
coverage==7.17.4
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
defusedxml==0.7.1
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
httpx==0.29.0
hypothesis==6.170.23
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
httpx==0.28.1
hypothesis==6.170.17
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit
mcp==2.3.0
mypy==2.4.1
pre-commit==4.7.0
@ -24,6 +24,6 @@ pytest-sugar==1.1.1
pytest-xdist==3.8.0
pytest-xvfb==3.1.1
requests==2.34.2
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.3#subdirectory=rtdb_relay
rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
ruff==0.17.6
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays