# AGENTS.md — EverShelf working guide > Purpose: let an AI agent (or a new dev) be productive **without** loading the > two giant files (`api/index.php`, `assets/js/app.js`) in full. Read this first, > then jump to just the lines you need using the generated indexes. ## What this project is Self-hosted **pantry manager** (PHP 8 + SQLite + vanilla-JS PWA). No framework, no build step required at runtime (minify is optional). Everything is served from the repo root: `index.html` (SPA) talks to `api/index.php` (single router). Repo root = `/var/www/html/dispensa` (git remote: `dadaloop82/EverShelf`). ## The 30-second mental model ``` Browser (index.html + assets/js/app.js) │ fetch api/index.php?action= (JSON, POST/GET) ▼ api/index.php → switch($action) → handler fn → SQLite (data/evershelf.db) ▲ ▲ │ │ api/lib/*.php (env, security, ai, health, weather, seasonal…) api/cron_smart_shopping.php (CLI cron) ──────────┘ ``` - **All** HTTP actions are dispatched by one `switch ($action)` in `api/index.php` (line **898**). See `docs/INDEX-actions.md` for action → handler. - Frontend is `assets/js/app.js` (~46k lines, ~1.7k top-level functions) plus a few focused modules that own their own screen: `assets/js/audit.js` (the stocktake), `assets/js/screensaver.js` (the idle screen), `assets/js/settings_search.js`, `assets/js/receipt.js`. See `docs/INDEX-app-js.md` for function → line. - Backend is `api/index.php` (~25k lines, ~520 functions) over `api/lib/*.php`. See `docs/INDEX-api-index.md`. ## Golden rules (conventions already in the codebase) - **Language**: code, comments and docs are **English**. UI strings live in `translations/*.json` (IT/EN/DE/FR/ES/ZH) and are used via `t('key')` in JS / `data-i18n="key"` in HTML. Never hardcode a user-facing string. - **Errors**: never emit HTML before JSON. `api/bootstrap.php` disables `display_errors`. Return `{"success":false,"error":"..."}`; wrap handlers in the existing global try/catch and `EverLog`. - **The state of the HOUSE lives on the SERVER, never in `localStorage`.** A phone, a tablet in the kitchen and a kiosk on the wall are ONE household: a stocktake left half-done at the fridge, the setup ledger (`setup_done` / `setup_seen`), the deleted places (`app_settings.deleted_locations`), a dismissed shopping row — all of it is READ FROM THE SERVER. When it lived in the browser the second device started from scratch and the user was asked to redo what he had already done: that is the report this rule exists for (a stocktake run of 195 rows begun on the phone, and a fresh browser that only offered «↩ Riprendi l'inventario (195 rimasti)» after the blob moved to `app_settings.audit_state` — `GET audit_state` / `POST audit_state_save` / `audit_state_clear`, with the one-hour expiry owned by the server, `auditStateRead()`). `localStorage` is allowed as an **offline mirror**, and for what genuinely belongs to that device (the chosen stocktake mode, a UI preference) — never as the truth. New household state → an action + a row in `app_settings`, not a key in the browser. - **Logging**: use `EverLog::info/warn/error/debug/exception/request` (`api/logger.php`). **Client lines have three levels and two rivers.** `remoteLog()/scanLog()/_kioskTrace()` write `[ts] [INFO |WARN |ERROR] [device] tag text` into `data/logs/-YYYY-MM-DD.log`, where the source is declared by the client (`app` for phones/tablets/desktops, `kiosk` for the Android wall — its WebView lines AND its native `report_error` reports), because an Android WebView claims to be a phone in its User-Agent and the wall's evidence used to be filed as `[phone]`. `LOG_LEVEL` governs what is stored (`EVERSHELF_LOG_KEEP_DAYS` = 14), one device can be raised with `?log=debug`, and `_logLevelFromTag()` reads the level out of the legacy tag (`UNCAUGHT` → error, `JANK`/`MEM` → warn, else info) so the hundreds of existing call sites did not have to change. `data/client_debug.log` remains as a compatibility mirror for `get_client_log`. Do **not** use `error_log`/`var_dump`. Put the human-readable words in the message and the stable machine key in the context: `EverLog::warn('API pairing code', ['event' => 'api_pairing_code', …])`. The pairing code must stay greppable with the command the docs advertise (`grep -i "pairing code" logs/evershelf_*.log`) — a snake_case-only message made that command silently return nothing. - **The Android Health Bridge uploads only when EverShelf ANSWERS, and says which river it is.** `evershelf-health-bridge/` keeps each day in a local SQLite queue and every pass asks `health_bridge_hello` first: a phone in the street has internet and no route to the LAN server, so "the phone is online" is never the question — an unreachable server is a *successful deferral* (the day waits on the phone), never a retry storm. Its `report_error` carries `source=health_bridge`, which `reportError()` and `clientLog()` map to their own river (`data/logs/health-YYYY-MM-DD.log`) next to `app` and `kiosk`, and `context.version_guard_bypass=true` because that guard compares against the WEBAPP release tag while the bridge has its own version line. Its OTA asks the LAN server first (`health_bridge_update`, `releases/evershelf-health-bridge.apk` + `health-bridge-version.json`, published by the health-bridge workflow) and GitHub second, and installs only an APK with the **same signature** and a higher `versionCode`. Feature work on it follows the same rule as the webapp: a roadmap entry + an issue, never a code-only change. - **Product titles lead with their genre.** `products.name` is user data and the app now owns the first word of it: a new/renamed product goes through `mergeIncomingProductFields()` → `productKindApply()` (`api/lib/product_kind.php`), which prefixes the genre the label usually omits (`"Fiori di latte"` → `"Yogurt Fiori di latte"`) and stores it in `products.kind`. **A genre is never a CLASS:** «Integratore alimentare», «Parafarmaco», «Dispositivo medico» (and `farmaco`/`medicinale`, already there) live in the vocab's `umbrella_labels`, `productKindIsPlausibleGenre()` refuses them — exact **and** as the head of a longer phrase — and the AI's answer is validated *before* it is cached or prefixed, because an answer like «Integratore alimentare» was replayed by the signature cache and titled every supplement with it (a box of glycerol read «Integratore alimentare glicerolo CARLO ERBA», `products.kind` = the class); `migration_strip_kind_class_prefix_v1` heals the titles already written by `productKindStripUmbrellaCategoryPrefix()`. Cheap first — the curated dictionary (`evershelfShoppingPhraseMap`/`...KeywordMap`, the *same* dictionaries `computeShoppingName()` uses) — and the AI only when the genre word does not lead the name, i.e. when the dictionary cannot tell a yoghurt from a cheese. One paid word per signature (`data/product_kind_cache.json`), never two prefixes on the same title — neither when the genre is already there in another form (`Tarallini`/`Taralli`, `Pera Italiana`/`Pere`, `Kaffee`/`Caffè`, `Italia Zuccheri`/`Zucchero`) nor when the title already opens with the genre stored in `products.kind`: a maintenance pass must replay without drifting a single title (`productKindNameAlreadyHasKind()`, `productKindStartsWithWord()`). The same choke point also owns the *case* of the title: `productTitleCapitalize()` raises the first letter (`"latte fresco"` → `"Latte fresco"`) and nothing else — the rest of the case is kept (`NUTELLA` stays `NUTELLA`, while a brand spelling such as `iPhone` becomes `IPhone`: the rule is mechanical so it cannot disagree with itself) and a title opening with a digit or an emoji is left alone. It is applied in `mergeIncomingProductFields()` **outside** the genre guard, so `PRODUCT_KIND_PREFIX=false` switches off the prefix only, never the spelling, and it is idempotent, so the maintenance pass can replay it. `normalizeProductName()` (api/index.php) is **not** the storage normalizer: it lowercases a *copy* to compare two products in duplicate detection. One vocabulary, two consumers — `products.kind` (genre embedded in the title: precise, may legitimately stay empty) and `products.shopping_name` (the buyable word of the list/Bring!: historical, may be a raw token such as "Potato") are **two columns on purpose**, both reading that one dictionary through `productKindFromDictionary()`; never merge them and never add a second dictionary, or the two will disagree again. The same choke point also owns the **number**: the stored title is the *singular* (`productKindSingularizeName()`: `"Uova medie"` → `"Uovo medio"` — only the genre leading the title moves, the adjective run right after it follows, a variety name never does, and a title opening with a quantity is left alone), while the *plural* is derived where a count is shown, and only for units that count pieces (`productKindUnitCountsPieces()`, `productNameForPieces()`): the pantry read hands the client a `display_name` (`"3 Uova medie"`), so `500 g Pasta` stays a mass and never becomes `500 g Paste`. The two are one round trip (`singular → plural → singular`), which is what lets the maintenance pass replay. `products.shopping_name` is deliberately **not** rewritten by that pass: it is the buyable word of the list, and the shopping list buys `Grissini`, not one `Grissino`. - **Automatic favourites respect the user.** `api/lib/auto_favorite.php` promotes only the absolute top `AUTO_FAVORITE_TOP_N` (default 3) products by consumption that also clear `AUTO_FAVORITE_MIN_USES` inside `AUTO_FAVORITE_WINDOW_DAYS`; `products.favorite_user_override` records a manual unstar so the rule never re-adds it. Favourites are only ever added, never removed by the rule. - **Security**: every POST action goes through the CSRF guard and the API-token check. New action → add it to the relevant allow-lists in `api/lib/security.php` (`evershelfPublicActions`, `evershelfMutatingGetActions`, `evershelfDemoReadOnlyActions`, …) only when intended. **Never authorise on client-supplied headers** (`Origin`, `Referer`, `Sec-Fetch-Site` are forgeable). `app_bootstrap` only hands out `API_TOKEN` after the one-time pairing code (`api/lib/pairing.php`) is presented; a paired device shows the live code under Settings → System → Security (`pairing_code` action); see `SECURITY.md`. - **A public action authenticates itself, or it does not exist.** `gemini_usage` answered *before* the router and therefore forgot the token: a pre-router `if ($_GET['action'] === …)` must call `evershelfRequireAuthForSensitive()` itself. The two public endpoints that cannot present a token carry their own proof: the Telegram webhook compares the `X-Telegram-Bot-Api-Secret-Token` Telegram echoes back against `TELEGRAM_WEBHOOK_SECRET` (`telegramWebhookAuthVerdict()`) and **refuses to answer when there is neither a secret nor an allowlist** — an empty `TELEGRAM_ALLOWED_CHAT_IDS` used to accept any chat id — and the Drive callback consumes the OAuth `state` we issued (`api/lib/gdrive_state.php`: 32 random bytes, only the SHA-256 on disk, 10 minutes, single use, one outstanding flow, and a wrong value never cancels the pending one) *before* it contacts Google, because it overwrites `GDRIVE_REFRESH_TOKEN`. `ALLOWED_HOSTS` (opt-in, `*.example.lan` allowed, `evershelfHostAllowed()`) is the DNS-rebinding guard: a browser cannot see it, only the server knows which names it answers to. An install with no `API_TOKEN` **mints one** on its first request (`evershelfEnsureApiToken()`, `ALLOW_OPEN_LAN=true` opts out, the `data/api_token_autogen.json` marker stops a second mint) and prints the pairing code next to it in the log. A bearer token only ever follows a **same-origin** check (`evershelfSameOrigin()`, not `str_starts_with`) and is never handed to a third party: the Health Bridge pairing QR is drawn by `action health_bridge_qr` → `api/lib/qr.php`, not by a public QR service. `escapeHtml()` does not escape quotes, so an attribute value is `escapeAttr()` — `src="${escapeAttr(url)}"` — while product titles and text stay `escapeHtml()`. - **Auth overlays are drawn during startup, above everything.** Pairing is requested while `_initApp()` is still running, and `_initApp()` returns early when it cannot authenticate — so `#app-preloader` (z-index 200000) is never removed. The auth overlays use `EVERSHELF_AUTH_OVERLAY_Z` (`assets/js/core/auth.js`, 400000), which must stay above `#app-preloader` **and** `#network-error-overlay` (300000). At the `.modal-overlay` default of 200 the dialog is invisible behind the splash and the app dead-ends on "API token required". - **The splash must not lie about the boot.** The rail icons are driven by `_preloaderStage(stage, state)` and the stage→check ownership in `_PRELOADER_STAGE_OF_CHECK`: a health check nobody owns leaves its icon blinking forever, and a stage whose `startup.stage_*` string is missing from any of the six locales prints its raw key. New check → give it a stage; new stage → add the markup row *and* the six translations. Keep the version chip's `id="preloader-version">vX.Y.Z` shape too: `scripts/bump-version.sh` rewrites it ( locks all of it). - **Versioning**: bump version with `scripts/bump-version.sh X.Y.Z` in **5 places** (`index.html` badges, `manifest.json`, `sw.js` cache name, `app.js` i18n token, `README.md` version badge), add a `CHANGELOG.md` entry and prepend the release to the README “What’s new” line (prose, so it stays manual). `auto-merge-to-main` + `create-release` read the version from `index.html`. - **i18n**: never hardcode user-facing strings. Use `t('key')` (JS) / `data-i18n*` (HTML) and add the key to **all** locales (it/en/de/fr/es/zh). `scripts/i18n-audit.py` (run in CI) fails on used-but-missing keys; give `tl()` fallbacks in English. Optional UI strings from PHP should return a `hint_key` (+ `hint_args`), not a literal — and so should a whole payload (`tip_key`, `reasons[]`): the client resolves it with `t()`. The audit's JS regex is literally `\bt\(\s*['"]…`, so a key wrapped in a helper (the local `tr(key, fallback)` in `_localizeSmartReason`) or emitted **only** by PHP is invisible to it: write the resolution as a bare `t('key')` *and* lock the set asserts every `shopping.seasonal_tip_*` key PHP can return exists in all six locales. - **Secrets**: never commit keystores, `.env`, or signing passwords. Android builds read `keystore.properties`/env; CI reads GitHub Secrets (see `SECURITY.md`). - **Commits**: Conventional-ish prefixes seen in history: `feat:`, `fix:`, `release:`, `merge:`. Work on **`develop`**; CI auto-merges `develop → main`. - **Assets cache-busting**: when you edit `app.js`/`style.css`, bump the `?v=` query in `index.html` and the `sw.js` `CACHE` name (it carries the version *and* the stamp letter, e.g. `evershelf-v1.11.13b`). `scripts/bump-version.sh` does both and, inside the same day, continues the stamp letter (`20261014a` → `20261014b`) instead of reusing it — a repeated `a` leaves the browser on the old CSS. ## 4b. The vocabulary is DATA, the code is language-neutral Product names, genres, brands, plural/singular forms, stop words, the shopping dictionaries and the "what does this title mean" rules live in **`api/vocab/.json`**. `api/lib/vocabulary.php` is the only algorithm that reads them (tokenizer, word/stem/phrase match, number forms) and it contains **no product word and no rule about Italian**. The browser runs the same engine (`assets/js/core/vocab.js`) over **`assets/js/vocab.generated.js`**, generated from the JSON by `php scripts/gen-vocab-js.php` (committed, offline-safe). `php scripts/gen-food-facts-js.php` regenerates the offline screensaver facts the same way. The same file also carries the **SHELFY capture lexicon** (`"capture"`: intents, spelled numbers, units with their multiplier, fractions, "all of it", stop words) and the **language metadata** (`"locale"`: the language's own name, its collation tag, its recogniser tag). `_SUPPORTED_LANGS`, `_collationLocale()`, the `?lang=` deep link, the date/number formatting, the TTS voice and the capture parser all read those two blocks — no language name and no spoken synonym belongs in `app.js`. Adding a language = dropping `api/vocab/.json` and regenerating. Adding a word = editing JSON, never a function. The offline screensaver sentences are text as well and follow the same rule: **`data/food_facts_fallback.json`** → `assets/js/food_facts.generated.js` (`php scripts/gen-food-facts-js.php`, in the service-worker shell). enforces it: the generated files must match their JSON, a **ratchet** counts the vocabulary words still left in the logic files — `product_kind.php`, `vocabulary.php` and `core/vocab.js` are at **0**, the rest may only go *down* — and the browser engine must expose **every** top-level function it declares: a lost closing brace in `core/vocab.js` once left nine of them nested (the file still parsed, so nothing complained, and the piece-produce/prepared-salad/plural paths called `undefined`). A new product name in `api/index.php`, `api/database.php` or `app.js` fails the build. Remaining debt (next batch, same rule): the expiry heuristics in `api/database.php` / `app.js` and the recipe ingredient groups. ## 4c. Validate before saying "done" ```bash # PHP syntax check (same as CI) find api -name '*.php' -exec php -l {} \; # JS syntax check (CI runs `node -c` on app.js; the rest are local-only; # mcp-server is ESM → --check, not -c) node -c assets/js/app.js && node -c sw.js for f in mcp-server/src/*.js; do node --check "$f"; done # The only npm tree in the repository: 0 known vulnerabilities, and the lockfile still installs. # The patched floors live in mcp-server/package.json → overrides (see SECURITY.md). (cd mcp-server && npm audit --audit-level=low && npm ci --dry-run --no-audit --no-fund) # Android dependency check (build-only, debug APK, no secrets, nothing published). # It runs on pull requests touching either Android project; dispatch it by hand to # test a dependency bump on a branch before it reaches main: # gh workflow run android-deps-check.yml --ref # Translation files must be valid JSON python3 -c "import json; json.load(open('translations/it.json'))" # i18n audit: keys used in code must exist in every locale (exits 1 on gaps) python3 scripts/i18n-audit.py # Settings coverage: every key save_settings() can write must have a control on the # settings page or a documented reason in api/lib/settings_env_allowlist.php # (exits 1 and names the key it found, e.g. a retention number nobody could set) php scripts/gen-settings-schema.php # regenerate the registry first php scripts/check-settings-coverage.php # i18n value audit: keys whose value is still English (report; --strict to fail) python3 scripts/i18n-value-audit.py # Shell scripts shellcheck -S warning backup.sh scripts/*.sh # Upgrade check — run it BEFORE merging a long-lived branch into main: it builds a database # with the OLD code (a git worktree of --from), fills it with realistic content, opens it with # the NEW code (initializeDB + migrateDB, like the first request after the update) and proves # row by row that nothing was lost. Exit code 1 = merge blocker. php scripts/check-upgrade-migration.php # origin/main → this tree php scripts/check-upgrade-migration.php --from=v1.31.0 --to=HEAD --json # Import the Italian medicine catalogue (AIFA open data; the scan never calls a medicine API). # Optional: fill the gaps from an ONLINE provider, off unless MED_LOOKUP_PROVIDER is set. # It is consulted only for a code nothing local knows, and the answer is cached in the table. # MED_LOOKUP_PROVIDER=medifontis MED_LOOKUP_URL=... MED_LOOKUP_KEY=... (see .env.example) # Run it ONCE, from a shell, after downloading the AIFA file (CSV or XML): php scripts/import-medicines.php data/aifa_farmaci.csv --dry-run # parse + header map, writes nothing php scripts/import-medicines.php data/aifa_farmaci.csv # import / refresh (AIC is the key) # Bump the version in the 4 touchpoints at once (+ cache-busting stamp) scripts/bump-version.sh 1.9.2 # Regenerate the cheap code indexes (do this after big edits) bash scripts/gen-code-index.sh # Run locally without Docker (needs the php extensions from the Dockerfile) php -S 127.0.0.1:8080 # then open http://127.0.0.1:8080 # Optional minify (not required at runtime) npm run build ``` ## Where things live (quick map) | Want to… | Go to | |---|---| | Add/change an HTTP endpoint | `api/index.php` switch (line 898) + a handler `function` below. **A `const` is a STATEMENT**: it is executed where it stands, so a `const` placed next to the function that reads it but BELOW the router does not exist when the handler runs — `generate_recipe_stream` answered «Undefined constant "RECIPE_MIN_PANTRY_INGREDIENTS" (index.php:15914)» and the household's generation stopped working. Constants live at the TOP of the file; functions are hoisted, constants are not | | Auth / CORS / demo mode | `api/lib/security.php` | | Config / `.env` read+write | `api/lib/env.php` (`env()`, `loadEnvOverrides()`: a fallback stored because `.env` was read-only carries the value it was saved against, so a later hand edit of the file wins and the stale entry is dropped — `settings_override_stale`), `saveSettings()` (~9293) | | DB schema & migrations | `api/database.php` (`initializeDB`, `migrateDB`) | | AI providers (Gemini/OpenAI/Llama) | `api/lib/ai_provider.php`, `callGemini()` (~8302) | | Shopping logic | `smartShopping()` (~16000), `shopping_guards.php`, `shopping_sync.php` (shared Bring!/internal sync), `bring_*` fns | | “Non lo compro” must survive the cron | `shopping_remove` with `purchased: false` stores a dated dismiss (`app_settings.shopping_dismissed`, key → YYYY-MM-DD, `SHOPPING_DISMISS_DAYS` default 14 or `dismiss_days` 1–365). Both auto-add paths (`internalShoppingAutoAddCritical`, `bringAutoAddCritical`) skip it and never clear it; `purchased: true` or an `inventory_add` that covers the need clears it (`shoppingClearDismissed*()`) | | The shopping list must not fight itself | Three rules decide whether a row belongs on the list and they must never be asked about a cache that does not exist. **No cache = no knowledge**: `shopping_remove` (and the trip) unlink `data/smart_shopping_cache.json` on purpose, and while it was gone `internalShoppingPruneCovered()` (on every `shopping_list` READ, `shoppingGetList`) and `bringQuickSyncProduct()` (on every inventory WRITE — a stocktake deletes one row per answer) read the missing cache as "nothing is needed" and deleted every app-managed row whose family was covered; five minutes later `internalShoppingAutoAddCritical()` put them back — «mette e toglie», measured 14 → 2 rows while the cron logged `added: 8` twice. Both now return early on an empty smart index (ask the ITEMS, not `evershelfSmartItemsIndex()`, which always returns `["exact"=>[],"token"=>[]]` — a guard on that array never fires) and the prune asks the ONE predicate (`evershelfShoppingRowStillNeeded()` + `evershelfFamilyUsableStockQtyMemo`), never a second copy. A read-path deletion logs `shopping_prune_covered`, a blind quick-sync logs `shopping_quick_sync_no_cache`. **A pack row counts PACKS**: `shoppingUnitIsPack()` (`conf`, `pz`, `busta`, `pacco`, `barattolo`, `confezione`, `pezzo`) is the one vocabulary for the rate guard, the coverage rule and `SMART_PACK_REF_QTY_MAX` — without it a gram log written as `conf` (597 consumed, 86 per purchase) made «Panna da cucina» read `near_empty:6 · ends_in:0` with SIX packs on the shelf | | A shopping row is a FAMILY row | The payload carries `family_qty` (usable stock of the whole buyable generic, in the item's unit): the UI shows that, never the representative product's own quantity, or the row says “Esaurito” next to “Hai già 235 g”. The pantry hint (`_shoppingFamilyInventoryRows()`) counts the same `shopping_name` family only. Coverage: one whole pack/piece (`conf`/`pz`) or half the usual buy (`g`/`ml`) — `$coverageNeeded` in `smartShopping()`. **The family comes from the genre that LEADS the title**: «Yougurth fior di latte» (a spelling the vocabulary had not been taught) was filed as «Latte» because a mid-title genre won over an unknown first word, so a yogurt joined the milk family and the list read «Latte · Esaurito» next to a fridge full of milk («mi dice che ho esaurito cose che ho ancora»). The misspellings are DATA (`api/vocab/it.json` → `keyword_map`: `yougurth`, `yoghurt`, `yoghurth`, `merendine`, `merenda`), `productKindFromDictionary()` refuses a mid-title genre when the lead is food the vocabulary can place, `internalShoppingRetitleFamilies()` renames an app-owned row to the family its `raw_name` belongs to now (or drops it when that family already has a row; typed rows are never touched), and `migration_shopping_family_leading_genre_v1` heals the stored products (9 rows checked on the field install: 2 wrong, 7 compound families like «Pangrattato» left alone) + `invalidateSmartShoppingCache()` | | A finished product must reach the list | `smartShopping()` family coverage uses **usable** stock only: fresh, above `EVERSHELF_TRACE_QTY` (single source of `productQtyThreshold()`), expanded to the same base family with `evershelfBaseQty()` and worth ≥ 1 pack (or ½ the usual buy for g/ml) — `evershelfFamilyUsableStockQty()` is the DB form used by the cleanup and the backfill; `bringAddDepletedProduct()` (explicit "usa tutto") always adds, stamped `🛒 Esaurito`. **A family is MEASURED and COUNTED, the larger wins**: `default_quantity` on a `pz` row is often what ONE piece weighs, so the expanded grams left «Avocado Hass» at 0 of every unit with 4.5 avocados in the fridge (and 2 mozzarellas could not cover a 1 kg pack) — `shoppingUnitIsPack()` is the counted vocabulary, on both sides of the comparison. The row also answers for the ARTICLE: `days_left = familyUsableQty / dailyRate` when the family holds more than the row (two tomato rows are six tomatoes), while expiry keeps the row's own `$daysLeftOwn`. And **the plan says HOW MUCH, the trip says WHEN**: `$signalDays` (the inferred spesa cycle, floored at 7, capped by `plan_days`, 14 with no evidence) replaced `plan_days` as the urgency window in the high-use, predictive, buy-cycle and "on the radar" blocks — a 30-day plan told the household «🟠 Presto» about 5 apples and 500 g of honey (measured: 31 → 18 suggested rows on a real pantry). A «🛒 Esaurito» row is a decision and every prediction spares it, but a REFILLED shelf ends it: both prune paths ask `evershelfFamilyBackInStock()` and clear it (`shopping_finished_row_cleared`) — «Banane · 🛒 Esaurito» next to three bananas was the report | | A finished product is on the list, and «Urgente» is a HABIT | «Urgente» is not a forecast, it is the shelf: `shoppingRecalibrateUrgency()` calms the scale down (red only for an *essential* at zero) so a pantry of low-stock predictions does not read 75 rows of ⚡ — but it must **skip a row whose reasons carry `out_of_stock`**, or every finished article lands in «Presto» / «A breve» and the list's own «Urgente» pill (the one control the household uses to see what must be rebought NOW) is empty (measured on the field pantry: 47 products at zero, 4 under «Urgente»). A finished row is then graded in `smartShopping()` by the household's OWN habit — `critical` for a staple (≥ 3–4 uses a month), `high` for something used at least monthly or bought twice, `medium` («Pianifica») for a one-off — because promoting every empty row filled «Urgente» with «prodotti che ho preso una volta sola oppure che uso molto raramente», and a badge that means everything means nothing. A row stamped `🛒 Esaurito` (`evershelfSpecIsDeliberate()`) follows the same graded scale through `resolveShoppingListItemUrgency()` (never `null`, never the calmest badge), and a product never bought nor used stays in the suggestions (`low`). The screensaver's shopping sentence obeys the same rule: `_ssFactCandidates()` **ranks by urgency before naming** the two «più urgenti», because the list is ordered by when a row was added | | Recipe archive (chat / generate) | `recipesArchiveUpsert()` + `recipeArchiveContentHash()` in `api/index.php` / `api/database.php`; `recipes.content_hash` prevents clones; `useRecipeIngredient()` / scale X÷Y UI in `app.js` | | Which engine generates a recipe | Pressing «✨ Genera Ricetta» asks (`#recipe-engine-choice`): «✨ Genera una ricetta nuova con l'AI» or «📚 Prendi una ricetta dal ricettario Mealie», and the answer travels as `recipe_source` in the `generate_recipe_stream` payload — `recipeRequestedSource()` (`api/lib/mealie.php`) honours it per request over `RECIPE_SOURCE`, so «auto» (ricettario first) can never answer in place of the AI the household pressed. Only configured engines are drawn; one engine → no question. The sheet names the source (`recipes.source_ai` / `recipes.source_mealie`) so the two promises are never confused | | A ricettario recipe must be cookable | `mealieRecipePantryCoverage()` counts the ingredients that are not free staples (water/salt/pepper/oil) and matches each against a pantry name **with `recipeScorePantryMatch()`, the same matcher `recipeEnrichIngredientsFromPantry()` links with (`RECIPE_PANTRY_MIN_MATCH_SCORE`)** — the two used to disagree, so a dish was counted as covered and then had that ingredient deleted. `mealiePickRecipe()` refuses a dish that leaves more than `MEALIE_RECIPE_MAX_MISSING` (default **0**) missing and needs ≥ 2 on the shelf, ranks by fewest missing, and logs `mealie_pick` / `mealie_pick_no_match` (title, missing names, coverage, how many candidates were skipped) — the household's report was «mi propone ricette senza senso con ingredienti che non ho» (measured: 2 of 27 recipes cookable on the field pantry). The Mealie answer carries `pantry_coverage` and the sheet prints «✅ Tutti i {n} ingredienti sono in dispensa» (`recipes.coverage_all`). The AI side is scrubbed by `recipeEnforcePantryOnly()` and a result left with fewer than `RECIPE_MIN_PANTRY_INGREDIENTS` (2) real ingredients is refused (`error_not_cookable`), never rendered. No silent fallback: `mealie_no_match` brings the question back | | A recipe that lost an ingredient REMEMBERS it | `recipeEnforcePantryOnly()` deletes every ingredient the pantry cannot link, and `recipeAttachShoppingSuggestions()` now records that list **always** (not only with `recipe_shopping_mode` on): a scrubbed recipe used to look complete, so the screensaver proposed a «pizza margherita» whose pizza had been deleted and the sheet showed no missing line at all. `_recipeArchiveMissingInfo()` counts those rows as missing (`scrubbed`, named in `items`), refuses `allInPantry` while one exists, and stops counting a suggestion the household has since bought (`_recipePantryHasName()`: every significant token must sit on ONE live product name, so «Pizza alta regina» never covers «Pizza margherita»). The live shelf uses `isInventoryDepleted()` (a trace is not stock), the sheet prints `recipes.missing_scrubbed` («La dispensa non aveva: …»), and the server logs `recipe_ingredients_scrubbed` with the names | | Genre in the article title | `api/lib/product_kind.php` + `mergeIncomingProductFields()` (the single title choke point) + `products.kind`; dictionary shared with `computeShoppingName()` | | Titles with HTML entities | A catalogue escapes a name once and an old import escaped it twice, which is what printed `Marmellata di "Limone…"` in the pantry and in the history. `productTitleDecodeEntities()` runs inside `productTitleCapitalize()` (the single title choke point) and decodes until the string stops changing (4 passes max), the client's `decodeHtmlEntities()` does the same, and `migrateDB` repairs the rows already stored escaped (`migration_decode_title_entities_v1`, products + transaction notes, logged as `titles_entities_decoded`). Never store an escaped title and never `escapeHtml()` twice. | | Singular title ↔ plural pantry | `productKindSingularizeName()` (stored title), `productNameForPieces()` + `display_name` in `listInventory()`, `productKindUnitCountsPieces()` | | Automatic favourites | `api/lib/auto_favorite.php` (`maybeAutoFavorite()` on every `inventory_use`), `products.favorite_user_override`, maintenance action `products_apply_auto_rules` | | Correct a scanned title/brand | `showAddForm()` → `_renderAddProductPreview()` / `_commitAddProductRename()` in app.js (`name_user_set` locks the user name) + the AI card `_showAiMatchChoices()` | | An AI identification asks for the barcode | `_showAiMatchChoices()` carries `_aiBarcodeAskHtml()` — «Questo prodotto ha un codice a barre?» with a neutral «📷 Sì, scansionalo» / «No, senza codice» — because an AI reading knows the pack, not its number, so the article used to arrive with no barcode at all and the next scan of the same pack asked the AI again. «Sì» parks the card (`_aiMatchPanelPause()` keeps the draft and the candidate list: the read IS the answer) and arms the scan page's one-code box (`_syncBarcodeVerifyUi()` paints both jobs: `_barcodeVerifyTarget` and `_aiBarcodeWaiting()`); the read returns into the card (`_aiBarcodeAccept`) and `_aiBarcodeAttach()` writes it on the article the moment it EXISTS — called by `_openAiSavedProduct()` and `_selectAiProductCandidate()` — always through `product_barcode_set`, never `product_save` (the catalogue's merge point: a code sent through it renames/merges two articles). A code another article owns is refused (`audit.assign_taken`) and named, an article that already states a DIFFERENT code keeps it (that is «Verifica barcode»'s job), the device teaches its resolve table (`_barcodeApplyNewCode`), the typed code is the door of a device without a camera, the demo hides it, and leaving the scan page ends the identification (`_clearAiMatchPanel()`) | | A notice never kills the decode loop | `onBarcodeDetected()` must either navigate or call `resumeScanner()`: the read that reaches it has ALREADY stopped the loop that confirmed it. The food panel's medicine cross-hint («Questo è un codice farmaco: aprilo dalla dispensa dei farmaci») returned with the loop dead, so after ONE such notice nothing was read again — a normal pack included — until the scan page was left and re-entered («non mi riconosce più i prodotti normali»). And the branch asked the schema whether the read was PACKAGING, where Italy's Laetus rule (`^[0-9A-Z]{4,8}$`) matches every **EAN-8** — a small pack's own barcode was announced as a drug. It now resumes the scanner, asks only for a real DRUG number (`_medNationalCode`), checks `_localRowForBarcode()` first (a held code is a PRODUCT, not a drug) and hides itself on the first food barcode | | «Prodotto non trovato» is ONE answer, with a pause and «🔄 Riprova» | A code no catalogue knows stayed in frame, so it was re-confirmed on every frame: a vibration and the same toast many times a second («mi continua a vibrare e dire che non trova»). `_scanReportNotFound()` stamps the code (`SCAN_NOT_FOUND_COOLDOWN_MS` = 3 s), `_scheduleScanResume()` brings the decoder back ONCE through a timer (never by restarting the loop on the same frame, which reads it again in a few milliseconds), a read inside the window is dropped in silence, and the toast is `showActionToast(…, t('btn.retry'), …)` for 6 s: it clears the stamp and asks again at once. The timer never restarts a camera a sheet / the AI card / the one-code box / a shopping modal owns (`_spesaScanUiBlocked()` included) | | Verify / update the barcode of an article | The product sheet's `_itemDetailBarcodeHtml()` block (code + «📷 Verifica») → `_barcodeVerifyStart()` → scan page in one-article mode (`#scan-barcode-verify`, `#page-scan.is-barcode-verify`) → `onBarcodeDetected()` → `_barcodeVerifyHandle()`: same code (GTIN variants of `_barcodeCandidates()` ↔ `barcodeLookupCandidates()`) says so and writes nothing, a different one is written through `product_barcode_set` (one field) and remembered by `_barcodeApplyNewCode()` (`_barcodeForgetCode` + `_barcodeRememberProduct`); a code another article owns is refused (`barcode_already_used`). A medicine has no door, and the demo hides it | | A scan of a known article opens the sheet, and the camera page steps aside | `_finishBarcodeResolved()` → `_scanStepAside()` (app.js): the `scan` entries are dropped from `_pageHistory` and `showPage()` goes back to the page that opened the scanner BEFORE the product sheet (or the «Quale confezione?» chooser) is painted, because the scan page stayed underneath with a stopped, black viewport above the sheet («il popup della fotocamera sotto si deve chiudere»). An empty history falls back to the pantry; a spesa / shopping trip (`fastPath`) keeps its camera. | | Add to pantry needs a catalog id | `submitAdd()` → `_ensureAddProductRow()` (creates the row with `name_user_set`), `_apiErrorText()` for `error_key` answers, `addToInventory()` in api/index.php | | Duplicate products — never merge two different articles | `productNamesSameArticle()` (+ `productNameStem()`): the same name at another number is one row, but a shared **substring is not** ("Pomodoro" ⊄ "Passata di pomodoro"), and the loose head rule needs a barcode. A **loose vegetable never reuses/merges with the pantry's tin of the same word** (`productRowClashesWithLooseProduce()`: `isSoldByPieceProduct()` + the row's category) — used by `collectDuplicateProductIds()` (which DELETES a row) and `findDuplicateProductId()` — the AI-name ranking is `aiProductNameRelevance()` / `aiProductSuggestRank()`, the client drops candidates of another nature with `_aiMatchKeepSameNature()`. **The brand is a VARIANT, not an identity**: an exact name (or the same article at another number) reuses the row across brands, so a shopping trip cannot create one product per package ("Banane [SCB]" + "Banane [Iper Poli]"); the kept row is the one the household already uses (barcode → picture → real category → stock, `productCanonicalScore()`), every cross-brand reuse is logged (`product_reuse_brand_variant`) and the rows created *before* that rule are merged by `php scripts/consolidate-duplicate-products.php` (`--dry-run`, `VACUUM INTO` backup first, and it SKIPS any group whose stocked rows disagree on the unit: that is a conversion, not a merge) | | A label read is not a quantity | `_aiSuggestedUnit()` / `_aiStorageFields()` (app.js): produce never arrives as `conf` (a prepared salad keeps its bag, and what is sold by the piece is the vocabulary's call — `vocabIsPieceProduce`), and a starting amount is never below `_addMinQtyForUnit()` (a label misread gave "1 g" of broccoli and "2 ml" of cream, which the form then refused) | | Which category does a name belong to | `guessCategoryFromName` (app.js) and `guessCategoryFromNamePHP` (api/index.php) are **one vocabulary written twice**: the PHP one is a PORT of the JS one (same order, same patterns — port every change to both). A bare "Pomodoro"/"Pomodorini"/"Carote" is produce (`verdura`/`frutta`, unit pieces), only the preparations are `conserve` ("Passata/Pelati/Sugo/Polpa di pomodoro"); stems, no trailing `\b` (`pomodor`, `carot`, `mel[ae]`), and accented words close with `(?![a-z])` because the JS `\b` is ASCII-only while PCRE's is not ("Caffè"). An 80-name probe list covering the whole grocery is locked by, which runs the app's own JS in node against the PHP guesser | | Minimum quantity of a NEW pantry row | `inventoryMinAddQuantity()` (g/ml 20, kg/l 0.02, pz 1, conf 0.25) enforced in `addToInventory()` (`error_key error.quantity_below_min`), mirrored by `_ADD_MIN_QTY_BY_UNIT` / `_addMinQtyForUnit()` in app.js (`updateAddQtyStep()`, `onAddUnitChange()`, `submitAdd()`); tomatoes are piece produce in `isSoldByPieceProduct()` / `suggestCategoryUnitQty()` | | Recorded spend (dashboard) | `spendAdd()` / `getSpendStats()` in api/index.php + `data/shopping_spend.json` (append-only, one amount per spesa session, asked when the session starts); every write is logged (`event api_spend_add`, with the resulting month total) because the ledger has no correction UI | | "Spesa stimata" of the list (one figure only) | `_computeAllShoppingPrices()` is the only producer: the server-side resolution (`_resolveShoppingPriceItem()` from the smart cache) wins and the caller's quantity is only the fallback; one key `_shoppingListPriceHash()` and `data/shopping_total_cache.json` holds one bucket per key (`_pruneShoppingTotalEntries()`). The quantity is capped by `shoppingCapPriceQty()` — **one pack per line** (the product's own size when the pantry row says it, else 500 g / 1 l), one `conf`, a bag of `pz` (6) — mirrored by `_capPricePayloadQty()` in app.js: pricing the plan horizon read «ca. €344» on an 83-row list (1,4 kg of coffee, 1 kg of cheese) and now measures €161,13 on the 60-row field list. A total restored from `sessionStorage` (`_loadCanonicalTotalFromSession()`) is only a paint shortcut and dies when the stored row count no longer matches the list, or after 30 min with no list loaded | | Cron watchdog / notifications | `api/lib/healthcheck.php`, `api/lib/notify.php`, `cron_*.php` | | Actionable push — ✓ Usato / 🔥 Buttato from the notification (#122) | `api/lib/push_actions.php` (HMAC token `v1\|row\|action\|exp\|sig`, 12 h, one row one action) + `notification_action` (public, self-authenticating) + `sw.js` (`actions` + `notificationclick`) + a per-device inbox token (`webpush_subscriptions.inbox_hash`, minted by `webpush_subscribe`, kept by the page in localStorage and by the worker in the Cache API). `webpush_inbox` is public and authenticates with that token — before 2.2.0 it answered 401 to the worker and every push was a bare “EverShelf”. The write is `useFromInventoryCore()` (use-all / `Buttato\|spoiled`), so ledger, waste learning and shopping sync behave identically. One to three rows → one notification each with buttons; more → the aggregate line | | Printable monthly report (#103) | `api/lib/monthly_report.php` + `export_monthly_report` (GET, `?month=YYYY-MM&lang=xx`); `monthlyStatsData($db, $month, $topLimit)` in api/index.php is the ONE source of the month's figures (`monthly_stats` echoes it too). Print-first HTML, browser → Save as PDF, `evershelf-report-YYYY-MM`, no PDF dependency. Button in Settings → Sistema → Dati | | Freezer lifecycle — freeze / thaw (#286) | `inventory_freeze` / `inventory_thaw` + `api/lib/frozen_shelf_life.php` reading `data/frozen_shelf_life.json` (days per category slug). `frozen_at` + `pre_frozen_expiry` on `inventory` (migrations in `database.php`); the frozen date is WRITTEN into `expiry_date`, so dashboard, ICS and cron keep one column. Thaw = the sooner of now+48 h (`EVERSHELF_THAW_DAYS`) and a still-future original, plus one `expiry_alert` notification with `type: "thawed"` (which the actionable push turns into buttons). The genre gate stays the client's `data/storage_actions.json` table; a medicine is refused server-side | | `.env` bootstrap / pairing | `api/lib/env.php`, `api/lib/pairing.php`, `app_bootstrap` in `api/index.php` | | Seasonal produce | `api/lib/seasonal.php` + `data/seasonal_produce_it.json` | | Health / Fuel mode | `api/lib/health.php` | | Android Health Bridge (companion APK) | `evershelf-health-bridge/` — Kotlin, package `it.dadaloop.evershelf.health`, `versionName 2.1.0`. Five tabs (Today / Diary / Charts / Control / Info) in the **same six locales as the webapp** (`values/` + `values-it|de|fr|es|zh`, 260 strings each), with the day stored in a local SQLite queue (`HealthDb`), a **reachability gate** before every upload (`ServerReachability` → `health_bridge_hello`: a phone in the street has internet and no route to the LAN server, so "has internet" is never the question), OTA through `health_bridge_update` (LAN, from `releases/`) with a GitHub fallback and a **signature + versionCode** check before `PackageInstaller`. An update installs IN PLACE and the workflow proves it before publishing (`Guard — the APK must update the published app in place`: the new `versionCode` must beat `releases/health-bridge-version.json` and the v2 certificate must equal the one of `releases/evershelf-health-bridge.apk`, SHA-256 `36d84a43…cb25`). Errors go to the public `report_error` with `source=health_bridge` → its own river `data/logs/health-YYYY-MM-DD.log`. Its keep-alive FGS is started **only from a visible screen**: Android 15 refuses a `dataSync` FGS from `BOOT_COMPLETED`, which was one of the ways the old APK died. **And it cannot live for ever**: a `dataSync` FGS has a six-hour budget per 24 h, and when it is spent Android throws `ForegroundServiceDidNotStopInTimeException` into the app and kills the process — mid-pass, taking the scheduled sync with it (the field install uploaded every 30 min until 05:21 on 2026-11-28 and then stopped for eleven hours until somebody pressed «Sincronizza»). `KeepAliveService` stops itself after three hours, implements `onTimeout()` and returns `START_NOT_STICKY`. **A periodic work that ends badly is never repeated**, so `SyncEngine.syncNow()` answers instead of throwing, `HealthSyncWorker` only returns `success`/`retry`, and `SyncEngine.ensurePeriodic()` reads the real state of the unique work on every start and re-enqueues it when it is finished (`sync_schedule_revived`); a pass also re-reads the last three days the diary never got (`CATCHUP_DAYS`) and queues them. **And it also READS what only the server knows**: `health_bridge_summary` (X-Health-Token) answers the day `computeMealBudget()` gives the recipes, so Today draws «Oggi a tavola» (eaten / daily goal / left, hidden when the server says `enabled: false`), while `SyncEngine.readTodayLocal()` re-reads the phone on open (one Health Connect query, no upload) and the screen repaints — it used to show the previous pass's numbers. Built by `.github/workflows/build-health-bridge.yml` (signing secrets `HEALTH_KEYSTORE_*`) | | Frontend API wrapper | `api()` in `assets/js/app.js` (line drifts — `grep -n "^async function api("`). It **shares heavy reads**: `_API_READ_CACHEABLE` (inventory_list, products_list, stats, shopping_list, smart_shopping, the dashboard summaries…) answers a GET that is already in flight or arrived < 2 s ago, because the wall's boot asked for the same 136 KB `inventory_list` **eight times in four seconds** and the parse storm is what got its WebView renderer OOM-killed. Writes are never shared: any POST and `refreshAppDataAfterMutation()` call `_apiDropReadCache()` first. The real fetch is `_apiFetchJson()` | | A translation that carries markup | Some strings are HTML by design (`use.disambiguation_one_conf` «Finita `<strong>1 confezione</strong>` ({qty})», `scanner.camera_error_hint` «…fotocamera.`<br>`Puoi inserire…»): they are written RAW into `innerHTML` (or a template literal that lands there) and only the interpolated VALUE goes through `escapeHtml()`. Wrapping the whole translation in `escapeHtml(t(…))` or assigning it to `textContent` prints the tags to the household — the «usa / finito tutto» chooser literally read `<strong>1 confezione</strong>`. `scripts/i18n-audit.py` section **[5]** fails on that pattern (a bare `<` like «Peso < 10 g» is not a tag) | | i18n helper | `t()` (~line 1471), `loadTranslations()` (~1482), `_urlLangOverride()` (line 1417: `?lang=` wins over localStorage); anything PHP hands to the UI is a key (`error_key`, `hint_key`, `urgency_label_key`) | | Rate limits (429) | `checkRateLimit()` in `api/index.php` (line 111) + `data/rate_limits/`; the answer carries `error_key: error.rate_limited` + `retry_after` | | The product modal (one hierarchy) | `showItemDetail` renders it: a stepper (`_itemDetailQtyInit` / `_itemDetailStep` / `_itemDetailQtyLabel`) feeds `_itemDetailConsume` → `inventory_use` with the chosen quantity, then **one** primary (solid emerald), **one** secondary (emerald tint) and neutral support buttons (recipe, discard, extend expiry); barcode and timestamps live in the collapsed `<details class="item-detail-more">`, never in the middle of the card. The row itself carries a quick "Usa" + the ⋮ that opens this modal (`_rowMenuButtons`): extending an expiry is rare and must not own the row. The quick "Usa" opens THIS sheet (`quickUse`), so the sheet must carry what the old USE page had: the **¼ · ½ · ¾ · 1** chips (`_itemDetailFractionOptions` / `_itemDetailFractionsHtml` / `_itemDetailSetQty`, neutral chips, hidden when only one value is reachable). **The head is a picture and two lines**: the thumbnail is 64×64 with a 12 px radius (44 px could not tell “grano duro” from “integrale”), it is a `<button>` that opens the package photo full screen (`openProductImageLightbox` → `#image-lightbox`, Esc or a tap outside closes it, registered in `_OVERLAY_CLOSERS`) so an ingredient list or a lot number can be read off the box, and the title (1.14 rem / 700 / `--text-main`) is followed by the **brand on its own line** (`.item-detail-brand`) — never `Pan Bauletto (Mulino Bianco)` flattened into one grey sentence. The head also carries the **opened switch** (`#item-detail-opened` → `itemDetailToggleOpened` → `inventory_update` with `opened_at` / `opened_at_clear`; the expiry is re-dated on the opened clock only when it was an estimate, never over a typed date, and a medicine keeps `med_open`). **A `pz` row is judged by the FRACTION of a piece, never by `default_quantity`** — on a `pz` row that number is often the pack's WEIGHT (Pan Bauletto: `pz` with `default_quantity` 400, so 20 pieces read as «0.05 of a pack → opened» while 5 pieces fell inside the tolerance as «sealed»: the two answers the wrong way round) — and using PART of a perishable `pz` row stamps `opened_at` in `useFromInventoryCore` (the bag of sliced bread really is open; a non-perishable, the 9999 sentinel, never is, and **loose produce — `frutta`/`verdura` sold by the piece — never is either**: an apple is not a package, «che non sia ovviamente frutta e verdura»; a bag sold by weight or a `conf` bag of salad still opens). And, when the same article stands in other packs, the **«Anche in» block** (`_itemDetailOtherPlacesHtml`: one line per ROW — mark, place, stock, **expiry** — read from the whole pantry (`_allInventoryCache`), never from the place the list is filtered to, with the line that **opens that pack's sheet** (`_itemDetailSwitchPack`) and the ✏️ that edits THAT row), because a barcode points at an ARTICLE, not at a package: the sheet also leads with the total across the packs (`_itemDetailTotalPacksHtml`, «📦 38 pz in tutto») — «6 pz» on a shelf that also holds a 30-pack is half the answer. **And the pack on the SCREEN is the pack that is written**: `_itemDetailConsume` sends `inventory_id`, `useFromInventory()` hands it to `inventoryUseRowPlan()` / `useFromInventoryCore()` as `$onlyRowId`, so a use recorded from the sealed bag on screen is never applied to another room's opened pack (the resolver's opened-anywhere precedence is the default for callers that do not choose). A scan opens the sheet on the OPENED pack — `_packPickOrder()` / `_inventoryRowsForProduct()` order every pack the way a shelf is read (opened first, oldest open first, then the place the pantry has open, then the nearest date) and `_inventoryRowForProduct()` / `_inventoryIdFor()` both use it — and asks «Quale confezione?» (`_scanPackNeedsChoice()` / `_showScanPackChoice()`, `inventory.pick_pack_title` / `_lead` / `_opened`) only when the choice is genuinely the household's (several rooms with none opened, two opened packs); a pin whose pack was emptied meanwhile is dropped (`api_inventory_use_pin_stale`). The same grammar is shared by the edit sheet (`.edit-inventory-modal`: body at `85vh` with `overflow-y: auto`, 20 px padding, 14 px between groups and 6 px under a label) and by the recipe «Usa» head (`_recipeUseHeadHtml`). The recipe **“Usa” sheet** draws those same chips — `_fractionChipOptions()` is the ONE builder, `_recipeUseFractionOptions` / `_recipeUseFractionsHtml` / `_recipeUseSetFraction` are the household's — capped by what the place the sheet has open really holds, so a product with nothing to split on that shelf (no whole unit, no part of a pack) gets no row at all and a chip never asks for more than the shelf can give. Its head is the product sheet's own grammar (`_recipeUseHeadHtml`: thumbnail, name, brand, category, place, opened days, vacuum, expiry verdict of the row the selector has open — `_recipeUseSyncHead` repaints it when the place changes), never a bare title. A `conf` row whose pack is sold in g/ml has TWO units and must offer both: `_packMeasure()` reads the pack (`default_quantity` + `package_unit`), the **Confezioni | ml** switch (`_itemDetailPackSwitchHtml` / `_itemDetailSetEntryUnit`) moves the field between packs and the pack's own measure, the chips become amounts of the pack (250 · 500 · 1000 ml · Tutto), the scale is offered for that row too and writes the **fraction of the pack** (`_scaleApplyToItemDetail`, density applied for an ml pack), and a number typed in the wrong unit is understood instead of clamped (`_itemDetailOnQtyInput`: `250` in a "Confezioni" field of a 1 l row = 250 ml, never "ho finito tutte e 12"). `_captureQtyFor` converts a dictated amount through the same pack, so "ho usato 250 ml di latte" is 0,25 confezioni and not one whole pack. **A use is measured on the PLACE, and the write honours that figure**: one article can stand in several rows of the same place (a pack per purchase, an opened one, a leftover), so `inventory_use` builds `inventoryUseRowPlan()` — the resolver's own pick first, then the rest of that place — and applies it through `inventoryApplyUsePlan()` (one write per pack, ONE answer to the client: merged `transaction_ids`, the last `opened_id`, `total_remaining` of the final write). Before it, a request was capped at the single row `resolveInventoryUseTarget()` handed over: the sheet said «hai 608 g» and the ledger recorded 108 g («le quantità sono diverse da quelle realmente disponibili»). `use_all` clears the WHOLE place, not one pack, and «Tutto, ovunque» keeps its own `__all__` branch. A one-row place takes the exact path it always took (dedup, fallback, response), and the recipe sheet reads the shelf the ingredient line was measured on (`inventory_list?include_depleted=1&for_recipe=1`). The remainder of a partial use is a pack of its own, so the sheet **always asks WHERE it went** (`showMoveAfterUseModal(…, { stayPut: true })` → `_showMovePrompt`): the presumed answer comes from the product's history and then from its **genre** (`_preferredMoveChoice`), the control carrying it drains with the seconds printed on it — **the clock is the confidence** (`_moveHistoryConfidence()`, last five choices × the source, the genre weighing 0.55; `_movePromptSeconds()` maps 0..1 linearly to **6–20 s**: four identical choices = 6 s, one sample ≈ 9 s, a genre ≈ 10–13 s, no history = 20 s and the pack stays where it was) — and any touch stops the clock. The floor was 2 s and that is a FLASH, not a question: with the habits the app had taught itself almost every product sat on it (361 learned places on the field install) and the household reported «non mi chiede più dove metto il resto». And a clock that runs out is NOT an answer: `fromClock` keeps `_recordMoveLocChoice()` silent, so the app's own presumption cannot become the "habit" that shortens the next question. A move is never applied in silence, and ✕ applies nothing. **A finished product is never asked about** (“se è finito è finito”): `_movePromptHasPortion(remaining, unit)` skips the question when nothing is left, when the leftover is a trace the pantry itself calls finished (`isInventoryDepleted`), and when a `pz` row still holds whole pieces — no pack was opened, and “la confezione aperta” about three eggs is a lie (a half piece still asks); `_itemDetailConsume` hands it `total_remaining`, the recipe flow the product's total, so the question is about what really stays on the shelf. The anomaly banner's primary is `confirmBannerAnomaly` (`✓ Confermo {inv_qty}` — it CONFIRMS the physical stock and only acknowledges the notice, writing nothing: the ledger figure is a guess, and the household is the one looking at the shelf; "Modifica quantità" opens the sheet for a real correction) — never a nameless "Giusta" — and **no banner hides its actions behind a ⋮**: every entry renders them inline (`.alert-banner-actions` wraps) and every entry carries a Modifica, | | Capture (voice) — **SHELFY** | The assistant has a name, used in every string (caps), and **no voice of its own**: TTS is the recipes' feature (`_speakBrowser`), the capture never speaks. **It never navigates either**: `_shelfyRunConsume()` closes the sheet and shows the floating `.shelfy-confirm` card (`_shelfyOfferConsume()`: the avatar, “Registro {qty} di {name}”, an emerald bar draining right→left for 10 s, Modifica / ✕ Annulla). The bar emptying writes `inventory_use` (`_shelfyApplyConsume()`); **Modifica** stops the clock and opens the compact product sheet at that quantity (`showItemDetail(invId, productId, qty)`); “ho finito …” (use-all) opens that same sheet, where the slide-to-confirm stays the user's (`_shelfyOpenAdd()` never writes either). The legacy full-page `#page-use` is reached only by the guided flows that still drive its fields — **no capture path goes there**, which is what removed the ← Indietro header, the purple recipe button and “Tutte una parte” from the voice flow. Every countdown shows its seconds: `_shelfyArmButton()` paints `.shelfy-armed` (the mint fill) plus `.shelfy-arm-count` (the number), and any pointerdown/key cancels it so the tap is the user's; a promise of “10 seconds” with nothing moving reads as a frozen app. A second intent, **shop**, is listed *before* `add` in `vocabCaptureLexicon()`: “aggiungi le uova alla spesa” is a shopping line (`_shelfyAddShopping()` → `shopping_add`), “aggiungi il latte” is still a pantry add. `_openCaptureSheet()` shows the presentation once per device (`SHELFY_INTRO_KEY`, reopenable from `#shelfy-help-btn`), then `_captureStartVoice()` (ONE session per tap, `continuous = true`; the sentence is handed over **only** when the session our own silence deadline stopped — `_CAPTURE_SILENCE_MS` 1.4 s once the newest result is final, `_CAPTURE_SILENCE_INTERIM_MS` 2.2 s while the engine is still revising it, flagged by `_captureVoice.stopRequested` — while a session the **browser** ended mid-sentence is **resumed** instead of submitted (`_CAPTURE_RESTARTS_MAX`, bounded), because submitting that one is what cut "Ho usato 2 arance" at "Ho usato 2" and "Aggiungi il latte" at "Aggiungi il"; the transcript is REBUILT from `ev.results` on every event and joined **per word, ignoring case** (`_captureJoinText`: Chrome re-delivers finished results, Chrome Android restarts the list per phrase with the phrase already cumulative, and the interim is capitalised while the final is not — appending printed "ho ho ho usato ho usto ho usato una", "ho consumato ho consumato ho consumato 250 …" and "Ho mangiato ho mangiato una mela", and comparing *characters* swallowed the last word: "aggiungi il" + "latte" → "aggiungi il atte"), interim included, finals + the interim text the browser never finalised, `_captureSpeechLang()` = device language → UI language). **A voice turn is a visible state machine** (`_captureSetState()` / `_capturePhase()`): `listening` (the avatar fills with the live level, the bars move, “SHELFY ti ascolta…”), `thinking` from the instant the sentence is closed (the fill and the bars stop, the wrapper ring becomes a spinner, the status says “Sto elaborando…”, the button is `aria-busy`) and then the card — a live test measured ~7 s of a perfectly still screen between the last word and the card, which is what this removed. The transcript lives in a bubble (`.capture-bubble`: avatar + high-contrast frame with a tail) and the `[Esegui]` field is **not part of the voice view** (`_captureShowType()`: a neutral “Preferisco scrivere” link opens it, and it opens by itself only when the browser has no recogniser or the microphone was denied), because a field under the avatar reads as “press me to confirm what you just said”.`_captureSubmit()` routes only through `_captureIsActionable()`, and `_captureNotUnderstood()` is the one ending for a sentence it cannot act on: it hides the "Ho capito" chips, says "non ho capito", keeps the sheet open and shows the **fallback card** (`#capture-fallback`): the sentence heard is quoted back and the two honest ways forward are inline — the emerald **💬 Continua nella Chat** (`_captureContinueInChat()` → `_shelfyHandOverToChat()`, which writes the transcript into `#chat-input` and sends it, so nothing is said twice) and a neutral **🔄 Riprova a voce** (`_captureRetryVoice()`) —, because a sentence SHELFY cannot map is not a closed door. **A turn has a clock** (`CAPTURE_TIMEOUT_MS` = 15 s): the status line narrates what it is doing (`capture.thinking_step_2` → “Interrogo l’inventario…” at 4 s, `thinking_step_3` → “la risposta sta impiegando più del previsto” at 8 s), `_captureTimeout()` closes the turn with the fallback card, and `_captureTurnId` drops an answer that arrives late (the `inventory_list` fetch carries its own 12 s `AbortSignal`), so no sheet can pop up behind the card. **No capture path ever opens the "new product" form** (`startManualEntry()`: creating an article is the user's decision, never the end of a wrong parse), and the sentence it heard is the biggest text in the sheet (`.capture-transcript`, 1.06 rem, semibold, tinted block). `_captureParse()` reads fractions and eaten/drunk/used verbs; `_captureScoreName()` ranks by POSITION (the word leading the name is the product, a word buried in a longer name is a derived article → 0.55, no confident match). Ambiguity shows four candidates and the closest drains for **10 s** (`_shelfyArmButton`, any pointerdown cancels). **Its lexicon is DATA**: intent words, spelled numbers, units (with their multiplier: `etti` → g ×100), fractions, "all of it" and stop words live in `api/vocab/<lang>.json` → `"capture"` (the recogniser tag is in the same file's `"locale"`), reach the browser through `assets/js/vocab.generated.js` and are merged by `vocabCaptureLexicon()` in `assets/js/core/vocab.js` (current language first, all six shipped) — an Italian sentence works on an English UI; `_captureSpeechLang()` takes its tag from the data, never from a hardcoded map. **The fallback card asks the TRUE question**: a sentence SHELFY could not map is not one it “understood”, so it now says `capture.fallback_ai` («Non riesco a capire la richiesta: posso passare il tuo messaggio a un agente AI?») with the chat door, or `capture.fallback_no_ai` («Mi dispiace, ma non riesco a capire la tua richiesta») with **no** chat door when no provider is configured (`_chatAgentAvailable()` = `_geminiAvailable` and not a demo); a command it did understand but could not complete (`capture.no_product`) keeps the quote (`capture.fallback_lead`), which is why `_captureNotUnderstood()` passes its reason. **A door nobody can open is hidden** — the retry button needs `_captureRecognizerCtor()` (the kiosk `display: none` is gone: the wall has a native recogniser since 1.7.39) and `.capture-fallback-actions button[hidden]` keeps that win over the button rule. Closing always hides the sheet **before** the cleanup (`_captureVoiceStop()`), and the test fails if a `_capture*()` call has no definition | | SHELFY's avatar | `assets/img/shelfy/shelfy-avatar.png` (512, transparent), `-192` and `-96` — generated once from the artwork by removing the flat white sheet with a **flood fill from the border** (a threshold on the whole image would eat the robot's white panels; the fill only reaches the paper that touches the edge), then cropped, squared and resized with LANCZOS. It is in the `sw.js` shell and painted in five places: the **centre of the bottom nav** (`#nav-capture-btn`, `clamp(40px, 10.6vw, 54px)` inside the emerald circle), the capture sheet head (`.capture-head-avatar`, 26 px, *outside* the `data-i18n` h3 so `translatePage()` cannot wipe it), the intro hero (`.shelfy-hero-avatar`, 104 px, floating over the breathing ring — the 👋 wave is gone because the drawing already waves), the 10 s confirm card and the **foot of the splash** (`.preloader-shelfy`, 56 px under `.preloader-powered`, on its own breathing ring; decorative and `aria-hidden`, never a boot stage, and 44 px under `max-height: 620px`). Never replace it with a food emoji | | Cooking mode: the microphone is OFF until a tap | `startCookingMode()` sets `_cookingVoiceAuto = false` and **never arms the recogniser by itself** (it used to start 5 s after the recipe appeared: Chrome's start chime over the recipe, for a microphone nobody asked for). A card anchored to the 🎤 explains, **on every open**, what it does and that it is off — with the real words of `vocabCookingVoice()` — and disappears by itself after **5 s** (✕ or a tap outside closes it too; `#cooking-voice-hint`, no `localStorage` gate any more). `_cookingVoiceArm()` is the only door to `_cookingVoiceStart()` and returns immediately unless `_cookingVoiceAuto` is true, which only `_cookingVoiceCommand()` (the tap on the button, `aria-pressed`) turns on; a second tap mutes. After a heard command the session re-arms once the step's TTS has finished (`_COOKING_VOICE_AFTER_CMD_MS`), so a hands-free cook still works, and `closeCookingMode()` resets everything to off | | Chat → ricette: the ingredient list is the CHAT's | The chat has **no «Usa» buttons** (removed on request): `formatChatReply()` only formats markup and the one door a recipe reply keeps is «📥 Trasferisci alle ricette» (`chatTransferToRecipes`). The transfer parses the reply's own «Ingredienti» section (`recipeParseChatIngredients()` in api/index.php: bullets, `Nome: 200 g`, `200 g di nome`, `2 uova`, `½`, `1/2`, `80-90 g`, `q.b.`, group headings skipped, six languages, inline lists) and that list REPLACES the model's, which only shapes title/servings/times/steps. `recipePostProcessGenerated(..., ['keep_unlinked' => true, 'preserve_names' => true, 'clamp_qty' => false])` links it to the shelves without renaming, deleting or clamping, and `recipeChatRestoreQtyText()` puts the chat's own wording back (`qty_number` stays in the pantry unit, which is what «Usa» needs). Every row carries `verbatim`, which the BROWSER honours: `enrichRecipeIngredientsStock()` links without renaming and skips the per-serving cap, `_normalizeRecipeIngQtyNumber()` / `_computeRecipeIngStockHint()` leave `qty` alone, and `renderRecipe()` PRINTS unlinked rows (plain, «non in dispensa»). `chat_to_recipe_ok` logs `from_text` / `from_ai` / `kept`. | | Voice / TTS (one engine) | `_speakBrowser(text, opts)` is the only local voice: cooking steps (`speakCookingStep()`) and SHELFY share it; `_pickTtsVoice(voices, wantLang, selectedName)` is the pure rule (the Settings voice when it speaks that language → an offline voice of that language → any offline → the first). Never hardcode a language, never build a second `SpeechSynthesisUtterance` outside it | | Dialogs: Esc + focus trap | `_closeTopOverlay()` + `_overlayFocusables()` (one capture-phase `keydown` for every `.modal-overlay`): Esc closes the dialog on top through `_OVERLAY_CLOSERS` (so state is cleaned — `_closeCaptureSheet` stops the microphone), Tab/Shift+Tab cycle inside it, and the focus returns to `_lastFocusedOutside`. The first-run setup wizard is never closed by Esc. Visible = `getClientRects()` (a fixed overlay has no offsetParent) | | Alert rows open on tap (phone too) | `_bindAlertItemsHoldOpen()` → `_bindRowHoldOpen()`: a tap opens the sheet, a hold also works, a pointermove > 12 px cancels, a tap on a child button never opens, `tapToOpen: false` for lists where a tap means something else; all four lists incl. `stale-list` are bound | | The scanner stream is clean | The camera viewport carries **one** overlay: `.scan-lock-box`, placed where a barcode was actually read (`_setScanTrackTarget(rect,'lock')` → `_showScanLockBox`) and holding still. The moving line, the particle cloud (`#scan-ai-cloud`, whose `_updateScanCloudScout()` is now a no-op — it sampled the frame every 180 ms), the pulse ring, the dots, the lookup spinner, the live digits, the ✓ flash, the corner brackets and the `2×` badge were deleted: they helped nobody aim and repainted the feed every frame. The status text and the camera controls (torch / shopping / flip) live **under** the picture in `.scan-below-bar`, never on top of it | | The scanner never warms the AI classifier | `showPage('scan')` must **not** call `_getCategoryPipeline()`: that pulls 0.9 MB of transformers, instantiates the ONNX Runtime wasm and fetches `vendor/transformers/Xenova/all-MiniLM-L6-v2/onnx/model_quantized.onnx` (**22.9 MB**) while `getUserMedia()` is starting — it is what the `[LONGTASK] ~7 s page=scan` line measures, and on the wall it read as "the camera does not open" and, once the renderer died, "the app restarted". `classifyCategoryByEmbedding()` loads the model on demand (its two callers fall back to `guessCategoryFromName`) and returns `null` on a kiosk | | Opening the scanner on a kiosk | `initScanner()` does not schedule `_ensureTesseractWorker()` there (multi-megabyte wasm while the household is aiming): every OCR pass awaits the worker itself. `preloadBarcodeEngines()` is skipped on a kiosk for the same reason, and `content-visibility` is **not** an optimisation for a long list: an off-screen row is laid out at the intrinsic estimate (90 px) while the same row is 102 px in view, which makes the list height, the scrollbar and `scrollIntoView` lie | | An AI identification is never interrupted | `_triggerManualAiScan()` → `_tryGeminiNumberOCR()` / `_tryGeminiVisualBarcode()` call `pauseScanner()` for the WHOLE turn, `onBarcodeDetected()` drops a read while `_numOcrRunning || _aiBarcodeVisualRunning` (a read used to run `_resetAiFallbackForNewScan()`, bump `_aiVisualGen` and make the answer "stale"), and a turn that ends without opening anything calls `resumeScanner()` itself | | A pantry row: tap opens, scroll never does | `_initInventoryRowSwipe()` (the only touch grammar of `.inventory-item`): `INV_TAP_SLOP_Y = 10` px of vertical travel turns the gesture into a scroll, `INV_TAP_SLOP_X = 24` keeps a thumb landing askew a tap, a quick tap (≤ 300 ms) that moved ≤ 18 px and **scrolled nothing** is still forgiven, `pointercancel` is never a tap (the browser took the touch for the scroller), and the decision asks `.inv-scroll` whether its `scrollTop` actually changed — that is what stops the sheet from opening at the end of a scroll. CSS keeps `touch-action: pan-y` on `.inventory-list` / `.inv-row-content` (geometry lives in `style.css`, the themes keep the colours). The swipe is **right only**, needs ≥ 52 px and a clearly horizontal run (`maxDx ≥ maxDy × 1.8 + 12`) and opens the same product sheet (`editInventoryItem`) a tap does: the left swipe and its «Usa · Butta» chooser are gone. **The gesture that OPENS a sheet must not also press a button inside it**: `pointerup` precedes the browser's synthetic `click`, and that click is hit-tested at dispatch time — where the sheet now sits. Measured on a 393×860 phone: a tap at y=712 with the sheet's primary «✓ Usa 25 g» at 689–734 wrote `inventory_use { quantity: 25 }` by itself («appena premo parte di default un uso di 1 unità senza chiedermi nulla»), so `_initInventoryRowSwipe()` and `_bindRowHoldOpen()` arm `_guardTapClick()` (one shot, 450 ms) before opening — a later tap is always the household's, and a deliberate press still writes. The row also opens **its own** pack (`data-inv-id`), not the first one of that product in that place, and a `✓ Usa` never falls back to the legacy `#page-use` when the row is missing from the client cache: `quickUse()` reads the row from the server and opens the same sheet | | One row layout for every Home list | «In scadenza», «Scaduti», «Aperti» e «Dimenticati» are three tabs of the SAME block, so they must draw the same card: `[photo] [name + brand / place · 📦 stock · extra] [state badge] [✓ Usa] [⋮]`. Reported: «la lista "In scadenza", "Aperti" e "dimenticati" usano layout diversi… quella in "In scadenza" è buono usa quello» — «Aperti» had no meta line and no actions at all, «Dimenticati» a `📅 12/03/2027` pill and its own buttons. ONE builder for the pill (`_alertStateBadge(days, {date, vacuum, cls})`: compact relative verdict, classes `today/expiring/expiring-soon/expiring-later/expired`, exact date in the tooltip) and ONE for the actions (`_rowMenuButtons(item)`, which accepts `inventory_id` for the forgotten rows). The extra fact of a list goes in the TEXT line through `_alertItemMeta(item, extra, {qtyText, extraTitle})`, never as a fourth chip. Measured in headless Chromium at 360 / 393 / 800 px: every row 132 px, text block 62, action line 34. **«e altri N…» is a door, never a footnote**: the block keeps what does not fit above the nav in `_esPending`, and the note is a real `<button class="alert-more-note">` that `_expandAlertList()` turns into those very rows (re-bound, tap/hold work) and then removes — reported: «scrivi "e altri x.." — se premo lì dovrebbe darmi gli altri x», while it was a `<div>` with no handler. One delegated listener per LIST (`_esMoreBound`), because `innerHTML` is replaced on every paint, and the stock-hub badge / «Scaduti» subtitle are repainted with what the block now shows | | One soft tint per banner reason | Asked for: «per ogni motivazione per cui crei un alert banner in alto puoi usare uno sfondo tenue diverso?». The strip used to be neutral for every kind, so an open yoghurt, a loss check and a prediction were the same card with different words. Every reason now sets one variable — `--banner-hue` — on `#alert-banner`'s class (`banner-opened` + `is-warn`/`is-critical`/`is-cook`, `banner-expired-danger/-warning/-ok`, `banner-review`, `banner-prediction`, `banner-anomaly`, `banner-finished`, `banner-dup-loss`, `banner-no-expiry`, `is-medical`), and `surfaces.css` paints ONE soft wash of it (12 % → 4 % over `--surface-bg`, 24 % → 8 % in dark). The theme still owns the paper (light/dark/Corporate/Elegant) and the left rail keeps the urgency (`is-critical` is red whatever the reason hue is). The «quantità insolita» strip had no class of its own — it is `banner-review` — and `style.css` no longer declares banner gradients: one palette, in `surfaces.css` | | The Home lists wait with SHELFY, like the shopping list | Asked for: «nella sezione liste quando viene generata una lista c'è una bellissima animazione con SHELFY eccetera, perché non l'hai fatta anche per in scadenza, aperti e dimenticati?». The skeleton existed but lived in a hidden panel: `#stock-hub` starts `hidden` and `_syncStockHub()` computes its visibility from the rows it finds (zero while the request is in flight). `_stockHubLoading()` now shows the hub and paints `_listSkeletonHtml()` into **all three** lists (expiring, opened — which had none — and stale), keeps ONE panel on screen, blanks the tab counts (a «0» next to a list that is still coming is a lie), and `_stockHubSettled('expiring'|'opened'|'stale')` hands the block back to `_syncStockHub()` when the last list answers (an empty block still hides; a failed load removes the skeleton; `_stockHubSelect()` counts a `.list-loading` as content so a tab tapped mid-wait shows its own skeleton). The boot's wait for the first paint is bounded by `_SPLASH_DATA_WAIT_MS` (2.5 s) — the splash used to hold the screen until `loadDashboard()` resolved, so a slow answer meant the animation was never seen | | A medicine's ingredient wraps, never cut | Asked for: «capita che il principio attivo va fuori dallo schermo in larghezza non va bene, mettilo accapo!». The cabinet row's meta line was `white-space: nowrap` + ellipsis, so «CLORTETRACICLINA CLORIDRATO» / «ACIDO IALURONICO/SULFADIAZINA ARGENTICA» were cut at the edge; a medical row (`.inventory-item.is-medical-row .inv-meta-line`) now wraps (`white-space: normal; overflow-wrap: anywhere`) while food rows keep their single line. The sheet's `.item-detail-med-facts` wraps too — `mobile.css` used to make it ONE horizontally scrollable line with a hidden scrollbar (`flex-wrap: nowrap; overflow-x: auto`), so the ingredient ran off the right edge; the pills also wrap inside themselves (12 px corners). Measured 360 / 393 / 800 / 1024: page overflow 0, `scrollWidth === clientWidth` everywhere | | The shopping list wears the SAME row as the Home | Asked for: «puoi fare il layout di "liste" uguale a quello di "in scadenza" adattandolo alla situazione? Tutte le liste devono avere lo stesso layout e stile!». A shopping row was its own design (52 px pastel square, title line with badges, subtitle, reason sentence, two round buttons). It is now `[photo strip] [name + brand / 📦 stock · 🛒 qty · 🍃 waste · 💶 price] [state] [✓] [✕]`: `_shopThumbHtml()` → `_productThumbHtml()` on the same `--row-photo-w` ladder, `_shopRowMetaHtml()` for the text line (the qty is still a tap target → `_shopQtyPopover`, the price still taps `showPriceDetail`), `_shopRowStateBadge()` for the ONE pill (`.alert-item-badge` metrics, every row has one) and the Home's `✓` + `✕` in the strip. The coloured left rail is gone (two lists that are "the same" may not carry two urgency languages) and the padding moved from the card to `.shop-row-main`, so the strip fills the card's corner. Swipe untouched; `_initShopRowActions` listens for `[data-act]`. Measured 132 px at 360 / 393 / 420 / 800 px, light and dark | | A medicine in the shopping list is not a tomato | Asked for: «i medicinali devono avere uno sfondo diverso (come hai fatto nei banner) e devono andare nella sezione Medicinali». `SHOPPING_SECTIONS` carries the **💊 Medicinali** shelf (after the household goods, before «Altro») and `getItemSection()` answers it first when the row is a medicine — the name guess would file «Rinore» among the drinks. The row wears the notice strip's indigo tint (`.shop-row.is-medical` / `.smart-item.is-medical`) while the urgency rail keeps saying HOW urgent it is; the gradient is painted **alone**, never with a base colour, because `.shop-row` is `--bg-card` and `.smart-item` is `--es-surface-tint` and the theme owns the paper. The flag travels from the server: `smartShopping()` selects `COALESCE(p.is_medical, 0)` and returns `is_medical`, and `smartShoppingCached()` refuses a payload without the `medical_sections` marker (three minutes of a stale cache would put a medicine back among the carrots). A row typed by hand has no product behind it, so `_shopRowIsMedical()` looks the name up in the pantry it already holds («Tachipirina» → «Tachipirina 1000 mg compresse») and never matches on a two-letter stub | | A peripheral that cannot work says why, in small red | Asked for: «se ci sono problemi con periferiche o altro (microfono, fotocamera, altoparlante, ecc..) mi scrivi sempre sotto la motivazione tecnica in piccolo e in rosso?». `_techReason()` / `_techReasonText()` paint the engine's own words under the sentence that already exists (`diag.*` in the six locales + the raw detail the log carries): the capture sheet (`#capture-tech`), the scan page's no-camera card (`#scan-nocamera-tech`, filled from `_cameraDiag` by `_syncScanNoCameraChrome()`) and the cooking voice card (`diag.speaker_tts` when `speechSynthesis` is missing). The reasons are real: `SpeechRecognition` absent, kiosk WebView, permission denied (`NotAllowedError`), **`audio-capture`** (no microphone — its own sentence, `capture.mic_missing`), missing `getUserMedia` **with `secure_context=no`** (the usual cause on a plain-HTTP LAN install), permission denied, no device, driver error. `_captureSyncMicAvailability()` logs the state ONCE per change (`[SHELFY] mic unavailable: … SpeechRecognition=… secure_context=… kiosk=…`), so «il tablet dice che non ha il microfono» is answered by the log: the wall reads `speech=true kiosk=true`, i.e. the recogniser is there and SHELFY is the one not opening the microphone | | No camera, medicine panel: the typed AIC is the door | `_setScanModeInner()` opens the hand entry **at once** when the medicine panel has no camera (`medical.code_no_camera` replaces the «inquadra l'etichetta» hint) and the medicine action bar keeps its place (it carries `#scan-med-code-open`). The only old door was the twenty-second rescue card, and `_medAskCodeSoon()` bails without `scannerStream` — a phone with no camera had no way at all to name a box by its code. The lookup is the scan's own (`_medSubmitCode` → `_medConfirmRead`): catalogue verification, the near-match picker and the name fallback answer exactly as for a read code | | A shopping row: LEFT is bought, RIGHT is "not buying it" | `_initShopRowSwipe()` (the only touch grammar of `.shop-row`): two gestures, two meanings, nothing else. Swiping **left** (`≤ -52 px`) runs `_shopRowBought()` — it writes the stock and takes the row off the list; swiping **right** (`≥ 52 px`) runs `removeBringItem()` — the dated dismiss of `shopping_remove purchased:false`, so it comes back on its own. The third zone that used to open the scanner on a long right swipe is **gone** (a full-width swipe started the camera instead of buying something), and so is `markShoppingItemBought()`. The suggestion rows keep their own one-way swipe (right = add it to the list). The labels are `shopping.swipe_bought` / `shopping.swipe_not_buying`, painted by `.shop-row-swipe-bg-left` (emerald: it writes the outcome) and `-right` (neutral: a dismiss loses nothing) | | A purchase is ALWAYS dated | Every door into `inventory` infers the best-before date when nobody typed one: `inventoryInferExpiryDate()` (called by `addToInventory()` and `inventoryImportAddStock()`), which is `estimateSealedExpiryDaysPHP()` on the **kind** of place (`storageKindOfLocationPHP`) + `inventoryVacuumExpiryDays()` for a vacuum pack, stored as an ESTIMATE (`expiry_user_set = 0`) so the product sheet still says «stimata» and the household edits it in one tap. A medicine is refused: its box prints its own date. `migrateDB` dated the rows that were already stored without one (`migration_infer_missing_expiry_v1`, logged `expiry_inferred_backfill`), because a row with NULL expiry never enters «in scadenza» and the pantry can never warn about it | | Anti-waste advice on a suggested quantity | `smartShopping()` attaches `waste: {keep_qty, keep_unit, shelf_days, cover_days, leftover}` to a row when the suggested amount would OUTLIVE the food: `daily = period_usage ÷ edible_days`, and if `suggested_qty ÷ daily > shelf_days + 1` the row also carries the largest amount still eaten in time (`shoppingWasteSafeQty()`: whole pieces/packs or a round weight). The client prints it beside the quantity as `🍃 (2 pz)` (`_shopWasteChipHtml`) plus the sentence underneath (`_shopWasteHintHtml`, `shopping.waste_hint` / `_chip_title`) — emerald, never red: nothing is lost yet, and the household still buys what it decides. Only **perishable** categories (`latticini/carne/pesce/frutta/verdura/pane`) with a shelf ≤ 45 days raise it, and a durable staple never does: the name heuristics read «Muesli … con fragole» as strawberries, and a marker that cries waste on a box of cereal is the noise that teaches the household to ignore it | | An offline write is never lost | `api()` sends a write that died in flight to the offline queue (`_queueWriteAfterNetworkFail()` → `_offlineQueuePush()`) instead of throwing, so marking a row «comprato» in a supermarket aisle survives the network dropping: the answer is the optimistic one (`_offline: true, _queued: true`) and the op is replayed by `_syncOfflineQueue()` — at boot, on `online` (`_flushOfflineQueueSoon()`) and when offline mode is left. ONE list of replayable actions (`_OFFLINE_QUEUEABLE_ACTIONS`) is shared by offline mode and this path, and `_offlineReplay` stops a failed replay from queueing itself again | | A discard has ONE sheet | `openWasteSheet(item)` → `_showWasteRecordModal(item)` (quantity chips + the four reasons, `waste.*`) is the only food-waste surface: the row's 🗑️ (`itemDetailThrow` → `deleteInventoryItem`), the banner (`bannerThrowAway`), the swipe and the action page (`throwWasteForProduct`, which asks only WHICH place when the product sits in more than one) all land there. A medicine keeps its short confirm. The legacy `showThrowForm()` (places + packs + `throwAll`/`throwPartial` + a second reason dialog) and the swipe-left "Cosa vuoi fare?" chooser were removed, not parked | | Dry staples never ask for a shelf check | `evershelfIsDurableStaple($name, $category, $location)` (`api/index.php`, sealed shelf life ≥ `EVERSHELF_STAPLE_SHELF_DAYS` = 180 from `estimateSealedExpiryDaysPHP`, short-life categories excluded) keeps rice, pasta, flour, oil, tins and spices out of `getInventoryAnomalies()` and `getConsumptionPredictions()`: an empty ledger is the normal state of a pantry nobody writes into, and “hai più scorte del previsto” on a two-kilo bag is not a discrepancy | | Expiry verdict (safety pill) | `getExpiredSafety()` in `app.js`: the expiry day itself is "Controlla" (server query is date-only), 1–2 days past are "Controlla" everywhere, liquids say "Non bere" (status.dont_drink / status.tip_drink_*). **The verdict is the PILL, never the door**: low-risk shelf-stable food (flour, pasta, crackers, spices) answers "Va bene" for 30 days past its best-before, and that answer used to be the gate of `shouldShowExpiredBanner()` — so the notice strip never drew the row and `evershelfExpiryNeedsAttention()` dropped it from the HA sensor and from the daily digest ("la farina integrale bio è scaduta il 13/11 e non me l'hai mai detto"). The row is now shown in the calm `banner-expired-ok` layout; only the two real extensions survive (a freezer inside its bonus, a vacuum pack inside `VACUUM_EXPIRY_EXTENSION_DAYS`, the same rule `getStats()` applies to the «Scaduti» list). The expiry digest also needs a door: Web Push is its own switch (`WEB_PUSH_ENABLED` written by Settings → «Notifiche push»), so `evershelfNotifySend()` lets it through without `NOTIFY_ENABLED`, and the cron's pass counts it via `evershelfWebPushHasSubscriptions()` — before, a subscribed device received nothing at all | | Mobile layout (list rows) | `assets/css/mobile.css` (layer 4, loaded **last**, geometry only): at ≤640 px the text owns the row and badges/quantities wrap under it, so an alert name is not cut at 107 px and a shopping title does not collapse to 0 px (43 lines, one letter each). Do not put colours there — themes stay in charge| | Tablet / kiosk layout | `assets/css/tablet.css` is NOT keyed on `min-width`: a desktop monitor is ≥768 px and was getting bold truncated two-column rows, while many Android kiosk WebViews report a CSS width under 768 and saw no change at all. It activates on `html.is-kiosk` (set by `_injectKioskOverlay()` and `_markDeviceChrome()`) or `html.is-touch-tablet` (`(hover: none) and (pointer: coarse)` **and** `max(innerWidth, screen.width) >= 600`), which `_markDeviceChrome()` re-evaluates on resize. mobile.css stays last. **The band covers both lists**: `.inv-row-content.inv-card` AND `.alert-item` become one horizontal row (photo, text, then the action strip on the right, `flex: 0 0 auto` so the strip is never squeezed into two lines), with a 53 px floor shared by `.inv-card-top` and `.alert-item-info` — without it the Home rows kept the strip under the text and the two lists disagreed about where the buttons live. **The band must never eat the article's name**: `min-width: 0` on the text block let a narrow card squeeze it to ~10 px and print «A u r e .» one letter per line (reported on a 393 px window of a touch tablet, in the medicines cabinet); the text block now has a floor (`.inv-card-top` 15rem, `.alert-item-info` 11rem) and both containers `flex-wrap: wrap`, so the strip drops to a second line instead — and below 640 px the row stops being a band at all (`mobile.css`, loaded last): it stacks like the phone card, because a touch window that narrow IS a phone. That costs the 2-column tablet card (≈469 px) ~20 px of height and gives it a 372 px name instead of 136 px over three lines — measured 393 / 768 / 1024 / 1280. | | Dates / numbers in the UI | `formatDate()` / `formatDateTime()` use `_collationLocale()` (it 19/10/2026, de 19.10.2026, zh 2026/10/19) and every date is formatted — never print the API's raw ISO string; the collation locale also drives number formatting and the TTS voice | | Suggested purchase quantity | `smartResolvePlanDays()` (explicit request → `shopping_plan_days` → inferred cycle) + `smartPurchaseHorizonDays()` (shelf life of the real storage location, not the pantry) + `smartCapPeriodNeed()` | | Quick stocktake (#285) | `assets/js/audit.js`: one card at a time, three big answers, writes in batches (`AUDIT_MODE_BATCH_SIZE`) and can be resumed within the hour from ANY device: the run lives on the SERVER (`app_settings.audit_state` — `GET audit_state` / `POST audit_state_save` / `audit_state_clear`, `auditStateRead/Sanitize`, the expiry is the server's) and `localStorage` is only an offline mirror. A stocktake started at the fridge and left half-done is therefore offered again on the phone in the kitchen (measured: device B with an empty `localStorage` answers «↩ Riprendi l'inventario (195 rimasti)», and the tally written on B is what A reads). The sheet has **no visible title** («Verifica la dispensa» repeated what the mode switch and «Inventario di …» already say, and it took the first line of a phone screen): the head holds only the ✕ in the top-right corner, and `audit.title` survives as the dialog's `aria-label`. The summary dropped the same eyebrow. The scope list counts what is **LEFT** (`_auditScopesBodyHtml` reads the session's `answered`; a place with nothing left is a ✓ line, never a button that opens an empty run), «Ti dico io» empties the field once a product is confirmed (`_auditFinish` clears `_auditSearchTerm`), and the `answered` VALUE is the answer kind (`there|finished|spoiled|skip`) — `auditStateSanitize` keeps it, because casting it to int turned every answer into 0 ("not answered") and the counts went back to full after a reload. **Three ways, one card, ONE ledger** (`_auditMode`, kept in `evershelf_audit_mode`): «Uno alla volta» — the app proposes the rows it knows (`_auditScopesBodyHtml` + `_auditBegin`) — «Ti dico io» (`_auditSearchBodyHtml`), where the household types a name, `_auditSearchMatches()` splits the pantry ROWS into `here` (the place this stocktake is about) and `elsewhere` (another shelf), `_auditSearchPick()` opens the SAME card for that one product and `_auditFinish()` returns to the search with the term still in the field — and «Scansiona» (`_auditScanStart()`), which opens the stocktake’s OWN camera — its own stream **inside the panel** (`_auditScanLiveHtml()` → `#audit-scan-video` in `.audit-cam`, a framed box in the sheet’s body: the header, the three tabs and the tally stay on screen, and the ✕ on the picture (`audit.scan_stop_camera`) turns the camera off while the sheet stays open — and the 🔄 on the other corner (`_auditScanFlip()` → `_auditScanStreamStart()`) flips front ↔ rear WITHOUT restarting the run (it writes the shared `camera_facing` setting and re-asks only the stream: `flipCamera()` would restart the shopping scanner, and `_auditScanStart()` drops the proposed run) — never a full-screen takeover), INDEPENDENT of the shopping/medicine scanner (no `showPage('scan')`, no `_spesaMode`, no AI), sharing only the decoding engine (`_ensureBarcodeEngines()` + `_scanDetectFrame()`) — and the first code read lands on the card through `_auditScanHit()` → `_resolveBarcodeLookup()`; answering that card reopens the stream for the next box. **The three ways are TABS, drawn in EVERY view** (`_auditModeSwitchHtml`: the three sheets, the card of the run, a card opened by name or by barcode and the picker of an unreadable code — a switch only the sheets carried vanished the moment the banner opened a card), labelled «Uno per uno» / «Ti dico io» / «Codice a barre». **On a narrow phone the tabs are three ICONS**: below 480 px the CSS drops `.audit-mode-label` and the glyph grows to 26 px inside a 52 px tap target (the labels survive in `title`/`aria-label`), because «Uno alla volta» / «Ti dico io» / «Scansiona» — and the longer German «Eins nach dem anderen» — cannot share one line three ways, and a switch whose words wrap pushes the card down. **One answer per LOT, never per article.** A pantry really holds several packs of the same article in the same place (17 such groups in a real one), and each has its OWN quantity and its own date — so it is its own question: «✓ C'è», «Salta», «Finito» and «Andato a male» all apply to the row the card shows (`entry.siblings` is always empty; a destructive answer writes ONE row, `entry.rows` of one). Stamping the siblings made one answer cover every batch («se segno finito un lotto e ci sono altri lotti mi segna finiti anche quelli», «confermo un lotto e mi conferma tutti quelli dello stesso tipo»): the other lots keep their stock and get their own card, and «Salta» is the one tap that leaves a lot alone. Never queue one write per pack: `inventory_use` empties one row per call and the household is holding ONE pack. `_auditUndo()` reverts the answer (`entry.rows`); another shelf stays another question. The three are used in sequence on the same shelf and **count in one place**: `_auditSession` holds `counts`, `answered` and the propose run’s `order`/`index`, the sheets print that tally (`_auditSessionBarHtml`) with «Riepilogo» (`_auditShowSummary` → `_auditRenderSummary`) and «↩ Torna alla card» (`_auditResumeCard` → `_auditSessionView`, which resumes exactly where the run stopped), and «Fatto» closes it (`_auditEndSession`). The camera hands over **only a product with usable stock** — that row is the stocktake’s question, and the row of the place being inventoried wins when the product stands in two places (`_auditScanCard`) — while a code the app cannot place does not stop the run on a toast: an **unreadable** code and a code the catalogue **knows but no shelf holds** both close the camera and open the picker of «Ti dico io» (`audit.scan_no_match` / `audit.scan_not_stocked`, then `_auditAssignView` with the name already in the field when there is one), because a barcode can point at a second `products` row for the same article — `_auditRowForProduct()` looks the row up by `product_id` and then by the article's NAME, the shelf being inventoried first (the report «Tonno ai semi di girasole non c'è nell'inventario» about a tin standing in the pantry). The ✕ and Esc close it and a `visibilitychange` handler releases the stream, so a camera never outlives the sheet. The second mode is about what is really on a shelf: **only rows with usable stock are listed** (a depleted trace and a product the app knows with no stock anywhere are never offered), and the place (`_auditScopeKey()`: the open card's scope → the scope the stocktake PINNED (`_auditScopePinned` / `_auditSetScope`, released by `_auditStop`) → the pantry's open place → the last one, kept in `evershelf_audit_scope`) comes FIRST under its own heading. Each hit opens with the place mark — ✓ `audit.mark_here` / ✕ `audit.mark_elsewhere` — carries the card's own two facts on two lines (place + stock, then the date with its own mark, both bold: `_auditHitFactsHtml`, the same helper the barcode association picker uses, so a hit cannot disagree with the card it opens) and the action on the right answers the same question: the emerald **✓ C'è** (`_auditSearchQuickThere()` records the same "there" answer the card does, with no card — and a row already answered **leaves the list**: `_auditSearchMatches()` skips everything the session answered, `_auditSearchQuickThere()` and `_auditAnswer()` refuse a second answer for the same row, and `_auditUndo()` deletes the entry so a correction still works) for a row that belongs here, a neutral **Sposta qui** (`_auditSearchMoveHere()` → `inventory_update { location }` + the live cache patch + `loadInventory()`) for one that does not. **Below 520 px the action is one ICON** («✓ C'è», «↪ Sposta qui», «🔗 È questo», the words surviving in `title` + `aria-label` inside a 44 px tap target): with the label the pill took ~110 px of a 393 px phone, the text column fell to 123 px and the place was printed UNDER the pill; the place and the stock are two nowrap groups (`.audit-hit-seg`, ellipsis) that may wrap between each other but never inside one; the BRAND is a line of its own under the product name (`_auditHitTitleHtml`, one line, tail ellipsised, omitted when the product has none); **a scan NEVER walks into another shelf** — a row the ledger puts elsewhere is a question (`_auditElsewhereView`: the product, where the ledger has it, «↪ Sposta qui» / «No, lascia dov'è», eyebrow = the place being inventoried, session/tally/pin untouched; «Sposta qui» writes `inventory_update` through `_auditSearchMoveHere` and opens the card HERE), and the same guard covers the ✕ rows of the search list (`_auditSearchPick`), while only an explicit pick on a line that prints its place (the barcode picker) opens that row's card. An unknown name still offers `audit.search_create` (`_auditSearchCreate()` → the product form with the name typed). A one-question card is never a resumable run of its own (its answer lands in the session, and what resumes is the propose run it belongs to), and the three TABS at the top of every view are the only switch (they keep the run), so the card carries no second, duplicate way in. **It is not a setting**: the banner `#inventory-stocktake-btn` lives in the pantry (`_syncInventoryAuditBanner`), it names the place you have open — or the whole pantry — and its CTA `_auditStartFromBanner()` starts the wizard on those rows (`_auditBegin` compares `normalizeLocationKey()` on both sides); the whole-house view keeps the scope picker. `AUDIT_MODE_ENABLED` no longer exists: a procedure you perform in front of a shelf has nothing to switch off. **The card has ONE hierarchy** (`_auditRender`): the progress bar of the whole stocktake (`_auditProgressHtml`, see below) with `{n} di {total}` beside it; then the product as facts ONCE (56 px photo, name, brand on its own line, then the **place + stock on one line and the date on the NEXT one with its own mark** — «📍 Frigo · 📦 Giacenza: 1500 ml» then «⏳ Scade il 31/01/2027», because side by side the two number pairs read as one; `.audit-product-facts`, the stock `0.95rem/800` and the date the same against the `0.82rem` of the line around them, «Senza scadenza» when it has none); then the single emerald primary, which is the whole QUESTION (`Confermi {qty} in {place} che scade il {date}?`, «…, scaduto il {date}?» when it is already past, `Confermi {qty} in {place}?` without a date) — and `_auditFitConfirm()` MEASURES it after the paint and swaps in `Confermi {qty}?` (`is-compact`) when it needs more than two lines, so a phone, a big font or a long place name never grows a paragraph; then a neutral 2×2 (`🏁 Finito`, `🗑️ Andato a male`, `✏️ Modifica quantità`, `📍 Sposta`) where the two negative twins share one style, and the footer with «Salta» only. **The two answers that empty the shelf ASK FIRST** (`_auditPendingAnswer`, «se premo su Finito non mi chiede nessuna conferma»): the question replaces the answers in place — red confirm (`audit.confirm_yes_finish`/`_spoiled`), neutral «Annulla», title/message naming the product — because the shared `_showDestructiveConfirm` would sit BEHIND this sheet (its own overlay) and its 5 s bar confirms by itself, which is the opposite of asking. The pending answer carries the row id, so repainting another card drops it; only the confirm's own button passes `confirmed`, and `_auditStop()`/`_auditFinish()` clear it. The spoken sentence and the giant duplicate quantity were removed on purpose: the household reads the card in half a second. The scale is a mint pill (`#F0FDF4` + emerald border), never purple. **ONE progress bar, and it never comes and goes** (`_auditProgress` → `_auditProgressHtml`, `counts` ≠ position): `total` is the rows this run is ABOUT (the place being inventoried, or the whole pantry) and `done` the ones the session answered — the same ledger the scope list counts, so «Frigo (37)» and the bar cannot disagree. It is painted by the three mode sheets, by EVERY card (a proposed one and a single question alike: a card opened by name or by barcode is a run of ONE for the wizard, and its own counter read «1 di 1» on every box and never moved — the report «rimane sempre a uno»), by the panel of an unreadable code (`_auditAssignView`) and by the camera (`#audit-scan-progress` → `_auditScanProgressPaint()`), with the breakdown beside the count (`_auditTallyBits`, «40 di 206 · ✓ 33 · 🏁 3»). The open card counts as the one being looked at (`inHand`), so the first of fifteen reads 7% and never an empty line. And the scope is **pinned** (`_auditScopePinned`, released by `_auditStop`): reading the pantry's own filter mid-run moved the ledger to another shelf, and a session for a new scope starts at zero — measured in the simulation, «Inventario di Frigo: ✓ 4» became «Inventario di Dispensa: ✓ 1» on the next answer and never went past it again. For the same reason `_auditAdoptRunCounts()` never replaces a session that has answers (a barcode-only run has no card order, and adopting the server's blob over it was the second way for the tally to jump back). **A card of a row ALREADY answered says so** (`_auditAnsweredHtml`: mint line with the answer kind and the hour from `entry.at`) and stops pretending to be a question: a barcode read twice, a pack line of «Anche in» or a name picked again used to show the emerald «Confermo …», and pressing it counted nothing and closed the sheet. Its two doors are «↩ Cambia risposta» (`_auditReopen` → `_auditRevertEntry`, shared with `_auditUndo`) and «Avanti →» (`_auditNext`, the step a real answer takes, counting nothing); «Salta» and «Indietro» are hidden there, and `_auditOtherPacksHtml()` marks the answered packs with a mint ✓. | | A barcode no catalogue knows (stocktake) | The «Scansiona» mode used to answer an unknown code with one line of text and no way forward, while the household was holding the box. Now the camera closes and the same search as «Ti dico io» opens with the code on its head (`_auditAssignView` / `_auditAssignRender` / `_auditAssignPick`, `#audit-assign-input`, **one line per PLACE** — `_auditAssignMatches()` returns every ROW, the place being inventoried first, and the pick carries the row id so the card that opens is THAT shelf: a «Riso basmati» standing in the pantry and in two living-room rows listed once hid the shelf the household was looking at): picking a product writes the code through **`POST product_barcode_set`** (`setProductBarcode`) — `products.barcode` and nothing else, logged `api_product_barcode_set` with the previous value — and opens that product's card, so the stocktake continues on it. The write is deliberately NOT `product_save`: that is the catalogue's merge point (it re-derives name/unit/pack/kind and can merge two articles) and a hand association sent through it reset `default_quantity` 2 → 1 and `package_unit` g → '' on a real row. A code another product already owns is REFUSED (`barcode_already_used` + `audit.assign_taken`, naming the owner) instead of merging two articles behind a tap — and the card of the row the household picked opens anyway, because answering that row is the whole reason they lifted the box — and the client remembers the association (`_barcodeRememberProduct` → `_barcodeSessionCache` + `_BARCODE_PERSIST_KEY`) so the next read resolves, now and after a reload. **The same picker answers a code the catalogue KNOWS but no shelf holds** (`audit.scan_not_stocked` is now followed by the panel, never by a toast that leaves the household stuck), with the article's name already in the field: `_auditRowForProduct()` looks the row up by `product_id` and then **by the article's name** (folded, the shelf being inventoried first), because one article can live in two `products` rows — the one added by hand and the one created when the barcode was first scanned — and the scan of a tin standing in the pantry answered «Tonno ai semi di girasole non c'è nell'inventario». That fallback logs one `[AUDIT]` line, which is how the double row is found instead of blamed on the scanner. An unknown name still offers `audit.search_create` | | Settings page (sections, essentials, autosave, checklist) | **The page is a control panel and has NO Save button.** Six sections (`SETTINGS_GROUPS` = general, cooking, ai, medical, alerts, system) in a rail — a sticky 212 px sidebar on a monitor, a swipeable strip of pills on a phone — with the open section's topics as chips under it; `switchSettingsGroup()` + `_syncSettingsTabsVisibility(group)` (the ONE visibility rule, called by both the section switch and `_syncSettingsGroupForTab()`: skipping it on a fresh boot is what left all 18 chips on screen). Above the rail, never behind a tab: **four essentials** painted by `_renderSettingsEssentials()` (masked API token + reveal/copy, pairing code, last backup + «Backup adesso», version) — compact rows below 560 px. **Every control writes itself**: `_initSettingsAutosave()` (delegated on `#page-settings`; a checkbox/select writes at once, a field 700 ms after the last keystroke) picks the saver from the nearest `data-autosave="fn"` on the card or panel (`saveNotifySettings`, `saveHaSettings`, `saveCalendarSettings`, `saveTelegramSettings`, `saveWebPushSettings`, `saveHealthProfileFromSettings`), `data-autosave="none"` for the modules that already persist themselves (EverShelf Med), and defaults to `saveSettings()`, which is **one write at a time** and returns whether the server accepted it. The sticky `#settings-savebar` is the receipt (`_settingsSaveState`: pending/saving/saved/error) — never a button, and it must not say «Salvato» on a refusal (`_saveSettingsInner` returns the verdict). The accordions (`_initSettingsAccordions()`, `_openSettingsCardFor()`), the checklist (`SETTINGS_CHECKLIST`, `_checklistNewsItems()`) and its per-section badges (`_renderSettingsSectionBadges()`) stay. Long guides do not live in a panel: the CA instructions are `#ca-help-overlay`. The registry (`assets/js/settings.schema.generated.js`) is generated by `scripts/gen-settings-schema.php`, which needs every panel to keep `class="settings-panel"` + `id="tab-…"` — `scripts/gen-code-index.sh` keeps the line numbers | | Setup wizard / assistant ledger | `_getMissingSetupSteps()` + `_gdriveWizardNeeded()` + `_setupSeen()` in app.js; the ledger (`setup_done`, `setup_seen`) lives in `app_settings` and `get_settings` hands it to every device, so a new browser profile is not re-asked (issue #301); `GDRIVE_ENABLED=false` and `APP_LANG` hide the Drive/language steps | | Opened too long (PAO) | `data/opened_shelf_life.json` → `api/lib/opened_shelf_life.php`: 32 macro-families × 3 storage places with `warn` / `critical` days (USDA FoodKeeper + EFSA), deterministic, **no AI and no network**. `getStats()` attaches `pao` (`days_open, warn, critical, state, score`) to every opened row; the client judges an opened row by **that clock, not the printed date** (`_openedPao()` / `shouldShowExpiredBanner()`), sorts the banner by `score = days ÷ critical` (`_bannerPriority`: critical 3000+, warn 1500+), renders the `opened` layout (photo, "aperto da N gg · consigliato X–Y gg", amber/red rail, **🗑️ Butta** + **🍳 Usa per ricetta** inline, *Finito/Modifica/È ancora buono* in the `⋮` that opens in place), and offers "e altri N prodotti aperti" → `_showOpenedTab()`. "È ancora buono" snoozes 3 days (`app_settings.opened_check_snoozed`). **A drink past its drinking window is an ingredient, not waste**: a family that declares `cook_after` (the wine, 10 days) makes the summary emit `cook_only` + `cook_hint_key`, so the strip leads with the emerald **🍳 Usa per cucinare** (`bannerUseInRecipe()`), **🗑️ Butta** stays *inline* as a neutral secondary, the drinking window is not printed any more and `_bannerPriority` puts it at 1400+ — below a row that is really spoiled. A family may also carry its `icon` (`🍷`/`🍺`/`🥃`): `pao.icon` and the pantry row's `family_icon` feed `_productFamilyIcon()`, so a wine is never drawn as its category's 🥤. **A medicine may stand in the same strip, and it is never a food surface**: its clock is the PAO printed on the pack (`med_pao_days`, which `_openedPao()` now asks FIRST — the food table would lend a vial 20-45 days), the card wears the medical tint (`is-medical`, indigo over `--surface-bg`, light and dark) while the rail and the title keep saying how urgent it is, the limit is printed as ONE number (`medical.banner_opened_limit`: «da usare entro 1 gg dall'apertura», never the «1-1 gg» range of a monodose vial), and the ⋮ loses «✓ Segna come ancora buono» (`bannerStillGood`) and the strip loses 🍳 — you do not cook a drug, and how long an open pack stays usable is printed on the box. A form whose opening changes nothing (`0`: tablets, capsules) raises no clock at all. **A single-dose form has no period after opening either** (`data/medical_pao.json` v3 answers 0 for `fiala` / `monodose` / `flaconcino` / `siringa preriempita`; the table is **multilingual by data** — each rule's `match` is a `lang => [words]` map, `medicalPaoRules()` flattens all six languages together because the NAME comes from the catalogue while the UI may speak another one, matching is whole-word + accent-folded («comprime» finds «comprimé», `gel` no longer fires on `Angelini`) and a `*` marks a German compound: `*saft` → «Hustensaft»): the container is used in one go, and the row the pantry stores is the BOX — «6 CONTENITORI MONODOSE, 4 pz rimanenti, scadenza 2028» read «da usare entro 1 gg dall'apertura» and declared a sealed box expired two weeks ago. The stored values the old `1` produced are re-derived by `migration_med_pao_single_dose_v1` (only the exact value the old rule could write, and only when the form now says 0 — a number the household typed is never touched). Food keeps its two thresholds, printed once when a table declares the same day twice (`dashboard.banner_opened_limit_flat`). **The window is editable, and it learns**: the pantry edit sheet carries it (`pao_get` / `pao_save` / `pao_reset`, `api/lib/pao_overrides.php`) — one row per product × family × place — and the value the pantry uses is the **AVERAGE** of the household's corrections for that family in that place (`paoAverageMap()` → `openedShelfLifeThresholds()`), never the last tap: correcting a single yoghurt nudges the category instead of rewriting it. No observation → the data table answers as before; «↺ riporta ai valori consigliati» clears the family. | | Header: the scale | `#scale-status-indicator` (`.scale-pill`) is **hidden** when no gateway is configured, neutral while it searches, **mint with the live weight** (`#scale-pill-weight` + `#scale-pill-battery`) only when a reading is genuinely streaming. The Android bridge **replays its cached status + last weight to every new client**, so the first weight of a relay session is ignored (`_scaleWeightMsgCount`), a reading is live only if a second one arrives within `SCALE_LIVE_MS` (10 s, re-rendered by a 5 s tick), and "gateway reached" ≠ "scale on" (`scale-status-waiting`, `scale.status_waiting`). Tap → `_scaleTogglePopover()` (device, battery, big weight, `_scaleTare()` local baseline — the bridge is read-only, connect/disconnect) | | Bottom nav | The centre is SHELFY (`#nav-capture-btn`) and it wears the assistant's **avatar** (`.nav-capture-avatar`, the same transparent PNG as its sheet), the slots are Home / Dispensa / **🍳 Ricette** (`data-page="recipe"`) / Spesa / Storico / Config. The recipes own a slot again (the dashboard CTA alone made them feel gone); the **scanner is not a nav slot** and stays one tap away (`showPage('scan')` from the dashboard, the product modal and the flows). Scanning a barcode of a product you already have opens the **product modal** (`_inventoryRowForProduct()`); a new one opens the add form prefilled from Open Food Facts. **Nothing scrolls visibly under the bar**: the bar is a floating pill (`elegant.css`: rounded, `bottom: 10px`, `width: 100% - 20px`), so rows used to travel across the 10 px gaps and through its corners — `body::after` paints the **canvas band** (`z-index: 90`, just under the bar's 100, `pointer-events: none`) opaque by the time it reaches the pill and dissolving over the last 12 px above it, so a row fades out instead of being sliced. No `backdrop-filter` on purpose: a blur over a scrolling list repaints every frame | | Shopping session (spesa) | `startSpesaMode()` opens the **camera first**; `endSpesaMode()` stops it and, only if `_spesaSession.length > 0`, asks the total with a **numeric keypad** (`_spesaFinishPrompt` / `_spesaKeypad` → `spend_add`) — `[Salva totale]` / `[Salta]`. The former "amount before scanning" dialog is gone, and so is the receipt **file upload** (the OCR code is parked, settings toggle hidden) | | A list has a SHAPE while it loads | `_listSkeletonHtml()` / `_showListSkeleton(id, rows)` / `_hideListSkeleton(id)` (app.js) paint the waiting state the shopping list has always had (`_shoppingSkeletonHtml`, `.shop-loading`): **SHELFY on the splash breathing ring** + skeleton rows with a shimmer, so a page is never a white void for the second or two a fetch takes on a phone. The CSS is ONE block with two aliases (`.shop-*` / `.list-*`) and respects `prefers-reduced-motion`. Used by the pantry (`loadInventory`: 6 rows, removed on the render or when the retry also fails) and by the Home (`loadDashboard` → `#expiring-list`, `loadStaleDashboardItems` → `#stale-list`); it never paints over rows that already exist. A **remote picture** (Open Food Facts) shimmers too: `.product-thumb`, `.inv-image`, `.item-detail-image` carry `is-loading` until the image's own `onload`/`onerror` takes it away, so an empty square never looks like a missing product | | Credits / free APIs | `data/free_apis.json` → `assets/js/free_apis.generated.js` (`php scripts/gen-free-apis-js.php`, in the service-worker shell) so the **splash** can paint the row before there is a token, offline; `_renderPreloaderApis()` runs at `DOMContentLoaded` and paints **logos only** (no names: they wrapped onto three lines on a phone) **and only the ones that read at 22 px** — a horizontal wordmark (7:1) is a sliver in a square, so `data/free_apis.json` marks it `wide: true` (a wide box in the card, the dialog and the thanks page) and `splash: false` (kept off the splash); the line `startup.free_apis_lead` above them says what they are, and the logos light up in turn (`--i` staggers `preloader-api-glow`, off with `prefers-reduced-motion`), `_loadFreeApis()` paints the *Settings* card (`#settings-free-apis`) and the **dedicated thanks page** (`#settings-free-apis-page`, tab `tab-credits` with `_openCreditsPage()`), from the same generated file (falling back to `GET free_apis` only for a stale bundle). The card's primary button (`credits.why_button`, immediately above the support card) opens `_openFreeApisDialog()` — one block per service with **why** (`credits.api_*`), **where** (`credits.api_*_where`), licence and URL. **The overview carries no credits footer** (it stole a third of a phone screen above the nav bar). `_freeApiLogoHtml()` renders the logo with the monogram as the `is-fallback` fallback; a `logo` passes through only when it is a **local** `assets/img/*` path (never a remote pixel), and an entry with no file at all draws its `mark` (the national catalogue ships that way until its official asset is vendored). A source can be **CONDITIONAL** with a `when` gate (`{medical:true, country:["IT"]}` on AIFA): `_freeApiActive()` filters the splash, the Settings card, the thanks page and the why/where dialog by the ACTIVE country module, `_syncCreditSources()` repaints them when `med_status` arrives (and when the module is switched off), and the last active set is kept in `evershelf_credits_seen_v1` so the splash — painted before any token — is right offline too. The sentence per service is a literal `t('credits.api_*')` / `_where` resolved by id in `_freeApiUsage()` / `_freeApiWhere()`; the logos are the projects' own brand assets and `credits.logo_note` attributes them. **The splash also says whose project this is**: right under the open-data credit, one quiet chip (`.preloader-github`, `startup.free_project`) carries the GitHub mark (`assets/img/icons/github.svg`, in the service-worker shell so an offline boot still draws it) and links `https://github.com/dadaloop82/EverShelf` — the same link as `about.github` in Settings → About. It keeps GitHub's slate, never the app's emerald (that colour belongs to the stage lighting up), and it is `tabindex="-1"` on purpose: `#app-preloader` is `aria-hidden` and deletes itself ~1.7 s after boot, so a keyboard must never land in it. **The splash has ONE progress line and ONE foot**: the rail's connector already fills with `--preloader-progress` (`_preloaderStage()`), so the 3 px `#preloader-bar` that stood between the caption and the credits is gone (on the light canvas it was a stray line whose status words were still pale-on-dark colours); a `?debug=1` boot keeps only `.preloader-status-text`, in the slate family. The credit line, the chip and SHELFY sit inside `.preloader-foot` (8 px gap) — their spacing is one value, not three negative margins cancelling the rail's 18–28 px gap. Under the address sit **two standard badges, not more prose**: `MIT` (the SPDX code of the repository's `LICENSE`, monospace and never translated — a licence badge must be the one the project really has, GPL would be a lie here) with `assets/img/icons/license.svg`, and `startup.no_ads` (the two words `No ads`, true since the banner slots are commented out) with `assets/img/icons/no-ads.svg`; both in the shell, both slate pills on a hairline so they read as metadata. **The three strings of that chip are ENGLISH IN EVERY LOCALE, on purpose** (`startup.free_project` / `startup.no_ads` carry the same value in all six, exactly like `startup.powered_by_open_data`): the splash is painted BEFORE the language is known, so a translated line would flash in one language and settle in another — the meaning is carried by the marks and by a code that is the same in six languages, and the translated version of the same facts lives in Settings → About | | Custom locations (add / rename / delete) | `CUSTOM_LOCATIONS` (`.env`, or the `app_settings.env_overrides` fallback) holds the **typed labels**; the slug (`inventorySlugifyCustomLocation` ↔ JS `slugifyCustomLocation`) is what `inventory.location` stores. **Every write is saved server-side before the UI paints it** (`_saveCustomLocations` → `save_settings`): the pantry validates a location on the server, so a place that exists only in the browser answers `Invalid location` on the first product — a refused save is reported and nothing is painted. `inventoryCustomLocationMap` also **adopts a `custom_*` slug that still holds stock but lost its label** (`inventoryOrphanCustomLocations` + `inventoryLabelFromSlug`), so a place with products is never invisible nor refuses new stock. Deleting is one action for EVERY place, built-in included: `POST location_delete` (`locationDeleteAction()`), refused with `settings.custom_locations.in_use` while the place still holds usable stock (the pantry rule: `isInventoryDepleted`, so a trace does not keep a room alive) and with `settings.custom_locations.last_place` when it is the only one left. A built-in disappears through `app_settings.deleted_locations` (`deletedLocationsList()` / `saveDeletedLocations()`, handed to the client by `get_settings` and subtracted by `validInventoryLocations()`, so the pantry refuses new stock there), a custom place also loses its label; deleting Dispensa also retires its legacy alias `altro`. The Settings list shows all of them (`renderCustomLocations`) with rename only on custom places. **Renaming** is `POST location_rename` → `locationRenameAction` (api/index.php), which moves `inventory` + `transactions` in one transaction, updates `app_settings.medical_locations`, then rewrites the label list (in place), and answers `error_key`s for reserved/duplicate/comma/too-long. Client: pencil in `renderCustomLocations` → `renameCustomLocation` / `_submitCustomLocationRename` (`location-rename-overlay`, Esc via `_OVERLAY_CLOSERS`). **The order and the icons live in ONE list** (`mergeCustomLocations`): Dispensa → the marked **medicine cabinet** (`MEDICAL_LOCATION_ICON` 💊, resolved by `isMedicalLocation` from `medical_locations` in either stored form) → the fridges → the other custom places (`CUSTOM_LOCATION_ICON` 📦); the rail, the pantry tabs, the add/use pickers, the Settings list and `_medLocationChoices` all read that list, and `med_status.medical_locations` hands it to a new device at boot. The **pantry place filter is one control**: `_locMacroBarHtml()` paints the two macro pills (🥫 Food & Kitchen | 💊 pharmacy) and, on the food side, the only room menu (`_locFoodMenuToggle`) — a **fixed** layer anchored to its trigger by `_locFoodMenuPlace()`, because `.location-tabs` scrolls horizontally and clips an absolutely positioned child (the menu opened *out of sight*, so the tap read as "il dropdown non si apre"); a scroll/resize closes it, the first 350 ms forgiven; `_syncLocationFilterUi` repaints it with the counts. **The list groups by genre or by place** — a switch under the status chips (`#inventory-group-bar`, `setInventoryGroupBy()` → `_inventoryGroupBy` in localStorage, `renderGroupedByLocation()` with the same `LOCATIONS` order and the same section headers): it REORDERS the rows, it never filters, so it is not a second place control. It is hidden while one place is open (one group) and in the cabinet; a search result and the pharmacy stay flat; opening a place clears a leftover search/tag filter, the search runs on `currentInventory` (that place), and `recent_popular_products?location=` takes the quick-access rail from that place's own history and stock. **The pantry shows the place you opened**: `_syncInventoryTitle` puts its icon + name in the page header (`inventory.title` comes back with "Tutti", `data-i18n` restored) and the cabinet pill is hidden while another place is open — it sits before the dropdown, so it used to be the first thing on screen after opening the fridge. A picker marks **exactly one** place by `data-loc` (`markLocationButton` + `resolveLocationKey`, which accepts a slug or the typed label): matching the button TEXT lit up "Dispensa" and "Dispensa cucina" together, and a manual pick records `dataset.userPicked` so no history/AI hint may move it afterwards. The **dashboard** lists the same places as ONE dropdown (`#dashboard-location-select`, `renderLocationRail`: a way in that resets after the pick, so the same place can be chosen again) with the marked cabinet as its own 💊 pill **outside** the list. **The expiry estimate follows the KIND of place, not its name** (`storageKindOfLocation`: pantry / fridge / freezer, read from the built-in key, from the label the built-ins carry in the ACTIVE language and from the words the CSV import knows; PHP port `storageKindOfLocationPHP`): "Dispensa cucina" is dated exactly like "Dispensa", and a pick between two places of the same kind NEVER moves the date (add form `recalculateAddExpiry` and both edit modals `recalcEditExpiry` recompute only when the kind changes, or on purpose with the vacuum toggle), while the AI hint may not apply days that belong to another kind (`sameKind`) | | Product photo on a row | `_productThumbHtml()` — 44×44 neutrale (`var(--bg-app)`, hairline, radius 8, `object-fit: contain`) with the **category emoji under the picture**, revealed by `is-icon` when the URL is missing or fails (`onerror`) and 📦 when the category is unknown: never a broken image, never an empty square. **That frame is now the LEFT QUARTER OF THE CARD** (`assets/css/surfaces.css`, next to `.product-thumb`): the strip is `absolute` and the card clips it (so the card's corners are the photo's), the picture is scaled 150% and pulled 50% left so its **centre** lands in the opaque zone — `object-fit: cover` never crops horizontally in a strip this wide, so without it the visible part was the package's *left edge* (`margin-left = width − 100%`) — and a long `mask-image` dissolves it before the first letter. Every text line reads **one** custom property (`--row-photo-w`, the same one the strip's width uses — the ladder 18% → 14% → 10% → **5%**, its floor), so no text is ever printed on the photo: shrinking only the padding is exactly how the first letter landed 62 px inside the picture on a phone. The sheet keeps its own 74 px (its 64 px photo is the lightbox target); **no photo → the category emoji takes the same strip**, same size and dissolve, so a list never changes shape; the layer is `pointer-events: none` (tap/hold/swipe untouched); all cards are the same height (name clamped to two lines, meta to one, 62 px floor on `.inv-card-top`, skipped on the touch-tablet/kiosk band, where `.inv-card-bottom` stays on the right at full width). Home and pantry are **one list grammar**: `.urgency-hub` / `.alert-section` are plain sections, every `.alert-item` is a card with the pantry's chrome *down to the pixel* (same hairline, 12 px padding, 10 px gap, 62 px text floor, 34 px action line: **132 px in both lists**), the badge strip always takes its own line, the row ends `[expiry] [✓ Usa] [⋮]` in both (the pantry's ⋮ lives in the action line, not on the name line), the brand sits beside the name, and `✓ Usa` collapses to a bare check below 520 px in both. **The pixel work is in the tokens, and every one of them was wrong once** (measured in headless Chromium with the real stylesheets — the four Home lists came out 149.86 / 131 / 132.86 / 120.8 / 190.8 px against the pantry's 132): the corner and the shadow come from `--es-radius-card` / `--es-shadow-card` (18 px, the tokens `elegant.css` gives `.inventory-item`) and never from `--radius` / `--shadow` (24 px, the "slightly different shape"); the title is `0.95rem/700` and the secondary line `0.8rem` **in both** lists, and the two facts a row is read for are **the biggest things in it**: the stock chip `0.95rem/800` in its mint pill and the date `0.9rem/800` in its state colour (`surfaces.css`, "the two facts of a row"), with a 6 px strip gap that pays for them — every row is still 132 px, measured 320 → 1200 px. The date is **compact by construction**, never a sentence: «⏰ Scade fra 12gg», «⚠️ 12 gg fa», «📅 ~3 mesi», «✅ Stabile» past a year (the full sentence in the `title`, the exact date in the tooltip), because «⏳ Scade tra 12 giorni» is 136 px and the strip has 126 px for it beside the chip and two buttons on a 360 px phone — the old sizes fitted by **0.3 px** of 292, which is why they had to stay small. Those keys already carry their glyph: prefixing them again printed **two** ⚠️ on an expired row and on «Scade oggi!»; `.alert-item-badges` carries a **34 px floor** (a row whose badges are only text was 23 px and its card 11 px shorter); `.alert-item + .alert-item` must **not** zero `border-top` (with separate cards 10 px apart it made every row after the first 1 px shorter); the brand belongs **inside** the name (`_alertItemHead()` emits it in `.alert-item-name`, like `.inv-brand-inline`), because as a flex sibling it cannot fit beside a two-line title and drops to a third line (+18 px); and a Home row may not carry more badges than the pantry's action line holds in one line at phone width (the "forgotten" row lost its second badge for that reason). `.alert-item-qty` lost its white chip (invisible on white, a grey pill in the dark theme). **The photos are remote Open Food Facts URLs and the service worker used to ignore another origin**, so every render asked the network again and offline the picture never arrived: `sw.js` now keeps them in their own `IMG_CACHE` (`evershelf-images-v1`, cache-first, `IMG_MAX` 400, pruned oldest-first, kept across shell updates) for the `images.*`/`static.*` fact hosts only — never the API host, where cache-first would serve a stale search. **A medicine never wears a food category emoji**: `_isMedicalRow()` swaps the fallback for the drawn mark `_medIconMarkup()` (`assets/img/icons/medicine.svg`, medical tint `#6366f1`, in the service-worker shell) — also in the plain emoji slots (`_productCatIconHtml()`: detail sheet, action hero, add preview, products list), in the pantry badge (`badge-medical` = `medical.row_tag`, so the food `badge-category` and its "altro → guess a category" repair never touch a box) and in the medicine's own category group (`renderGroupedByCategory()` puts medical rows under "Farmaco" with the pill header); a PLACE is drawn by `_locIconMarkup()` (the cabinet = the pill, the rest keep 🗄️/🧊/❄️/📦; a native `<option>` keeps the 💊 character, an image cannot go in an option label). Used by the four dashboard rows, by `_bannerIconSet()` for the notice strip, and by `.inv-image` in the pantry (same frame; the detail modal keeps its own). `getStats()` **must** keep selecting `p.image_url` in both the expiring and expired queries, or the Home rows have nothing to show | | UI grammar of an action strip | One emerald (`--brand-primary`) for the answers that write the outcome (`Usa`, `Conferma`, `Sì è finito`, `Esegui`, `Iniziamo`), neutral secondaries (`--surface-bg` + `--surface-border` + `--text-muted`) for everything else: no pastel per-button colours. **Red only for what loses stock** (throw away, finish, a correction that takes quantity away): the history's ↩ confirm is `btn-danger` when it undoes an *addition* but `_showDestructiveConfirm(..., {tone:'positive'})` → `btn-primary`, emerald bar and **no countdown** when it puts a consumption back. A toast never prints a slash between number and unit (`1/pz`): `showToast()` normalises it. Every banner action stays **inline** (wrapping), never behind a ⋮. A safety verdict that only asks for a look (`Controlla`) is a neutral tag; `Va bene` / `Non mangiare` / `Buttalo` keep their colour, | | Dashboard panels & limits (live) | **Any mutation refreshes the dashboard itself**: `_dashboardLiveRefresh(invId)` fades the row out (`_fadeAlertRow` → `.alert-item.is-leaving`, 220 ms) and rebuilds the blocks on a debounce, wired into the edit save, `extendInventoryExpiry()`, a consumption, a deletion and `refreshAppDataAfterMutation()` — never ask the user to reload. **And the refresh is now ONE choke point, whatever forgot to ask**: `api()` hands every successful POST to `_afterPantryWrite()`, whose `_PANTRY_WRITE_ACTIONS` lists the writes that change an ARTICLE (stock, catalogue, place, PAO) — the stocktake, SHELFY, the sheets, the scanner and the shopping trip all go through it, so no caller has to remember. One debounced `_runAppWideSync()` (150 ms, single flight, a burst collapses) then drops every read/local cache, re-reads `inventory_list` **once** (`loadInventory()` refills `currentInventory` AND `_allInventoryCache`, which is what the product sheet's «Anche in», `_auditItems()`, the capture and the shopping hint read, and repaints the pantry list it was made in), reloads the banner, the Home blocks (when on screen), the active page (shopping with its smart list, catalogue, history, recipe archive) and the Spesa badge; off the shopping page it never runs the recommendation engine (that is the heavy pass of the page that shows it) | | Dashboard panels & limits | `DASHBOARD_*_MAX`, `_dashboardAlertCap()`, `_INSIGHT_PHASES` / `_applyInsightPhase()`; bars are drawn at 0% and filled from `data-target` on reveal; "Dimenticati" is the `DASHBOARD_STALE_MAX` (5) rows with the nearest expiry among the stock nobody uses (`forgottenExpiringItems()`, `mode=expiry`) | | Emoji-before-translated-label bug | `iconLabel` / `_stripLeadingEmoji`| | HTML printed as text (screensaver fact, alert banner, chooser modal) | `formatQuantity` returns `<span class="conf-size-info">`; text-only callers use `_formatQtyPlain` / `stripHtml`| | Splash / boot rail | `#app-preloader` in `index.html` + `_preloaderStage` / `_PRELOADER_STAGE_KEYS` / `_PRELOADER_STAGE_OF_CHECK` in `app.js`. **Three household phases** (`system` → `pantry` → `ready`), each paced ≥ `_PRELOADER_STAGE_DWELL_MS` (~380 ms); floor `_SPLASH_MIN_MS` ≈ 1.2 s. Light canvas (no dark flashbang); quiet `startup.powered_by_open_data` line (API logos live in Settings → Crediti). `_bootDebug` (`?debug=1`) still shows the per-check ticker. Hand-off: `is-lifting` then fade-out. Version chip `#preloader-version` keeps the `vX.Y.Z` shape for `scripts/bump-version.sh`. | The splash closes with **SHELFY's avatar** under `.preloader-powered` (`.preloader-shelfy`: 56 px on a breathing emerald ring, `aria-hidden`, no stage of its own — it is a greeting, never a boot claim; 44 px under `max-height: 620px`). | EverShelf Med (opt-in medicines) | Own settings SECTION (`data-group=medical`, `#tab-medical`) + one-time boot question (`med_setup_done`); `api/lib/medical.php` + `data/medical_categories.json` (**8 closed categories**, six locales, ATC prefixes for Phase 2 — never free tags; the prefixes are DATA and the form ticks the chip they resolve to (`_medCategoryFromAtc()`): a topical NSAID (Fastum gel, `M02AA15`) is `pain` via `M02A`, `S01*` is `eyes`, `D08/D03/D06/D09` are `firstaid`, `A02A/A03/A06` join `stomach`, `R05*` the whole cough group joins `cold`, `M03*` `muscles`) and `data/medical_atc.json` (Phase-2 ATC map): `med_status`, `med_symptom_search` (longest phrase first, medical rows only, tags → ATC fallback, **no AI and no dosage**) — and the **reader never calls a model either**: a box is identified by a printed code verified against the catalogue (`gemini_*` is banned in this module, the shelf-life AI hint skips a medical row, and fails on any `gemini_med_*` / `_medReadLabelAi` reference), `med_classify` (tags from the closed list + active ingredient + `med_pao_days`), `med_open` (Segna aperto → expiry = today + PAO, `expiry_user_set=1`, logged `med_open`). The module needs a **dedicated location** (pick or create → `medical_locations`) painted with its own tint; OFF by default (`MED_ENABLED` / the switch), nothing opens before `med_disclaimer_accepted`, a medical row never enters `for_recipe=1` or the recipe action, an **expiring** medicine stays in the expiry list with the tint while an **expired** one moves to its own block with **Smaltito**, **Food and medicines never share a place**: `inventoryLocationDomainError` refuses a food product in the cabinet and a medicine outside it on every write (`addToInventory`, `updateInventory`, the CSV import) and `med_classify` moves the stock of a product that becomes a medicine into the cabinet; the client only offers the legal places (`_renderLocationSelector(.., 'medical'|'food')`, `_locationsForDomain`, and for the edit screens `_locationsForEdit` + `_editDomainIsMedical`: a food's "📍 Posizione" never draws the cabinet, a medicine only its own, and a single legal place hides the whole block). **In Italy the number is the AIC and it travels two ways**: printed (`A040313076`, Code 39; or the bare 9 digits of Code 32; or AI `710` of the FMD DataMatrix) **and** carried by a Code 39 of the bollino, while the lot (`16G87N`), the pack's progressive number with its check digit (`0140581421`) and the DataMatrix that joins them are **packaging** — a barcode read is accepted only when the country module resolves it AND the catalogue contains it (`_medConfirmRead`, so a serial that starts with an `A` is thrown away) — `_medDetectCode`/`medicalDetectCode` answer the AIC first, `_medCodeIgnored`/`medicalCodeIgnored` throw a packaging code away, and the scan then **OCRs the label** (`_medReadLabelOcr`, the bundled Tesseract in a second parameter set, `_medOcrFindAic`; the label remains the reader that always works — first frames + every 2 s, bounded to 45 attempts, the printed `A`+9 form inside the rectangle `#scan-med-frame` (`_medGuideRect`), which prints the expected `A000000000` from `schema.ocr.sample`, **plus one rotating BAND of the whole frame per attempt** (`_medFrameBands`, because aiming is a skill and a box held half out of the rectangle is not a wrong box) — and the band pass runs **psm 6, never psm 7**: measured on a reproduction of a real bollino, a half-frame band through the single-line mode answers `'32'` or `''`, while psm 6 reads `A040313076`; a **psm 13 (raw line)** pass on the guide is added for the same reason. **One region per attempt, rotating every 900 ms** (`_medPassCursor`): six OCR jobs in a row made an attempt 3-5 s long on a phone and the household read that as *it does not read*. The **status chip belongs to the READER**: a packaging barcode is decoded on every frame, so it announces itself once per 8 s and never over a line the OCR wrote in the last 2.5 s (`_medLastOcrStatusAt`), and its sentence must fit the chip (`nowrap` + ellipsis: 60 chars max, six locales). The guide crop **grows** beyond the rectangle (`padX/padY` added, never subtracted) and the canvas is 1400 px — plus the `💊 Leggi AIC` button `#scan-med-ocr-btn`; when the printed letter is lost the page's digit runs are offered to the CATALOGUE (`_medOcrDigitCandidates` → `_medTryLooseReads`, only with a dataset loaded, at most four, each one verified like any other read); **a packaging barcode is never the drug number** — the SSN label carries several indistinguishable Code 39s, so only the AIC-shaped read and the FMD DataMatrix AI 710 get in, both proved against the catalogue). **The scanner has TWO panels** (`_setScanMode` / `#page-scan.is-medical-scan`): the place the pantry shows decides (`_scanModeForLocation` — the marked cabinet → medicines, anything else → food), and neither panel answers with the other world's codes: the medicine one hides AI/name/shopping and refuses an EAN with `medical.scan_not_medicine`, the food one hands a drug code over with the inline `#scan-med-cross` notice (*Apri 💊 farmaci* → `_medGoToCabinetScan`). A letter-carrying read in the medicine panel goes to the OCR, then to the form — never to a catalogue. The **catalogue is local**: `api/lib/medicines.php` + the `medicines` table (created by `initializeDB`) filled by `php scripts/import-medicines.php --country=IT <csv|xml>` from the AIFA open data (headers by NAME, one row per AIC, `--dry-run`/`--truncate`) — no medicine API is ever called; `GET med_lookup?aic=…|q=…` names the box, `_medShowCatalogueMatch` paints the card and **`_medUseMatch`** fills the field only on the household's click; `med_status.dataset` + `#med-dataset-block` say how many medicines are loaded (or that none are). A recognised AIC becomes a **medicine form**, not the food form (`_medFormSetMode` sets `is-medicine-form` on `#page-product-form`: `pf-food-only` hidden, no "is it a medicine?" switch, medical wording, the read code in `#pf-med-banner`, one closed-taxonomy chip required as the category) **before** asking any catalogue, and `med_status?lang=` falls back to the client's UI language so the country schema is never missing on an Italian UI. `data/medical_code_schemas.json` is **v3, one block per country** (`codes`, `ignored`, `ocr` with the printed `sample`, `fmd_national_ai`, `dataset`, and a `scan` summary): Italy is the BOTH-carriers case (the printed AIC and its Code 39), Germany prints the PZN (`PZN 00000000`), the US prints the NDC (`00000-0000-00`, catalogue = openFDA JSON, key = any 6.20 char national number), France's CIP-13 IS the EAN-13, Spain/Austria use AI 710. A country with no schema is **BLOCKED**: `medicalScanSupported` + `_medScanSupported` make `_medBlockedPopup` say so, offer the hand entry and point at `docs/wiki/Medicines-Country-Schemas.md` (the contributor guide) — never scan a label the app cannot read. Every code definition in `data/medical_code_schemas.json` carries a `pattern` matched against the **whole** read (`_medCodeMatches` in the browser, `medicalCodeMatches` in PHP — two ports, one rule): the AIC is `^A?\d{9}$` (both printed forms), the Pharmacode `^\d{3,6}$` inside 3…131070, and an alphanumeric read that matches nothing — `16G87N`, the lot/serial fragment of the box's EU FMD DataMatrix — is **not** claimed (digit-stripping it to `1687` is what made a 4-digit "Pharmacode" out of a code nobody had read); a letter-carrying code never reaches the five food catalogues, the household is asked once (`_medOfferMedicalFallback`); a row is medical when the product flag says so **or** when its location matches `medical_locations` in either form (`_medLocationKey`: slug or typed label), and the **product form** carries the `pf-medical-group` toggle (chips + ingredient + PAO) which saves through `med_classify`. A scanned box is **stocked from the medicine form itself** (`_medStockAddDirect()`): quantity, the printed expiry and sealed/opened are answered there and the row goes **straight into the cabinet** — no pantry step, no place question (a medicine has one legal place) and no second quantity — and the form/page speak about the cabinet, never about the pantry (`medical.form_save`, `medical.add_title`, `#add-location-group` hidden, `medical.action_add_sub`/`medical.action_use_sub`, no recipe button on a medicine's action page, `recalculateAddExpiry()` returns early for a medical row). **One screen, always**: a missing cabinet is created on the spot (`_medEnsureCabinet()` → the default `medical.default_location_name`, `medical.cabinet_created`), a refused write keeps the form with every answer and says `medical.stock_failed` (never a second form), and success lands on the CABINET LIST with the new row in it (`showPage('inventory', cabinet)`). The package code is not shown on a medicine (`#pf-barcode-group` hidden: the code was already read and verified), and the pack size (“how many it should hold”) is the catalogue's, shown by `medical.pieces_hint` with the quantity prefilled from it. The stock questions follow the household’s order: **sealed / already opened first** (it decides what the number means), then `medical.form_qty_label` — on a SEALED box the quantity IS the pack (`_medFormStockPrefill()` fills it from `_medPackSize()`, editable) — and only when OPENED a second field, `medical.pack_qty_label` (“Confezione intera”), so the app knows the stock AND the pack it belongs to; the pack is stored as `products.default_quantity` (the pack size the rest of the app reads: fractions, “sta per finire”, shopping list) while `inventory.quantity` stays the stock. `_medPackSize()` (core/med.js) reads the CONTAINER, not the first number: it takes countable pieces first, otherwise the g/ml measure, **skipping a ratio** (`25 mg/g`, `mg/ml`) and keeping the largest — “Fastum gel 2,5% 25 mg/g tubo 50 g” is 50 g, never 25 mg. The expiry of a box is a **month + a year**: `_medExpiryFillPickers()` / `_medExpiryIso()` / `_medExpiryPick()` ask "scadenza MM/AAAA" (`#pf-med-expiry-month`/`-year`, hidden `#<prefix>-expiry`) and store the **last day of that month**, because that is what the pack prints; the twelve month names are DATA (`months.*` in `translations/*.json`, six locales — never hardcoded), painted by `_medExpiryPaintMonthOptions()` from `translatePage()` as soon as the strings load, so the `<select>` is populated before any form opens. The ADD step survives only as the fallback of a refused write (`#add-med-stock`, `_renderAddMedStock`, same month+year pickers): **sigillata o già aperta** (an opened pack calls `med_open`, so the expiry becomes today + the PAO) and **quante ne restano** as fractions of the pack the catalogue describes (`_medPackCount` in `core/med.js` reads "10 buste" from the row's notes; a liquid names no pieces). **The medicine edit sheet is the FOOD sheet** (`edit-inventory-modal`): same header with the 56 px photo, the title and the state as its subtitle, `.edit-section-label` sections, the stepper + unit select row, `.edit-form-actions` with Annulla/Salva — the old `is-medical-edit` compaction (6 px groups, a unit badge instead of the select, one full-width Salva) is gone; the medical extras are the categories, the pack size, the opened control and the PAO, and `.med-pao-hint` is the only rule they keep. **A medicine's stocktake card carries the bold AIC and then the CATEGORY** (`_auditMedCategoryOrIngredientHtml`: «🔖 A002039055 · Primo soccorso»), never the AIFA active ingredient (a pharmacist's text, «CLORTETRACICLINA CLORIDRATO»): the household at the shelf reads what the box is FOR; a hand-added box with no category falls back to the ingredient. **An open pack has TWO clocks and the SOONER wins**: `med_pao_days` (the PAO from `data/medical_pao.json`: colliri 28, sciroppi/gocce 30, spray/balsamo/creme/gel 90, monodose/compresse 0 = nessun orologio, editable in the sheet) and the printed month/year stored as the last day of that month. `_openedPao()` owns the PAO clock for the strip; `_inventoryExpiryBadgeHtml()` prints the **printed date** when it comes first (`medical.sealed_expires_in` / `sealed_expired`), because a pack cannot outlive its own date — an open cream expiring in 34 days used to read only «🕓 75 gg» | | Optional support (donations only — **no ads**) | `api/lib/support.php` (decision, payload, donation link, disclosed costs), `api/lib/qr.php` (ISO QR encoder → `?action=support_qr`), `assets/js/core/support.js` (dialog, donation panel; `_renderAdSlots` is a parked no-op), `.env` keys `SUPPORT_*` — the banner slots and the `ADS_*` / `SUPPORT_BANNERS_AVAILABLE` keys are **commented out on purpose**doc `docs/wiki/Support-and-ads.md` | | PWA service worker | `sw.js` | | Unraid / containers | `unraid/evershelf.xml` (CA template: the `data` path is the database), `docs/wiki/Unraid.md`, `EVERSHELF_ENV_FILE` → `evershelfEnvFile()` in `api/lib/env.php` | | Backup + the scheduler that runs it | `createLocalBackup` / `restoreLocalBackup` / `listLocalBackups` in `api/index.php` (`VACUUM INTO` → `.part` → rename, retention, `data/backup_last_ts.json`); `docker/evershelf-cron` (`/etc/cron.d/evershelf`, every 5 min as `www-data`) runs `api/cron_smart_shopping.php`, which backs up at most once every 23 h when `BACKUP_ENABLED=true` (default); *Settings → 💾 Backup* shows the last one and warns after `_BACKUP_STALE_DAYS` (8); failures carry `error_key`, restore carries `message_key`, | | A medicine read is CONFIRMED, never assumed | `_medConfirmRead()` opens the form (never a card over the camera) and the catalogue card carries a **"Non e questo?"** chip row: `med_lookup?near=1` -> `medicineFindNeighbours()` (real rows sharing the leading digits, ranked by `medicineLevenshtein`): up to **four** neighbours with the name/dosage/pack printed on the box (`_medNeighboursHtml()` / `_medUseCode()`, in `#pf-med-match`), the read first at distance 0; `_medConfirmRead(reading.aic)` is the only exit from the reader — `A040313076` read as `...72` is one digit and the reader cannot tell. Without a catalogue the card says so instead of inventing neighbours. The form fills itself from an exact catalogue row — name, company, notes, closed category (`_medFillFromCatalogue()`, `_medCategoryFromAtc()`), empty fields only — and a box the catalogue cannot name is **not added at all**: `_medStartManualEntry()` looks the code up FIRST and a refusal keeps the scanner running (`medical.only_catalogue`, or `medical.scan_needs_catalog` when no dataset is imported). No typed title, no name read off the label, no "Aggiungi a mano": `_medConfirmedAic` — set only by `_medFillFromCatalogue()` — is what `submitProduct()` requires, so the only ways in are a `medicines` row or a product that already exists (`pf-id`); the name field is read-only in medicine mode (`#pf-med-name-hint`, `medical.name_from_catalogue`) and the title carries no "new" (`medical.form_title`). Over the viewfinder **nothing** is drawn: the guide frame fills with the digits and the existing status chip shows the pass result; every OCR call goes through `_medOcrRun()` (one worker, one job at a time — interleaved calls returned nothing), `_medOcrSelfTest()` proves the engine on the device, and the code can be **typed** (`#scan-med-code-input` + `_medSubmitCode()`, same verification) — but the field is **asked for, never parked**: it stays closed behind **✏️ Scrivi codice** (`#scan-med-code-open` → `_medCodeRowOpen()`, a toggle that also puts it away) and appears by itself only in the twenty-second rescue card (`_medShowAsk(true)`), so the camera keeps the whole screen. No "Leggi AIC" / "Aggiungi a mano" buttons. The guide frame fills with the digits already recognised (`_medPreviewSample()`), the catalogue card carries its **source** (`medical.match_source`: "AIFA open data · N farmaci") with ingredient/form/pack/company/ATC/class, and the catalogue **downloads and refreshes itself** (`med_catalog_sync`: the module `dataset_sync` declares the source, Italy = the AIFA confezioni export, 160k packs, streamed to a temp file, ~30 s, 4 MB; automatic on module activation, daily at most, monthly, and from the cron; Settings keeps "Aggiorna dal sito AIFA" and the manual `POST med_catalog_import`) — a scan is **verified**: an AIC the catalogue does not contain is a misread digit, `_medConfirmRead()` rejects it and keeps reading (`medical.scan_code_invalid`, `_medRejectedReads`) | | Medicine label reader (feedback + hardening) | `_medReadLabelOcr()` runs THREE passes on the guide rectangle (`#scan-med-frame`): single line, the same crop binarized with a LOCAL (Bradley, integral-image) threshold (`_binarizeScanCanvas()`), a contrast-stretched + sharpened copy (`_contrastScanCanvas()`), single block, then a 1.6× wider band; the OCR alphabet is `0-9A` (`_tesseractConfigure('aic')`) and `_medOcrFindAic()` repairs the letter-spacing and the `1/l`, `0/O` confusions of OCR-B — only inside a run that starts with the prefix letter, so a pack serial can never become a drug number. `_medOcrFeedback()` paints `#scan-med-read` (“Letto «…» + the crop), because a silent failure cannot be diagnosed by the household; the loop never stops, it slows to `_MED_OCR_IDLE_MS` (4 s) | | Medicine read diagnostic (TEMPORARY) | `MED_DEBUG=true` in `.env` → `med_status.debug` hands the flag to the client, `_medDebugPass()` / `_medDebugPanel()` post `POST med_debug` (token + CSRF, 403 without the flag) and the server writes `data/med_debug/events.jsonl` + `frames/*.jpg` (20 events/request, 700 kB/image, pruned to 400 events and 40 pictures; the folder is git-ignored). It is how "it reads nothing" is seen instead of guessed: region, psm, video size, the text of each pass and the crop it came from. Turn it off with `MED_DEBUG=false` — the whole path goes quiet | | Medicine code: which number identifies the drug | **Split core + country module.** Core, country-neutral: `api/lib/medical.php` (`medicalGs1Parse()`, `medicalCountryModule()`, `medicalLocalCode()`, `medicalCodeIgnored()`, `medicalOcrPatterns()`) and `assets/js/core/med.js` (`_medGs1Parse()`, `_medRegisterCountryModule()`, `_medLocalCode()`, `_medDetectCode()`, `_medOcrFindAic()`) — they read `data/medical_code_schemas.json` and ask the module. **Italy only**: `api/lib/med/italy.php` (`medicalItalyAicFromCode()`, `medicalItalyColumnAliases()`) + `assets/js/med/italy.js` (registered by the schema's `"module": "italy"`), because the AIC has three printed forms, a Code 39 form and a place in AI 710. The scan takes the AIC-shaped read first (a Code 39 of the bollino) and otherwise OCRs the label with `_medReadLabelOcr()` | | Medicine catalogue (names) | `api/lib/medicines.php` (`medicines` table, `medicineUpsert/FindByAic/Search`, `medicinesImportFile($db,$file,$opts,$aliases)` — the COLUMN NAMES come from the country module) + `scripts/import-medicines.php <csv\|xml\|json> --country=IT` (one importer, one module per country; JSON = the openFDA NDC shape; `--dry-run`, `--truncate`, `--limit`) + `GET med_lookup` + `_medShowCatalogueMatch()`/`_medUseMatch()` in the medicine form, `#med-dataset-block` in Settings. Never an API call | | Header: the versions | `.header-version` is a **bare semver** (reportError() reads it as the app version). The kiosk APK version is a second element, `#header-kiosk-version` ("kiosk 1.7.26"), from `_kioskBridge.getAppVersion()`; `_paintKioskVersion()` shows both only when the row fits — otherwise the kiosk label goes first, then `#header-branch` (a **work-in-progress build only**: `scripts/bump-version.sh` fills it from git on a feature branch and clears it on `main`/`develop`, and `:empty` hides it, so a released install shows the version and nothing else), then **the app NAME entirely** (`.header-title.is-name-hidden` → logo + version, never a clipped "E…"), and the version is raised a notch because it is then the only text there. The measurement only works because `.header-title` carries `min-width: 0`: as a flex item its default `min-width: auto` pinned it to the whole nowrap title, so it overflowed its clipping parent and `scrollWidth === clientWidth` at every viewport (the reason a phone showed "E -" while nothing was ever dropped). `hidden` flags are reset on each pass, so a rotation brings back what a narrow measurement removed. Re-measured on resize and after the translations | | A reload names its author | Every self-reload goes through `_reloadPage('why')` (language, backup restore, setup language, startup retry, pairing, API token) which logs `[RELOAD] why shelfy=… page=…` before reloading; a `pagehide` handler posts `[PAGEHIDE] reload:<why>` / `[PAGEHIDE] unload` with `fetch(…, {keepalive:true})` (the buffered logger would flush after the page is gone). `unload` with no `reload:` line = something OUTSIDE the page reloaded it (the kiosk's ↻, its watchdog, a new Activity) | | Auto-home on idle (2 min, **1 min with a search open**) | `_resetAutoHomeTimer()` is armed by the same idle listeners as the screensaver (`pointerdown`/`pointermove`/`keydown`/`scroll`/`touchstart`) and fires `_triggerAutoHome()`: after `AUTO_HOME_MS` (2 min) it calls `showPage('dashboard')`, but `_autoHomeDelayMs()` answers `AUTO_HOME_SEARCH_MS` (**1 min**) while the PANTRY is narrowed by a word — and `_triggerAutoHome()` then drops that search first (`_clearInventorySearchSilently()`, no focus so a kiosk never opens a keyboard) and re-renders the pantry unfiltered, because `_inventorySearchQuery` is restored on every visit: a forgotten search would otherwise show an empty/wrong shelf forever. Guards (never skipped): the idle screen, cooking mode, shopping, the in-store scan/add flows, and ANY open overlay (`_visibleOverlays()`) — those are the household using the app; `_noteVoiceActivity()` re-arms the clock because talking never touches the screen | | Screensaver (ambient dashboard) | **The views live in `assets/js/screensaver.js`** (own file, like `audit.js`); the idle clock in app.js (`activateScreensaver` / `dismissScreensaver`, `initInactivityWatcher`, `resetInactivityTimer`, `_screensaverTimeoutMs`, `_screensaverBlockedPage`) owns the timing, the pin and the dismissal, the engine owns what is on the screen. Four cards, all read from the household's data, each `null` when it has nothing to say (the rotation walks to the next): **meal** (`_ssViewMeal` + `_ssPickRecipe`: a recipe from the household's **own archive**, with «fatta N giorni fa» and «ti era piaciuta?» — the slot of the day is NOT a filter any more, filling a savoury crostini under «colazione» because the clock says nine was a guess; **a proposal must be VERIFIABLE** (`_recipeArchiveMissingInfo`: `checked` = a shelf snapshot existed, `pantry` = linked ingredients, `missing` = rows gone, `unknown` = no link and not a free staple water/salt/pepper/oil; `_ssPickRecipe()` refuses anything that is not `allInPantry` (`!checked || !pantry || !allInPantry` — a dish with ONE gone ingredient is not a proposal: the household reads a ⚠️ beside a recipe as «mi parla ancora di ricette con ingredienti che non ho», measured with a «pizza margherita con pizza alta regina» whose pizza is finished; no cookable recipe → the rotation walks to the next view) and the ✅ chip «Hai tutti gli ingredienti» is printed ONLY on `allInPantry` — `missing === 0` alone also means "nothing was checked", which is how a card ended up claiming it about ingredients that were finished: the old rule demanded a NUMERIC `qty_number` too, so every «q.b.»/«80-90 g» ingredient was skipped in silence, measured old `missing 0` vs new `missing 1` on «Maxi-Pancake al forno» with the sugar gone; `refreshAppDataAfterMutation()` drops the snapshot), fully-cookable scores highest, expiring ingredients weigh more, a recipe rated well weighs more, one cooked yesterday weighs less, and the same dish never appears twice in a row — `_ssLastRecipeId`; the two thumbs post `recipes_rate` through `_ssRate()`, and `_ssRatedNow` makes the card say «grazie» instead of asking again), **alerts** (`_ssViewAlerts`/`_ssAlertRows`: opened past its PAO window → expired → expiring ≤ 3 days, max 3 rows, each `data-ss-open` opening the product sheet; nothing to do → the 30-day milestone from `used_30d`/`wasted_30d`), **nutrition** (`_ssViewNutrition`: the `_buildNutritionData` pie + three rings + one insight from the weakest score) and **fact** (`_ssFactCandidates`: shopping list — **ranked by urgency before it names the two «più urgenti»**, because the list is ordered by when a row was added and the old code called a forgotten «Previsione» the most urgent thing to buy —, savings vs waste, weather + the first expiring, medicine cabinet, pantry shape). Layout: `#screensaver` → `.ss-stage` (the whole stage drifts a few pixels every `SS_PIXEL_SHIFT_MS` = 2.5 min, `transform` only, against burn-in) → `.ss-head` (clock + date + context pill with `weather_get` and the plan) → `.ss-core` (ONE `.ss-card`, `data-accent` emerald/amber/coral/sky) → `.ss-foot` (the vitals: `🛒 n in lista · €x · ⚠️ n in scadenza · 📦 n aperti`). **Interaction**: a tap flips the view (`_ssShowNext`), a swipe left/right does the same, a swipe up or **«Sblocca»** (`#screensaver-unlock`) dismisses, Esc dismisses — and the idle listeners **return early** while the screen is up (`initInactivityWatcher`), because a brush on the wall must not close it. **It always starts** after the timeout (`screensaver_timeout`, minutes) — on any page, with any sheet or a live scanner open: a wall screen is not something the household has to be idle for, so `_screensaverBlockedPage()` has ONE exception, **cooking mode** (`body.cooking-mode-active`: the recipe is the session). Entering it clears the pending clock, `closeCookingMode()` re-arms it, and `activateScreensaver()` stops both cameras (`stopScanner`, `_auditScanStop`) — a stream behind an opaque overlay is a LED and a heater for hours; `dismissScreensaver()` gives the scan page its reader back with `resumeScanner()`. **Forced runs** (`?screensaver[=N]` / «▶️ Anteprima 30 s») still work and are PINNED: `_screensaverPinned`, no dismissal from a tap, the pin bar names the next card (`_ssNextViewLabel`) and ✕ prints the time left. `scripts/i18n-audit.py` reads this file (it is in `SRC_JS`), and every label is four literal `t()` calls rather than one key built from a variable — a key the audit cannot see is a key that can go missing. Settings under Aspetto: four view switches → `SCREENSAVER_VIEWS`, pace → `SCREENSAVER_INTERVAL` (15/20/30/45/60/90 s, default 30), and `_applyScreensaverViewSettings` falls back to the nearest option for a value that comes from `.env`. **The change of card is a movement, not a cut**: the old card dissolves upward and the new one comes down from the top with its blocks in cascade — two phases in `_ssPaint` (`is-out` → swap → `is-pre` released on the next frame after a forced reflow, `SS_CARD_OUT_MS` matching `.ss-card` in style.css), `prefers-reduced-motion` falls back to a 200 ms fade, and a 700 ms safety timer clears the states anyway. `_ssNextFrame()` gives the fade step a timeout fallback: a hidden wall never calls `requestAnimationFrame`, and a card stuck at opacity 0 is a blank screen. On ≤640 px the pinned controls move to the bottom (they covered the clock on a 393 px screen) and the round shortcuts hide. **A phone is not a small tablet**: below 460 px the scale is one step smaller (clock 13vw, title 1.35 rem, chips 0.86 rem) and the card is `min-height: 0` + `justify-content: flex-start` — a flex column centred on content TALLER than its box pushes the first block above the top edge where no scroll can reach it (the recipe's eyebrow printed over the date); the portrait PANEL rules are `(orientation: portrait) and (min-width: 461px)` so they cannot come back through the cascade. The stage reserves the pinned bar's 152 px only when the bar is drawn (`body`-class `is-pinned`). **Portrait has its own scale** (`@media (orientation: portrait)`): every size above is tuned on the WIDTH of a landscape screen, so upright the clock/type/rings step up, the card becomes a full-width panel (`min-height: clamp(240px, 40vh, 520px)`, blocks centred, `.ss-rows` sharing the height with `space-evenly`), the context pill is an `inline-block` (a flex row dropped its `·` onto its own column when the text wrapped) and the place is shortened to its city (`_ssShortCity`) — «Bolzano, Trentino-Alto Adige, Italia» is an address, not a label. | Kiosk (Android WebView) | `KioskActivity.kt` (WebView surface colour, URL normalisation on resume, 5-min page watchdog, **`onConfigurationChanged()` that re-applies immersive mode instead of letting the Activity be recreated**), `themes.xml` (`windowBackground`), `SetupActivity.kt` (pairing wizard). The manifest declares **every** `configChanges`: a soft keyboard, a rotation or a locale switch must never rebuild the Activity, because a new Activity means a new WebView means the URL loaded again — on the wall that is "the app restarted". And **SHELFY never opens a keyboard on a kiosk**: `_isKioskDevice()` (`_kioskBridge` or `html.is-kiosk`) makes `_captureShowType()` refuse, hides the "Preferisco scrivere" link and keeps `_openCaptureSheetInner()` from focusing the field; the sheet says `capture.kiosk_no_voice` and the example phrases are one tap away (the WebView has no Web Speech at all, so the field was the only fallback — and focusing it is what reopened the app). `preloadBarcodeEngines()` also skips a kiosk: instantiating ZBar + the Tesseract core at boot is ~20 MB of WASM, the cheapest way to lose a low-RAM renderer (→ `onRenderProcessGone` → `recreate()` → "it restarted"). Every reload path is logged (`kiosk-create`, `kiosk-config-change`, `kiosk-resume-reload`, `page-watchdog-reload`, `renderer-crashed`) and lands in `data/error_reports.log` even when GitHub reporting is off. **Updates are downloaded by the app**: `DownloadManager` cannot reach a self-signed HTTPS LAN host and waits forever for an 'internet' network, so `triggerApkDownload()` streams the APK through `openTrustedConnection()` into the app folder with the progress on the banner (`install_download_ok` / `install_download_failed`). **The launch permissions are asked BEFORE the pin**: three dialogs (camera + microphone + photos) requested from inside `startLockTask()` killed a freshly installed wall at the camera grant — the server log had three `report_error` POSTs and **not one `index.html` request**, no `uncaught-exception` (a Java throw is saved and re-sent on the next start) and no `renderer-crashed` (a renderer needs a live Activity), i.e. a native kill inside the permission window; `startWhenPermissionsSettled()` asks the **camera only**, with no lock task and no WebView alive, `onRequestPermissionsResult()` completes the start (a denied camera still boots: "no scanner" is not "no app"), a page-side request suspends the pin for the dialog, `grant()` on a `PermissionRequest` that outlived its page is guarded (it throws `IllegalStateException` on the main thread), and `ErrorReporter.reportExitHistory()` posts the last five exits with their **reason numbers** on every boot because `REASON_SIGNALED` was silently filtered out. **And the wall says which version it is running, on every boot**: a native Toast (`launchWebView()`), the page banner `_showKioskBootVersion()` (APK + web app version, 9 s, 44 px ✕) and the `[KIOSK] boot version apk=… app=…` log line — `#header-kiosk-version` alone was not enough, because the fit drops it first | | OCR preprocessing (why not simply B/W) | Tesseract binarizes internally (Otsu), so a pure black-and-white copy is not a free win: one GLOBAL threshold on a phone photo of a glossy blister lets the lamp gradient decide the cut. The crop is upscaled ×3 first, then `_binarizeScanCanvas()` uses a **local** Bradley threshold (integral image, window = 1/8 of the short side, margin 0.15) and `_contrastScanCanvas()` does a 2%-98% histogram stretch + 3×3 sharpen; only two of the six rotating passes are preprocessed, the other four keep the raw pixels, so a clean label is never harmed. `_medDebugPass()` records the `prep` of each pass. Measured on a synthetic 40→240 gradient strip: the old global cut found 7140/168 ink pixels (paper eaten on the dark side, digits lost on the bright one), the local one 240/240 (= exactly the 480 strokes). | ## Anti-patterns to avoid (already present — do not copy) - **One undefined element in the scan panel stops the camera.** `_setScanMode()` runs right before `initScanner()` in `showPage('scan')`, so a `ReferenceError` inside it leaves a frozen frame and NO reader at all — while every symptom says "the OCR does not read". A removed button (`ocrBtn`, v1.28.0) did exactly that for a release. Keep the body inside the `try` wrapper (`_setScanModeInner`) and check the console before blaming the engine. - **A missing `}` does not fail — it nests.** Five functions were parsed inside `dismissBannerItemAfterAction()` and the banner threw "is not defined" while `node -c` stayed green. `php now brace-matches every shipped script and checks that each inline handler exists at top level. - Building HTML with string concatenation + `innerHTML` and inline `onclick` with un-escaped data. Prefer the existing `escapeHtml`. - Reading whole giant files to find one function — use the indexes / `grep -n`. - Writing to `.env` without escaping values (comment/quote/newline safe). ## See also - `docs/CODEBASE-MAP.md` — deep architecture, DB schema, data files, action catalog. - `docs/ROADMAP.md` — the product-facing roadmap: what is next, the effort involved, and which issues are open for grabs (the pinned #290 is the community entry point). - `docs/OPTIMIZATION-BACKLOG.md` — prioritized bugs, perf, CI, and technical debt. - `docs/ARCHITECTURE.md`, `docs/CORPORATE-UI.md`, `SECURITY.md`, `CONTRIBUTING.md`. - `.clinerules` — the short digest of this file, loaded automatically by Cline. - `.clineignore` — hides generated/binary/runtime/vendor files from the agent's context (gitignore syntax). Update it when a new generated folder appears. > Audit / review notes are **internal working documents**. They are kept in the > git-ignored `todo/` folder at the repo root and are intentionally never pushed: > this repository is public and everything committed must be in English. > > This includes the CI improvements that need a `workflow`-scoped PAT to push: > they live on the local branch `ci-tests-lint` and as > `todo/0001-ci-run-the-test-suite-lint-every-JS-file-shellcheck-.patch`. > Apply with `git am todo/0001-ci-*.patch` once a PAT with `workflow` scope is set.