# ofte — oops, forgot to eat

A phone-first meal reminder, food log and nutrition tracker that grows into a personal health assistant (supplements, sleep, water, activity, body metrics). It lives in the toolbox at `tools/public/ofte/` → `/ofte`, is fully static, and keeps everything in the browser. "ofte" is a working name.

Start here, then read the others as needed:

| File | What it is |
|---|---|
| `CLAUDE.md` | **Read first if you change code:** the data stability contract (people use this daily; their data must survive every update) |
| `README.md` | This file: what the app does, how it is built, how to run and test it, how to continue the work |
| `PLAN.md` | The architect's plan: goals, architecture, the Neon research for accounts, and every phase with subtasks |
| `TASKS.md` | The live checklist by phase. Update it when you finish or add work |
| `DECISIONS.md` | Judgment calls made while Austin was away, and open questions for him |
| `DATA-MODEL.md` | Exact record shapes, storage layout, the export file format, the compatibility contract and the format history |
| `SETUP-NEON.md` | Accounts on Neon: what was verified, setup steps for Austin, push-server plan, security checklist, families |
| `LEARNINGS.md` | Bugs found and lessons, so the next session does not repeat them |
| `info.md` | The short public write-up shown at `/ofte/info` |
| `meta.json` | Toolbox metadata (title, status, storage disclosure) |

## Using it

- **First run** asks for a detail level (from “just track eating” to every nutrient), a goal preset, the meal-gap reminder hours, units, and whether to load 65 starter foods. It can also restore a backup file instead.
- **Today** shows how long since you last ate against your meal-gap goal (green, amber, orange, red), a one-tap **I just ate**, quick-add chips for favorite and frequent foods and meals, today’s nutrition rings against goals with coverage notes (“1/2 items”) when values are missing, a **What would help today** card that suggests foods from your own cookbook for unmet minimums and names the biggest sources of anything near a limit, today’s meals, water quick-add, a supplement checklist, last night’s sleep and today’s activity. The arrows in the header step through past days.
- **Log a meal** (`#/log/new`, or tap a meal to edit it) has a date and time picker in the step you chose (5, 15 or 30 minutes; −1h, −15m, +15m, +1h and Now nudges), a meal type, an optional title, items, notes and an “estimate” flag. Search the cookbook to add a food or a whole meal template, or type any name and choose “Add without details” for a ballpark entry. Each item has a quantity in its serving unit, grams or ounces (when the food has a weight), +/− buttons, and **Nutrition for this meal**, where totals can be edited for this meal only (“edited for this meal”, with “Reset to cookbook values”). Saving with no items records that you ate. Extra actions: save as template, copy to now, discard changes, delete with undo.
- **Cookbook** (`#/foods`) lists foods and meal templates with search, sort, tag filters and favorites, plus a + to log any of them now. The food editor takes nutrition per serving or per 100 g (converted on save, needs the serving weight), tags, favorite, accuracy and notes. Starter foods can be removed (unused ones) and re-added without duplicates.
- **Goals** (`#/goals`): presets, per-nutrient at-least and at-most values, meal gap, meals per day, eating window, water, sleep hours and times, active minutes and steps. Saving dates the goals so history keeps the old ones for old days.
- **History** (`#/history`): 7, 14, 30, 90 days, a year or a custom range; group by day, week or month; choose metrics (any tracked nutrient, meals, longest gap, first meal time, water, sleep, activity, supplements, body metrics). Each metric gets a chart with goal lines (dashed green minimum, dashed red maximum) and bars colored on target, under or over, plus days-on-target. Below: where a nutrient comes from (top foods and shares, suggestions or lower alternatives), a day-by-day table, and a searchable, filterable meal list. Save and load named views (one can be the default), save frozen **snapshots**, and export CSV (days and meals) or an AI summary (Markdown).
- **Supplements**, **Sleep**, **Activity & water** and **Reminders** are under More on phones and in the side navigation on wide screens. Reminders can be exported as a `.ics` calendar for alerts while the app is closed.
- **Settings**: name, detail level and custom nutrients, units, time step, day start hour (default 4 a.m.), week start, quick water amounts, theme, storage status and “keep my data”, full or partial export, import with preview (merge or replace), restore points, AI summary, run setup again, erase everything (typed confirmation).

### Added in v0.2

- **Log menu.** The center button (or Log in the side navigation) opens one menu: meal, “I just ate”, shopping item, water amounts, screens off, going to sleep, woke up, sleep or nap, workout, supplements, measurement, and every event module that is on. New records show “Now” and take the moment Save is pressed; the pencil opens the date and time.
- **Modules** (`#/settings/modules`, also chosen in onboarding): food (always on), Kitchen, Food review, water, supplements, sleep, workouts, body measurements, symptoms, mood and energy, meditation, breathwork, social, routines, journal. Off hides a module from navigation, Today, the Log menu and History, and keeps its data.
- **Sleep** (`#/sleep`): log moments as they happen (they pair into a session) or add a session with optional screens-off, asleep and awake date-times; naps and several sleeps a day add up; “count toward a different day” overrides the default (the day you woke up).
- **Kitchen** (`#/kitchen`): What can I make (ready, 1–2 missing, all; add missing to the list; log it), In stock (quick add, have/low/out toggles, filters, shopping-cart toggle), Shopping list (check off as bought with undo, copy or share, add everything out or low, repeating items return). Item details: kind, category, stock, amount, low-at, location, list note, repeat interval, barcode, linked cookbook food, used in. Recipe editor at `#/kitchen/recipe/<food|template>/<id>`, also linked from the food and template editors.
- **Food review** (`#/review`): every food, meal and typed item eaten in a range, in a table (sticky first column, sortable headers, chosen nutrient columns) or cards; filters for verdict, unrated, “high in something” and symptoms after; saved views with a default; per-food notes page (`#/review?note=<key>`) with verdict, tags, notes and alternatives; CSV and an AI export.
- **Event modules** (`#/m/<type>`): a 14-day chart and entries by day, and a generic editor built from the field definitions in `core/modules.js`. Routines (`#/routines`) have their own checklist editor.
- **Settings hub**: Modules, Data & updates (format version, migration log, import older backups, data check), Online lookups (barcode consent), Developing (in-app roadmap), Terms and Privacy drafts.

## How it is built

- Plain ES modules, no framework, no dependencies, no build step. `index.html` loads `assets/js/app.js`. Styles are one file, `assets/app.css`, with light and dark tokens.
- `assets/js/core/` is DOM-free logic and is unit tested in Node: `time.js` (day keys with a day-start hour, steps, formatting), `nutrients.js` (catalog, daily values, detail levels), `nutrition.js` (items, totals, coverage, contributors, suggestions), `goals.js` (presets, versioning, evaluation), `schema.js` (defaults, normalizers, migrations), `backup.js` (export, import validation, merge and replace), `reminders.js` (due reminders, meal gap, `.ics`), `summary.js` (day summaries, series, grouping, AI summary), `starter-foods.js`.
- `assets/js/data/db.js` is the store: IndexedDB with an in-memory cache (synchronous reads), ordered async writes with error reporting, a localStorage fallback, a memory-only last resort with a red banner, cross-tab updates over `BroadcastChannel`, and restore points. `data/drafts.js` keeps form drafts in localStorage.
- `core/modules.js` (module registry and event-module field definitions), `core/sleep.js` (pairing sleep taps into sessions), `core/kitchen.js` (can make, recurring purchases, shopping text, category guesses), `core/review.js` (eaten rows, flags, symptom links, AI export) and `core/off.js` (Open Food Facts mapping) are DOM-free like the rest of the core. `content/developing.js` and `content/legal.js` hold the text of the Developing, Terms and Privacy pages.
- `assets/js/store.js` sits on top, and runs data migrations at start-up (`runMigrations`): settings, versioned goals, cached summaries, save helpers that bump use counts, starter library, export, import and restore.
- `assets/js/app.js` is the shell and hash router. Views in `assets/js/views/` export `{ title, live, render(ctx) }`; `live: false` (editors) means data changes do not re-render the page under the person’s fingers. `ctx.dispose` runs when leaving a page (drafts flush there). `reminders-runtime.js` checks reminders and the meal gap every 30 seconds while open.
- `sw.js` caches the app network-first for offline use; `manifest.webmanifest` and `icons/` make it installable. Bump `VERSION` in `sw.js` and `APP_VERSION` in `core/constants.js` on release; add any new module file to the `CORE` list in `sw.js`.
- `window.__ofte` exposes `{ store, db, render }` for debugging and tests. Nothing in the UI depends on it.

## Running and testing

From the repo root:

```
npm run dev                                   # toolbox build + server, then open http://localhost:4173/ofte/
node --test tools/public/ofte/tests/unit/*.test.mjs
node tools/public/ofte/tests/e2e/flows.mjs   # needs Playwright + Chromium; add --shots <dir> for screenshots
```

The unit tests (`core.test.mjs`, `v2.test.mjs`) cover the core in any time zone, including importing a format 1 backup (run them with `TZ=Pacific/Auckland` and friends). The end-to-end script starts its own static server and drives a 390 px phone viewport through onboarding, logging, per-meal edits, drafts surviving a reload, retroactive meals, a per-100 g food, goals, supplements, sleep, water, workouts, weight in pounds, reminders and calendar export, history views and snapshots, export then erase then import, reload persistence, every route in light and dark without sideways scroll, the desktop layout, the localStorage fallback, and zero console errors; since v0.2 also the Log menu and sleep taps, a late-night sleep past midnight, modules on and off without data loss, the Kitchen flow, symptoms and Food review notes with the AI export, routines, a mocked Open Food Facts barcode lookup, the Settings sub-pages, and a real upgrade of a format 1 browser database (26 checks). If Playwright is installed globally, prefix with `NODE_PATH=$(npm root -g)` or set `PLAYWRIGHT_MODULE_DIR`. `dev/make-icons.mjs` regenerates the app icons, the favicon and the animated Toolbox card thumbnail (`shell/images/thumbs/ofte.svg` plus `ofte.static.svg` for reduced motion) from one geometry.

## Showcase

The explainer shows ofte as it should feel, which is ahead of the current UI. `DESIGN-DIRECTION.md` explains how it was made, compares it screen by screen with the app, and lists the steps to get there.

`showcase/` holds ofte's trailers, served at `/ofte/showcase/` (the toolbox build adds the index page, the Trailer button on the card and the Trailer block on the info page; see "Showcase" in the root `README.md`). It uses the same player contract as Facet's showcase, with its own copy of the player (`showcase/lib/player.js`, global `OfteShowcase`, warm palette) and a drawing kit (`showcase/lib/ofte-draw.js`: palette, easing, the animated plate mark, vector icons, cards and pills; no emoji, since the render machine has no colour emoji font).

- `explainer-v1` (primary): a 26 second square explainer drawn in a centred 1080 × 1080 stage. A busy day rushes past a plate-clock, the rim turns red as the gap since the last meal grows, a nudge appears and one tap logs a snack; then the Log menu, the Kitchen (what you can make, add the missing item to the shopping list), Food review (good foods and problem foods) and the logo.
- `logo-v1`: a 4 second seamless loop of the mark, rendered three times over in wide, vertical and square. The ring fades out just before the loop point so the last frame matches the first.

Render from the repo root with `node scripts/render-showcase.mjs ofte <slug> [--formats square]` (add `PLAYWRIGHT_MODULE_DIR=$(npm root -g)` if Playwright is global). Scenes must stay pure functions of `t`: no clocks, no `Math.random`.

## Moving out of the toolbox

The folder is self-contained, so moving it is a copy: put the folder’s contents at the root of a new static site (any host; Vercel with no build step works) and it runs as is, because every path is relative. The browser keeps data per origin, so people on `app.austinpranger.com/ofte` would need to export and import once on the new address (or the phase 3 sync moves it). Remove `meta.json`, `info.md` and the thumbnail from the toolbox, or turn the toolbox entry into an `external` redirect card like Hearth’s.

## Continuing the work

1. Read `TASKS.md` for the next unchecked items and `DECISIONS.md` for open questions; Austin’s answers may already be in a newer commit.
2. Keep the core DOM-free and add unit tests for any new logic; extend `tests/e2e/flows.mjs` for any new flow.
3. Changing a stored shape means bumping `SCHEMA_VERSION` and adding a migration in `core/schema.js`, plus updating `DATA-MODEL.md`.
4. Log non-obvious bugs in `LEARNINGS.md` (and the repo’s `KNOWN-ISSUES.md` if they would bite other tools).
5. Follow the repo rule: no hard-wrapped paragraphs in `.md` files.
