Planning inputs are prepared before ranking#
planning-service.ts is a deterministic service. PlanWeekInput includes day configurations, eligible recipes, optional ratings/history, pinned wishes, default servings, an optional meal restriction, week start, recent recipe uses and already-reserved recipe IDs.
Recipe facts include preparation/cooking minutes, meal eligibility, favorites, ingredient IDs/categories, pantry coverage and offer matches. The provider builds these through selectors.ts and filters preferences before calling the planner.
planWeekdoes not independently inspect every allergy. The safety boundary is the preference-filtering pipeline feeding it. Any new caller must preserve that filtering; an AI prompt is not a substitute.
preference-service.ts owns allergy/dislike matching and diet eligibility. meal-settings-service.ts owns per-meal modes, enabled state and recipe compatibility.
How a week is assembled#
planWeek:
- Derives average ratings from history.
- Builds recipe lookup tables, usage counts, ingredient sets and recency penalties.
- Registers existing reservations and compatible pinned recipes before automatic choices.
- Expands each day into breakfast, lunch and dinner; snacks are included when explicitly enabled/requested.
- Orders requests by scarcity of suitable candidates so a flexible meal does not consume the only recipe fitting a constrained one.
- Honors pins and explicit leftovers/free-text/blank wishes.
- Produces empty slots for no-cook mode and placeholders for leftovers mode.
- Chooses cook/eating-out candidates, recording warnings when choices are missing or repeats are necessary.
- Restores output order to the requested day/meal order.
If no candidate fits, the result is an empty slot and a warning—not a magically valid recipe invented by the planner.
Eligibility and ranking#
cookCandidates filters by meal type, whether the recipe represents eating out, and available time. Cook-mode candidates must fit the cooking budget. Eating-out selection follows its separate mode.
The ranking in decideCook is lexicographic:
- Fewest uses already reserved/chosen in this week.
- Highest
scoreRecipescore. - Deterministic week-based rotation rank when a week key is available.
- Recipe integer ID as final tie-breaker.
This matters: a huge pantry bonus cannot make a repeated recipe beat an eligible unused one merely by outweighing a fixed repeat penalty.
What the score rewards#
| Factor | Current scoring behavior |
|---|---|
| Fits available time | Base bonus plus bounded spare-time bonus |
| Rating | Average/default rating multiplied by four |
| Repeated weekly use | Penalty of 25 per use |
| Recent use | Additional recency penalty |
| Favorite | Small bonus of two |
| Ingredient reuse | Up to five reused ingredients, four points each |
| Near-duplicate ingredient sets | Penalty for high-overlap recipes, avoiding nominal variety only |
| Offers | Up to five matched ingredients, three points each |
| Produce | Up to five produce entries, 1.5 points each |
| Pantry stock | Up to five stocked ingredients, five points each |
| Expiring ingredients | Up to five used expiring ingredients, eight points each |
These weights are implementation details, not a nutritional guarantee or proof of the cheapest possible week. The planner balances heuristics; it is not an exhaustive price optimizer.
planGap fills a single meal using the same candidate/score machinery without replacing the remainder of the week. recipeRecencyPenalties and recipeRotationRank keep rotation deterministic instead of using unseeded randomness.
Editing, cooking and recipe history#
plan-edit-service.ts identifies editable targets and meal summaries. recipe-service.ts computes recipe meal types, cooking time, search matching and ratings. database/recipe-uses.ts supplies actual recent uses before a target week.
An explicit cooked marker and rating are durable user history. A generated recommendation is not evidence the meal was actually cooked. Preserve that distinction when feeding future recency and rating calculations.
Batch cooking and leftovers#
batch-cooking-service.ts implements planBatchCooking, batchCookServings, leftoverSources, planLeftoverLink, batchMealDetails and home-change validation. database/batch-meals.ts persists links.
A slot's batch_source_uuid references the source cook event. The source must provision the necessary servings; a leftover slot must not independently request the same raw ingredients again. Home changes also need checking so a linked meal does not accidentally consume food attributed to another location.
A batchFriendly recipe tag alone does not force the automatic planner to repeat that recipe. Explicit user batch reservations define the relationship.
Shopping-list derivation#
buildShoppingList accepts planned meals, optional pantry lookups and best matched deals. Each meal includes home, planned servings, recipe servings and ingredient quantities.
recipe ingredient quantity
× planned servings / recipe servings
→ aggregate by home + ingredient + compatible unit family
→ subtract suitable pantry stock
→ attach best available deal metadata
→ sort and group into shopping output
aggregateIngredients converts kilograms to grams and liters to milliliters for aggregation. It preserves count-unit distinctions: pieces, tablespoons and cloves are not automatically interchangeable. Mass is not converted to volume using an invented density.
For example, a two-serving recipe with 500 g tomatoes planned for four servings needs 1000 g. A second meal needing 250 g at the same home raises the aggregate to 1.25 kg. A different home gets a separate requirement.
Pantry subtraction is delegated to pantry-service.ts. Expiry/default shelf-life calculations live in expiry-service.ts, rather than being embedded in list rendering.
Sorting and price limitations#
finalizeShoppingList sorts by home, then the configured aisle route, then label. The aisle route is produce, bakery, meat/fish, dairy, frozen, pantry, drinks, household and other.
The result reports priced and unpriced line counts. Its estimatedTotalCents sums the attached line prices, and savings sums attached savings. In this reviewed implementation, it does not multiply every offer by required pack counts or solve a cross-store basket optimization. Unpriced items contribute zero to that estimate.
Do not present this estimate as a complete guaranteed checkout total. A display change promising exact cost would need additional unit/package/currency logic and tests, not just a renamed label.
Manual items and checked state#
Generated rows are derived caches and can be rebuilt. Manual shopping rows represent explicit user intent and must survive regeneration. Checked state is also separate: shopping_checks uses a portable key built from week, home, ingredient and unit identities.
The sync table list uploads only manual shopping_items, plus separate shopping_checks. Uploading all generated rows would let multiple devices compete over a projection they can independently rebuild.
Testing the domain#
Use fixed expected-result tests for constraints, scarce recipes, duplicate avoidance, rotation, allergen filtering, leftovers, servings scaling, incompatible units, multiple homes and incomplete prices. Snapshots of whatever the planner currently emits are not enough to establish financial or food-safety intent.