From ee65715a6919701d22e977b1a3e51123e9a3f613 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 28 Nov 2026 23:35:22 -0500 Subject: [PATCH] fix(tkc): stabilize recipe generation metadata recovery and image refresh --- server/metadataRecovery.ts | 401 ++++++++++++------ src/App.tsx | 30 +- src/application/imageSaveRefresh.ts | 40 ++ src/components/CreateForMeModal.tsx | 10 +- src/components/VaultIntelligenceModal.tsx | 22 +- src/schema/generatedRecipe.ts | 40 +- src/utils/vaultIntelligence.ts | 72 +++- tests/fixtures/smokedChicken.ts | 76 ++++ tests/unit/aiConsumerMigration.test.ts | 6 +- tests/unit/createForMeDraftView.test.tsx | 49 ++- tests/unit/createForMeSave.test.ts | 24 ++ tests/unit/createForMeSaveUi.test.tsx | 30 ++ tests/unit/generatedRecipeSchema.test.ts | 58 +++ tests/unit/imageSaveRefresh.test.ts | 68 +++ tests/unit/metadataRecovery.test.ts | 133 +++++- tests/unit/nutritionEstimatorSafety.test.ts | 3 +- .../vaultIntelligenceBatchRecovery.test.tsx | 82 ++++ .../vaultIntelligenceRecoverySafety.test.ts | 102 +++++ 18 files changed, 1067 insertions(+), 179 deletions(-) create mode 100644 src/application/imageSaveRefresh.ts create mode 100644 tests/fixtures/smokedChicken.ts create mode 100644 tests/unit/imageSaveRefresh.test.ts create mode 100644 tests/unit/vaultIntelligenceBatchRecovery.test.tsx create mode 100644 tests/unit/vaultIntelligenceRecoverySafety.test.ts diff --git a/server/metadataRecovery.ts b/server/metadataRecovery.ts index 7c55672..12691aa 100644 --- a/server/metadataRecovery.ts +++ b/server/metadataRecovery.ts @@ -62,6 +62,110 @@ function cleanWikilinks(text: string): string { .replace(/\[\[([^\]]+)\]\]/g, "$1"); } +/** Below this per-serving calorie figure, a recovered estimate is not credible. */ +const MIN_RECOVERED_CALORIES_PER_SERVING = 20; + +const PASSIVE_DURATION_CONTEXT = + /\b(?:refrigerat\w*|chill\w*|cool\w*|freez\w*|rest\w*|marinat\w*|brine|brining|dry[-\s]?brine|sit|standing|overnight)\b/i; + +const ACTIVE_COOKING_CONTEXT = + /\b(?:bake|baking|roast|roasting|cook|cooking|simmer|boil|fry|frying|saut[eé]|grill|smoke|smoking|braise|steam|broil|poach|sear|blanch|air[-\s]?fry|pressure[-\s]?cook)\b/i; + +interface StepDurationSummary { + readonly activeMinutes: number; + readonly passiveMinutes: number; + readonly passiveMentions: number; + /** Active durations expressed as ranges cannot yield a precise cook time. */ + readonly impreciseActiveMentions: number; +} + +/** + * Extracts durations from instruction text while separating ACTIVE cooking + * from passive preparation (refrigeration, chilling, resting, brining, + * marinating, freezing). Passive durations must never be summed into cook time. + * + * The parser is deliberately conservative: a clause that contains both an + * active and a passive verb is treated as passive rather than inflating cook + * time. Ambiguous durations are omitted, not guessed. + */ +function summarizeStepDurations(steps: readonly string[]): StepDurationSummary { + let activeMinutes = 0; + let passiveMinutes = 0; + let passiveMentions = 0; + let impreciseActiveMentions = 0; + for (const step of steps) { + const segments = step + .split(/[.;]\s*|,?\s*\bthen\b\s*|\s+\band\b\s+/i) + .map((segment) => segment.trim()) + .filter(Boolean); + for (const segment of segments) { + const hours = segment.match(/(\d+(?:\.\d+)?)\s*(?:hours?|hrs?)\b/i); + const minutes = segment.match(/(\d+)\s*(?:minutes?|mins?|min)\b/i); + const value = hours + ? Math.round(parseFloat(hours[1]) * 60) + : minutes + ? parseInt(minutes[1], 10) + : null; + if (value === null || value <= 0) continue; + const passive = PASSIVE_DURATION_CONTEXT.test(segment); + const active = ACTIVE_COOKING_CONTEXT.test(segment); + // "45–60 minutes", "45 to 60 minutes", and "45 minutes to 60 minutes" + // are ranges. An active range makes the cook duration imprecise; do not + // turn its upper/lower bound into a high-confidence total. + const range = + /\d+(?:\.\d+)?\s*(?:-|–|—|to)\s*\d+(?:\.\d+)?\s*(?:hours?|hrs?|minutes?|mins?|min)\b/i.test(segment) || + /\d+\s*(?:hours?|hrs?|minutes?|mins?)\s*(?:-|–|—|to)\s*\d+\s*(?:hours?|hrs?|minutes?|mins?)/i.test(segment); + if (range) { + if (passive) { + passiveMentions += 1; + } else if (active) { + impreciseActiveMentions += 1; + } + continue; + } + if (passive) { + passiveMinutes += value; + passiveMentions += 1; + } else if (active) { + activeMinutes += value; + } + } + } + return { activeMinutes, passiveMinutes, passiveMentions, impreciseActiveMentions }; +} + +function durationToMinutes(value: string, unit: string): number { + const amount = parseFloat(value); + if (!Number.isFinite(amount) || amount <= 0) return 0; + return /^h/i.test(unit) ? Math.round(amount * 60) : Math.round(amount); +} + +function findLabelledDuration(text: string, labels: string): number | null { + const match = text.match( + new RegExp(`(?:${labels})\\s*[:\\-–]?\\s*(?:for\\s+)?(\\d+(?:\\.\\d+)?)\\s*(hours?|hrs?|minutes?|mins?)`, "i") + ); + if (!match) return null; + const minutes = durationToMinutes(match[1], match[2]); + return minutes > 0 ? minutes : null; +} + +function parseTimeString(value: string | undefined): number | null { + if (typeof value !== "string" || !value.trim()) return null; + const hours = value.match(/(\d+(?:\.\d+)?)\s*(?:hours?|hrs?)\b/i); + const minutes = value.match(/(\d+)\s*(?:minutes?|mins?|min)\b/i); + if (hours) return Math.round(parseFloat(hours[1]) * 60) + (minutes ? parseInt(minutes[1], 10) : 0); + if (minutes) return parseInt(minutes[1], 10); + return null; +} + +function formatMinutes(total: number): string { + const hours = Math.floor(total / 60); + const minutes = total % 60; + if (total < 60) return `${total} mins`; + if (minutes > 0) return `${hours} hr ${minutes} mins`; + return `${hours} ${hours === 1 ? "hr" : "hrs"}`; +} + /** * Fallback algorithmic metadata recovery engine for when Gemini is unavailable or rate limited. */ @@ -71,14 +175,23 @@ export function recoverMetadataAlgorithmically( const title = (req.title || "Untitled Recipe").trim(); const rawMarkdown = req.rawMarkdown || ""; - // Parse ingredient lines + // Parse ingredient lines. `rawIngs` keeps the authored amount/unit text for + // nutrition; `classificationIngs` uses the ingredient NAME only so a + // preparation phrase ("seasoned under the skin") cannot classify the dish. const rawIngs: string[] = []; + const classificationIngs: string[] = []; if (req.ingredients && Array.isArray(req.ingredients)) { for (const item of req.ingredients) { - if (typeof item === "string" && item.trim()) rawIngs.push(cleanWikilinks(item.trim())); - else if (item && typeof item === "object") { + if (typeof item === "string" && item.trim()) { + const line = cleanWikilinks(item.trim()); + rawIngs.push(line); + classificationIngs.push(line); + } else if (item && typeof item === "object") { const line = item.original || `${item.amount || ""} ${item.unit || ""} ${item.name || ""}`.trim(); if (line) rawIngs.push(cleanWikilinks(line)); + const name = typeof item.name === "string" ? item.name.trim() : ""; + if (name) classificationIngs.push(cleanWikilinks(name)); + else if (line) classificationIngs.push(cleanWikilinks(line)); } } } @@ -94,60 +207,73 @@ export function recoverMetadataAlgorithmically( const allText = `${title}\n${rawMarkdown}\n${rawSteps.join("\n")}\n${rawIngs.join("\n")}`.toLowerCase(); - // 1. Scan for explicit timings in text - let extractedCookMins = 0; - for (const step of rawSteps) { - const minMatch = step.match(/(\d+)\s*(?:minutes|minute|mins|min)\b/i); - const hrMatch = step.match(/(\d+(?:\.\d+)?)\s*(?:hours?|hrs?)\b/i); - if (hrMatch) { - extractedCookMins += Math.round(parseFloat(hrMatch[1]) * 60); - } else if (minMatch) { - extractedCookMins += parseInt(minMatch[1], 10); - } - } - - // Heuristic Cook Time — only emit when there is real evidence. Prefer absence - // over a fabricated default ("20 mins") that the recovery UI would otherwise - // surface as a confidently-recovered value. Inference branches are still - // labelled `medium`/`culinary_inference` so the modal shows them as guesses. + // 1. Timing evidence. Only explicit ACTIVE cooking durations become cook + // time; passive chilling/resting/marinating never do. There is no + // ingredient-count prep estimate. Existing authored values are never + // proposed back to the user as a "recovery". type RecoveredText = { value: string; confidence: "high" | "medium" | "low"; source: "instructions_explicit" | "body_parsed" | "culinary_inference"; explanation: string }; + const existing = req.existingMetadata || {}; + const existingPrep = typeof existing.prepTime === "string" && existing.prepTime.trim() ? existing.prepTime.trim() : ""; + const existingCook = typeof existing.cookTime === "string" && existing.cookTime.trim() ? existing.cookTime.trim() : ""; + const existingTotal = typeof existing.totalTime === "string" && existing.totalTime.trim() ? existing.totalTime.trim() : ""; + const existingCategory = typeof existing.category === "string" && existing.category.trim() && !/^general$/i.test(existing.category.trim()) + ? existing.category.trim() + : ""; + const existingCuisine = typeof existing.cuisine === "string" && existing.cuisine.trim() && !/^general$/i.test(existing.cuisine.trim()) + ? existing.cuisine.trim() + : ""; + const stepDurations = summarizeStepDurations(rawSteps); + const explicitPrep = + findLabelledDuration(rawMarkdown, "prep(?:[\\s_]*time)?") ?? + findLabelledDuration(rawSteps.join("\n"), "prep(?:[\\s_]*time)?"); + const explicitTotal = + findLabelledDuration(rawMarkdown, "total(?:[\\s_]*time)?") ?? + findLabelledDuration(rawSteps.join("\n"), "total(?:[\\s_]*time)?"); + let cookTime: RecoveredText | undefined; - let cookMinutes: number | null = null; - - if (extractedCookMins > 0) { - cookMinutes = extractedCookMins; - const h = Math.floor(extractedCookMins / 60); - const m = extractedCookMins % 60; - const value = - extractedCookMins < 60 - ? `${extractedCookMins} mins` - : m > 0 - ? `${h} hr ${m} mins` - : `${h} ${h === 1 ? 'hr' : 'hrs'}`; + if (stepDurations.activeMinutes > 0 && stepDurations.impreciseActiveMentions === 0 && !existingCook) { + const passiveNote = stepDurations.passiveMentions > 0 + ? ` Passive durations (${formatMinutes(stepDurations.passiveMinutes)}) were excluded because they are not cooking time.` + : ""; cookTime = { - value, + value: formatMinutes(stepDurations.activeMinutes), confidence: "high", source: "instructions_explicit", - explanation: `Calculated from specific cooking durations mentioned in the instructions (${extractedCookMins} mins)`, + explanation: `Sum of explicit ACTIVE cooking durations in the instructions (${stepDurations.activeMinutes} mins).${passiveNote}`, }; - } else if (allText.includes("rub") || allText.includes("seasoning") || allText.includes("marinade") || allText.includes("dressing")) { - cookMinutes = 0; - cookTime = { value: "0 mins", confidence: "medium", source: "culinary_inference", explanation: "Seasoning/rub blend requires no cooking time" }; - } else if (allText.includes("slow cooker") || allText.includes("crockpot")) { - cookMinutes = 240; - cookTime = { value: "4 hrs", confidence: "medium", source: "culinary_inference", explanation: "Inferred from slow-cooker method" }; - } else if (allText.includes("bake") || allText.includes("roast")) { - cookMinutes = 35; - cookTime = { value: "35 mins", confidence: "medium", source: "culinary_inference", explanation: "Estimated typical oven baking duration" }; } - // Heuristic Prep Time (bounded inference derived from ingredient count) - let prepMins = Math.min(30, Math.max(5, (rawIngs.length || 5) * 2)); - if (allText.includes("rub") || allText.includes("seasoning")) prepMins = 5; - const prepTimeStr = `${prepMins} mins`; + let prepTime: RecoveredText | undefined; + if (explicitPrep !== null && !existingPrep) { + prepTime = { + value: formatMinutes(explicitPrep), + confidence: "high", + source: "body_parsed", + explanation: "Explicit prep time stated in the recipe text.", + }; + } - // Heuristic Servings — only emit when an explicit yield exists or the recipe is - // clearly a batch rub/seasoning. Never fall back to a baked-in "4 servings". + const prepForTotal = explicitPrep ?? parseTimeString(existingPrep); + let totalTime: RecoveredText | undefined; + if (!existingTotal) { + if (explicitTotal !== null) { + totalTime = { + value: formatMinutes(explicitTotal), + confidence: "high", + source: "body_parsed", + explanation: "Explicit total time stated in the recipe text.", + }; + } else if (prepForTotal !== null && stepDurations.activeMinutes > 0 && stepDurations.impreciseActiveMentions === 0) { + totalTime = { + value: formatMinutes(prepForTotal + stepDurations.activeMinutes), + confidence: "medium", + source: "culinary_inference", + explanation: `Sum of explicit prep (${formatMinutes(prepForTotal)}) and active cooking (${formatMinutes(stepDurations.activeMinutes)}); passive durations are excluded.`, + }; + } + } + + // Servings — only an explicit yield is evidence. No batch-size guess. let estimatedServings: number | undefined; let servingsConf: "high" | "medium" | "low" = "medium"; let servingsExplanation = ""; @@ -157,143 +283,154 @@ export function recoverMetadataAlgorithmically( estimatedServings = parseInt(servMatch[1], 10); servingsConf = "high"; servingsExplanation = `Extracted from recipe notes: ${servMatch[0]}`; - } else if (allText.includes("rub") || allText.includes("seasoning")) { - estimatedServings = 12; - servingsExplanation = "Yield estimated for spice rub batch (~12 portions)"; } - // The offline nutrition estimator always returns TOTAL batch nutrition, so a - // serving count is only a label; fall back to a neutral number for labelling - // without fabricating a recovered servings field. - const nutritionServings = estimatedServings ?? 4; - - // Heuristic Cuisine & Category - let cuisine = "General"; - let category = "Main Course"; + // Classification uses the TITLE and INGREDIENTS only. Instruction prose is + // not evidence of a category: "place on a baking sheet" does not make a + // chicken recipe Baking & Breads. + const classificationText = `${title}\n${classificationIngs.join("\n")}`.toLowerCase(); + const titleText = title.toLowerCase(); const tags: string[] = ["food/recipes"]; - if (allText.includes("hawaiian") || allText.includes("aloha") || allText.includes("poke") || allText.includes("luau")) { + let cuisine: string | undefined; + if (/\b(?:hawaiian|aloha|poke|luau)\b/.test(classificationText)) { cuisine = "Hawaiian"; tags.push("hawaiian"); - } else if (allText.includes("italian") || allText.includes("pasta") || allText.includes("parmesan") || allText.includes("guanciale") || allText.includes("risotto")) { + } else if (/\b(?:italian|pasta|parmesan|guanciale|risotto)\b/.test(classificationText)) { cuisine = "Italian"; tags.push("italian"); - } else if (allText.includes("japanese") || allText.includes("ramen") || allText.includes("miso") || allText.includes("matcha") || allText.includes("shoyu")) { + } else if (/\b(?:japanese|ramen|miso|matcha|shoyu)\b/.test(classificationText)) { cuisine = "Japanese"; tags.push("japanese"); - } else if (allText.includes("thai") || allText.includes("curry") || allText.includes("coconut milk") || allText.includes("fish sauce")) { + } else if (/\b(?:thai|curry|coconut milk|fish sauce)\b/.test(classificationText)) { cuisine = "Thai"; tags.push("thai"); - } else if (allText.includes("mexican") || allText.includes("taco") || allText.includes("salsa") || allText.includes("cilantro")) { + } else if (/\b(?:mexican|taco|salsa|cilantro)\b/.test(classificationText)) { cuisine = "Mexican"; tags.push("mexican"); - } else if (allText.includes("french") || allText.includes("sourdough") || allText.includes("boule")) { + } else if (/\b(?:french|sourdough|boule)\b/.test(classificationText)) { cuisine = "French"; tags.push("french"); - } else if (allText.includes("bbq") || allText.includes("barbecue") || allText.includes("rib")) { + } else if (/\b(?:bbq|barbecue|barbecued|smoked|smoker)\b/.test(classificationText)) { cuisine = "American BBQ"; tags.push("bbq", "american"); } - if (allText.includes("rub") || allText.includes("seasoning") || allText.includes("spice blend")) { + let category: string | undefined; + if (/\b(?:rub|seasoning|spice blend|dry rub)\b/.test(titleText)) { category = "Seasonings & Rubs"; tags.push("seasoning", "dry-rub"); - } else if (allText.includes("soup") || allText.includes("stew") || allText.includes("ramen") || allText.includes("broth")) { + } else if (/\b(?:soup|stew|ramen|broth)\b/.test(classificationText)) { category = "Soups & Stews"; tags.push("soup"); - } else if (allText.includes("salad") || allText.includes("dressing")) { + } else if (/\b(?:salad|slaw)\b/.test(classificationText)) { category = "Salads & Bowls"; tags.push("salad"); - } else if (allText.includes("bread") || allText.includes("sourdough") || allText.includes("baking")) { + } else if (/\b(?:bread|sourdough|boule|baguette|yeast|dough|baking powder|baking soda)\b/.test(classificationText)) { category = "Baking & Breads"; tags.push("baking", "bread"); - } else if (allText.includes("dessert") || allText.includes("cake") || allText.includes("chocolate") || allText.includes("cookie")) { + } else if (/\b(?:dessert|cake|cookie|chocolate|pie|tart)\b/.test(classificationText)) { category = "Dessert"; tags.push("dessert", "sweet"); - } else if (allText.includes("pasta") || allText.includes("spaghetti") || allText.includes("carbonara")) { + } else if (/\b(?:pasta|spaghetti|carbonara|lasagna|noodle)\b/.test(classificationText)) { category = "Pasta"; tags.push("pasta"); } - // Nutrition estimation. A recipe with NO usable ingredient lines has nothing - // estimable: skip estimation entirely and return nutrition as ABSENT (never a - // synthetic `1 portion ingredients` sentinel and never a zero-valued object - // that looks evaluated). Unrelated metadata recovery continues normally. - const nutResult = - rawIngs.length > 0 ? estimateAlgorithmicNutrition(title, nutritionServings, rawIngs) : undefined; + // Nutrition estimation. The offline estimator returns TOTAL batch values. + // A recovered calories field is PER-SERVING, so the batch total is divided by + // an EXPLICIT serving count. Incomplete coverage or implausibly low per-serving + // values are omitted rather than presented as credible nutrition. Existing + // authored calories are never re-proposed. + const existingServings = typeof existing.servings === "number" && Number.isFinite(existing.servings) && existing.servings > 0 + ? Math.floor(existing.servings) + : undefined; + const nutritionServings = existingServings ?? estimatedServings; + const existingCalories = existing.calories !== undefined && existing.calories !== null && String(existing.calories).trim() !== ""; + const nutResult = rawIngs.length > 0 && nutritionServings !== undefined && !existingCalories + ? estimateAlgorithmicNutrition(title, nutritionServings, rawIngs) + : undefined; + const completeNutrition = nutResult?.assessment?.complete === true && nutResult.assessment.trustedBasis === true; + const perServingCalories = completeNutrition && nutritionServings !== undefined + ? Math.round(nutResult!.calories / nutritionServings) + : undefined; + const nutritionEligible = + completeNutrition && + perServingCalories !== undefined && + perServingCalories >= MIN_RECOVERED_CALORIES_PER_SERVING; const result: MetadataRecoveryResult = { - prepTime: { - value: prepTimeStr, - confidence: "medium", - source: "culinary_inference", - explanation: `Estimated prep time based on ingredient count (${rawIngs.length} ingredients)`, - }, - totalTime: cookTime - ? { - value: `${prepMins + (cookMinutes ?? 0)} mins`, - confidence: "medium", - source: "culinary_inference", - explanation: "Sum of estimated prep and cook times", - } - : undefined, - ...(nutResult + ...(nutritionEligible ? { calories: { - value: nutResult.calories, - confidence: "medium" as const, + value: perServingCalories!, + confidence: "low" as const, source: "culinary_inference" as const, - explanation: `Total nutrition for the entire recipe batch across ${nutritionServings} servings (curated local food reference)`, + explanation: + `Complete curated-reference batch estimate: ${nutResult!.calories} kcal total across ${nutritionServings} servings ` + + `(${perServingCalories} kcal per serving). Low confidence; review before applying.`, }, nutrition: { value: { - calories: nutResult.calories, - protein: nutResult.protein, - carbohydrates: nutResult.carbohydrates, - fat: nutResult.fat, - fiber: nutResult.fiber, - sodium: nutResult.sodium, - servings: nutritionServings, - confidenceNote: nutResult.confidenceNote, + calories: nutResult!.calories, + protein: nutResult!.protein, + carbohydrates: nutResult!.carbohydrates, + fat: nutResult!.fat, + fiber: nutResult!.fiber, + sodium: nutResult!.sodium, + servings: nutritionServings!, + confidenceNote: `TOTAL batch nutrition for ${nutritionServings} servings. ${nutResult!.confidenceNote}`, }, - confidence: "medium" as const, + confidence: "low" as const, source: "culinary_inference" as const, - explanation: "Estimated macronutrient breakdown from the curated local food reference", + explanation: "Total-batch macronutrient breakdown from the complete curated local food reference pass.", + }, + } + : {}), + ...(category !== undefined && !existingCategory + ? { + category: { + value: category, + confidence: "low" as const, + source: "culinary_inference" as const, + explanation: `Suggested category from the recipe title and ingredient names; review before applying.`, + }, + } + : {}), + ...(cuisine !== undefined && !existingCuisine + ? { + cuisine: { + value: cuisine, + confidence: "low" as const, + source: "culinary_inference" as const, + explanation: `Suggested cuisine from the recipe title and ingredient names; review before applying.`, + }, + } + : {}), + ...(!(typeof existing.difficulty === "string" && existing.difficulty.trim()) + ? { + difficulty: { + value: rawSteps.length > 6 || classificationText.includes("sourdough") ? "Hard" : rawSteps.length > 3 ? "Medium" : "Easy", + confidence: "low" as const, + source: "culinary_inference" as const, + explanation: `Difficulty inferred from technique complexity and ${rawSteps.length} instruction steps; review before applying.`, }, } : {}), - category: { - value: category, - confidence: "medium", - source: "culinary_inference", - explanation: `Classified as ${category} from recipe title and ingredients`, - }, - cuisine: { - value: cuisine, - confidence: "medium", - source: "culinary_inference", - explanation: `Detected ${cuisine} cuisine profile from flavor and ingredient markers`, - }, - difficulty: { - value: rawSteps.length > 6 || allText.includes("sourdough") ? "Hard" : rawSteps.length > 3 ? "Medium" : "Easy", - confidence: "medium", - source: "culinary_inference", - explanation: `Difficulty inferred from technique complexity and ${rawSteps.length} instruction steps`, - }, suggestedTags: { value: Array.from(new Set(tags)), - confidence: "high", + confidence: "low", source: "culinary_inference", - explanation: "Curated Obsidian hashtags for culinary search and Dataview tables", + explanation: "Structural and title/ingredient marker tags suggested for review; not an authoritative category.", }, }; - // Zero-fabrication: only attach cooked/serving fields that actually have - // evidence. Fields left `undefined` are not offered to the user for approval. - if (cookTime) { - result.cookTime = cookTime; - } - if (estimatedServings !== undefined) { + // Zero-fabrication: only attach timing/serving fields that have evidence and + // are not already authored. Fields left undefined are not offered. + if (prepTime) result.prepTime = prepTime; + if (cookTime) result.cookTime = cookTime; + if (totalTime) result.totalTime = totalTime; + if (estimatedServings !== undefined && existingServings === undefined) { result.servings = { value: estimatedServings, confidence: servingsConf, diff --git a/src/App.tsx b/src/App.tsx index 83475a4..8daf057 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -43,6 +43,7 @@ import { type VaultSessionKind, type VaultTransition, } from './core/vaultSession'; +import { canPublishSavedImage } from './application/imageSaveRefresh'; import type { VaultAdapter } from './application/adapters/VaultAdapter'; import { createVaultAssetScope, type SessionAssetRunner, type VaultAssetScope, type VaultCollectionImportStart } from './utils/vaultAssets'; import { validateRecipeAssetReferences } from './utils/assetReferences'; @@ -552,6 +553,11 @@ export default function App({ const vaultHydratedRef = useRef(true); const lastImageSaveSessionRef = useRef(null); const lastImageSaveRevisionRef = useRef(null); + // Revisions captured around the image save's OWN collection invalidation. + // The handler must compare the pre-save and post-save values without treating + // this save's expected +1 as a concurrent-write conflict. + const lastImageSaveCommittedRevisionRef = useRef(null); + const lastImageSavePostMarkRevisionRef = useRef(null); const appUnmountedRef = useRef(false); const shutdownTransitionRef = useRef(null); const assetScopeDisposalTimerRef = useRef | null>(null); @@ -862,13 +868,20 @@ export default function App({ if (!lease) throw new Error('The active Vault changed before the image could be saved.'); lastImageSaveSessionRef.current = active.session; lastImageSaveRevisionRef.current = vaultAuthority.collectionRevision(active.session); + lastImageSaveCommittedRevisionRef.current = null; + lastImageSavePostMarkRevisionRef.current = null; try { const result = await saveGeneratedRecipeImageToVault( { vault: active.adapter, asset, assetScope: active.assetScope, previewSource }, { recipePath, recipeTitle, token, activeVaultSessionId, approved: true } ); + // Capture the revision AFTER the committed save but BEFORE this save's + // own scan invalidation. The success handler uses this to distinguish + // its own +1 from a genuine concurrent write. + lastImageSaveCommittedRevisionRef.current = vaultAuthority.collectionRevision(active.session); // Invalidate stale scans before releasing the write lease. if (vaultAuthority.isCurrent(active.session)) vaultAuthority.markCollectionChanged(active.session); + lastImageSavePostMarkRevisionRef.current = vaultAuthority.collectionRevision(active.session); return result; } finally { lease.release(); @@ -1659,14 +1672,17 @@ export default function App({ if (!saveSession || !vaultAuthority.isCurrent(saveSession) || vaultAuthority.writesBlocked()) return; if (isBuiltInRecipe(recipesRef.current.find((r) => r.id === recipeId))) return; const startRevision = lastImageSaveRevisionRef.current; + const committedRevision = lastImageSaveCommittedRevisionRef.current; + const postMarkRevision = lastImageSavePostMarkRevisionRef.current; const currentRevision = vaultAuthority.collectionRevision(saveSession); - // Recovery has committed both the asset and canonical Markdown. Advance the - // collection revision so a scan that captured the pre-recovery snapshot - // cannot commit over this result. - vaultAuthority.markCollectionChanged(saveSession); - if (startRevision !== null && currentRevision !== null && currentRevision !== startRevision) { - // A newer collection mutation intervened. Do not publish a stale recipe - // projection; the next authoritative scan will read the committed files. + // The save itself advances the revision by one. Compare the pre-save + // revision with the revision captured immediately after the committed save + // (before our own invalidation), then verify no later mutation occurred. + // The save's invalidation already happened inside the write lease, so it + // must not be mistaken for a conflict here. + if (!canPublishSavedImage({ startRevision, committedRevision, postMarkRevision, currentRevision })) { + // A genuine newer collection mutation intervened. Do not publish a stale + // recipe projection; the next authoritative scan reads the committed files. setVaultNotice({ tone: 'info', message: 'The image was saved, but the Vault state changed during the operation. Refresh to view the latest state.', diff --git a/src/application/imageSaveRefresh.ts b/src/application/imageSaveRefresh.ts new file mode 100644 index 0000000..ea6c670 --- /dev/null +++ b/src/application/imageSaveRefresh.ts @@ -0,0 +1,40 @@ +/** + * Revision reconciliation for the image-save success handler. + * + * The save flow holds a Vault write lease, commits the asset + canonical + * Markdown, captures the revision BEFORE its own scan invalidation, then + * advances the revision and releases the lease. The success handler must: + * + * - ignore that expected self-invalidation, and + * - still reject a genuine concurrent write during or after the save. + * + * Keeping the comparison pure makes the sequence testable and prevents the + * save's own +1 from being mistaken for a conflict. + */ +export interface ImageSaveRevisionSnapshot { + /** Revision captured when the save began. */ + readonly startRevision: number | null; + /** Revision after the committed save, before this save's invalidation. */ + readonly committedRevision: number | null; + /** Revision after this save's own invalidation. */ + readonly postMarkRevision: number | null; + /** Revision observed by the success handler. */ + readonly currentRevision: number | null; +} + +export function canPublishSavedImage(snapshot: ImageSaveRevisionSnapshot): boolean { + const { startRevision, committedRevision, postMarkRevision, currentRevision } = snapshot; + if ( + startRevision === null || + committedRevision === null || + postMarkRevision === null || + currentRevision === null + ) { + return false; + } + // A write during the save changed the revision before our invalidation. + if (committedRevision !== startRevision) return false; + // The expected self-invalidation produced postMarkRevision; anything later + // means a genuine concurrent write intervenes before the handler publishes. + return currentRevision === postMarkRevision; +} diff --git a/src/components/CreateForMeModal.tsx b/src/components/CreateForMeModal.tsx index da1ca0a..9a4caf5 100644 --- a/src/components/CreateForMeModal.tsx +++ b/src/components/CreateForMeModal.tsx @@ -487,10 +487,16 @@ export function CreateForMeModal({ isOpen, onClose, network, onSaveRecipe }: Cre // preparation/optional/timer fields and rejects empty required fields or // any malformed edited shape; no partial draft is saved. edited = normalizeGeneratedRecipeDraft(editedDraft ?? draft); - } catch { + } catch (error) { + const detail = error instanceof Error ? error.message : ''; + const explicit = detail.startsWith('Generated recipe draft is invalid:') + ? detail.slice('Generated recipe draft is invalid: '.length).trim() + : ''; dispatch({ type: 'SAVE_FAILURE', - message: 'Please complete the recipe title, every ingredient name, and every step before saving.', + message: explicit + ? `Fix the invalid recipe fields before saving: ${explicit.slice(0, 400)}` + : 'Please complete the recipe title, every ingredient name, and every step before saving.', }); session.current.setBusy(false); return; diff --git a/src/components/VaultIntelligenceModal.tsx b/src/components/VaultIntelligenceModal.tsx index 2778281..219cb31 100644 --- a/src/components/VaultIntelligenceModal.tsx +++ b/src/components/VaultIntelligenceModal.tsx @@ -43,6 +43,8 @@ import { summarizeVaultHealth, mergeRecoveredMetadata, normalizeTimeString, + defaultAcceptedRecoveredFields, + selectBatchAcceptedRecoveredFields, } from '../utils/vaultIntelligence'; import { assessRecipeImageHealth, @@ -591,15 +593,10 @@ const res = await network.post<{ recovered?: any; error?: string }>( const data = res.data; if (data?.recovered) { setRecoveredData(data.recovered); - // Default only missing fields to true, present fields to false to avoid overwriting unless user opts in - const newAccepted: Record = {}; + // Default only independently supported missing fields. Category, + // cuisine, tags, calories, and nutrition remain explicit opt-ins. const missing = assessRecipeHealth(recipe).missingFields; - - (Object.keys(data.recovered) as (keyof RecoveredRecipeMetadata)[]).forEach((field) => { - // If field is in missingFields or was empty, accept it by default - newAccepted[field] = missing.includes(field) || field === 'suggestedTags' || field === 'nutrition'; - }); - setAcceptedFields(newAccepted); + setAcceptedFields(defaultAcceptedRecoveredFields(data.recovered, missing)); } else { throw new Error('No metadata recovery payload returned from server.'); } @@ -685,9 +682,10 @@ const res = await network.post<{ recovered?: any; error?: string }>( const data = res.data; if (data?.recovered) { const missing = assessRecipeHealth(rec).missingFields; - const fieldsToAccept = (Object.keys(data.recovered) as (keyof RecoveredRecipeMetadata)[]).filter( - (f) => missing.includes(f) || f === 'suggestedTags' - ); + // Bulk recovery applies ONLY independently supported, high-confidence + // explicit/body-parsed values. Guesses stay in the per-recipe review. + const fieldsToAccept = selectBatchAcceptedRecoveredFields(data.recovered, missing); + if (fieldsToAccept.length === 0) continue; const merged = mergeRecoveredMetadata(rec, data.recovered, fieldsToAccept); updatedRecipes.push(merged); await onSaveRecipe(merged); @@ -1217,7 +1215,7 @@ const res = await network.post<{ recovered?: any; error?: string }>( ~{recoveredData.calories.value} kcal / serving {recoveredData.nutrition?.value && ( - (P: {recoveredData.nutrition.value.protein}g | C: {recoveredData.nutrition.value.carbohydrates}g | F: {recoveredData.nutrition.value.fat}g) + (batch total: P {recoveredData.nutrition.value.protein}g | C {recoveredData.nutrition.value.carbohydrates}g | F {recoveredData.nutrition.value.fat}g) )} diff --git a/src/schema/generatedRecipe.ts b/src/schema/generatedRecipe.ts index 78dcfc2..5c218e5 100644 --- a/src/schema/generatedRecipe.ts +++ b/src/schema/generatedRecipe.ts @@ -34,6 +34,14 @@ export const MAX_GENERATED_TAGS = 30; export const MAX_CREATE_PROMPT_LENGTH = 1200; /** Max constraint-list item count (e.g. dietary / exclude ingredients). */ export const MAX_CONSTRAINT_ITEMS = 20; +/** + * Bounded ingredient text. These are intentionally generous enough for real + * culinary descriptions (cut, brand, variety, preparation) while still + * preventing unbounded provider output. Over-limit fields are REJECTED, never + * silently truncated. + */ +export const MAX_GENERATED_INGREDIENT_NAME_LENGTH = 240; +export const MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH = 240; /** A single generated ingredient. Deliberately wikilink-free (no auto-linking). */ export interface GeneratedIngredient { @@ -118,6 +126,17 @@ function trimString(v: unknown, max: number): string | undefined { return t.length > max ? t.slice(0, max) : t || undefined; } +/** Trim only; callers must validate the bound before normalization. */ +function trimExact(v: unknown): string | undefined { + if (typeof v !== 'string') return undefined; + const t = v.trim(); + return t || undefined; +} + +function exceeds(value: string, max: number): boolean { + return value.length > max; +} + function isFiniteNumber(v: unknown): v is number { return typeof v === 'number' && Number.isFinite(v); } @@ -133,13 +152,15 @@ function normalizeIngredient(raw: unknown): GeneratedIngredient | null { return name ? { name } : null; } if (!isPlainObject(raw)) return null; - const name = trimString(raw['name'], 80); + // The authoritative validator rejects over-limit values before this runs. + // Never slice here: a shortened ingredient is fabricated content. + const name = trimExact(raw['name']); if (!name) return null; return { name, ...(isFiniteNumber(raw['amount']) ? { amount: raw['amount'] as number } : {}), ...(raw['unit'] !== undefined ? { unit: trimString(raw['unit'], 20) } : {}), - ...(raw['preparation'] !== undefined ? { preparation: trimString(raw['preparation'], 80) } : {}), + ...(raw['preparation'] !== undefined ? { preparation: trimExact(raw['preparation']) } : {}), ...(raw['optional'] === true ? { optional: true } : {}), }; } @@ -265,10 +286,21 @@ export function validateGeneratedRecipeDraft(raw: unknown): GeneratedRecipeValid } if (!isString(ing['name']) || !(ing['name'] as string).trim()) { errors.push(`ingredients[${i}].name is required`); + } else if (exceeds((ing['name'] as string).trim(), MAX_GENERATED_INGREDIENT_NAME_LENGTH)) { + errors.push(`ingredients[${i}].name exceeds ${MAX_GENERATED_INGREDIENT_NAME_LENGTH} characters`); + } + if (ing['preparation'] !== undefined) { + if (!isString(ing['preparation'])) { + errors.push(`ingredients[${i}].preparation must be a string`); + } else if (exceeds((ing['preparation'] as string).trim(), MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH)) { + errors.push(`ingredients[${i}].preparation exceeds ${MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH} characters`); + } } if (ing['optional'] !== undefined && typeof ing['optional'] !== 'boolean') { errors.push(`ingredients[${i}].optional must be a boolean`); } + } else if (typeof ing === 'string' && exceeds(ing.trim(), MAX_GENERATED_INGREDIENT_NAME_LENGTH)) { + errors.push(`ingredients[${i}] exceeds ${MAX_GENERATED_INGREDIENT_NAME_LENGTH} characters`); } }); } @@ -318,8 +350,8 @@ export function buildGeneratedRecipeSchema(): AiJsonSchema { properties: { amount: { type: 'number' }, unit: { type: 'string', description: 'Standardized unit, e.g. tbsp, cup, g, ml' }, - name: { type: 'string', description: 'Ingredient name' }, - preparation: { type: 'string', description: 'Preparation modifier, e.g. diced' }, + name: { type: 'string', description: `Ingredient name (max ${MAX_GENERATED_INGREDIENT_NAME_LENGTH} characters)` }, + preparation: { type: 'string', description: `Preparation modifier, e.g. diced (max ${MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH} characters)` }, optional: { type: 'boolean' }, }, required: ['name'], diff --git a/src/utils/vaultIntelligence.ts b/src/utils/vaultIntelligence.ts index bfdc5c0..bb22ff5 100644 --- a/src/utils/vaultIntelligence.ts +++ b/src/utils/vaultIntelligence.ts @@ -148,12 +148,12 @@ export function assessRecipeHealth(recipe: ObsidianRecipe): MetadataHealthReport if (hasCuisine) presentFields.push('cuisine'); else missingFields.push('cuisine'); - // 5. Difficulty & Rating & Tags Check (Weight: 10) + // 5. Difficulty & Tags Check. A personal rating is OPTIONAL and must never be + // reported as missing metadata or lower the recipe's quality score. if (recipe.difficulty) presentFields.push('difficulty'); else missingFields.push('difficulty'); if (recipe.rating) presentFields.push('rating'); - else missingFields.push('rating'); const hasSpecificTags = recipe.tags && recipe.tags.length > 0 && !(recipe.tags.length === 1 && recipe.tags[0] === 'food/recipes'); if (hasSpecificTags) presentFields.push('tags'); @@ -184,9 +184,9 @@ export function assessRecipeHealth(recipe: ObsidianRecipe): MetadataHealthReport if (hasCategory && hasCuisine) score += 15; else if (hasCategory || hasCuisine) score += 8; - // Difficulty & Rating & Tags: up to 10 pts - if (recipe.difficulty) score += 3; - if (recipe.rating) score += 3; + // Difficulty & Tags: up to 10 pts. Rating is optional personal data and + // does not affect metadata quality or the score. + if (recipe.difficulty) score += 6; if (hasSpecificTags) score += 4; // Core structure: up to 10 pts @@ -344,7 +344,10 @@ export function mergeRecoveredMetadata( const nutr = item.value as RecipeNutrition; updated.nutrition = nutr; frontmatter.nutrition = nutr; - if (nutr.calories && !frontmatter.calories) { + // When `servings` is present the nutrition block is TOTAL batch + // nutrition. Never copy that total into the per-serving `calories` + // field; the separate calories suggestion carries per-serving values. + if (nutr.calories && !frontmatter.calories && !(typeof nutr.servings === 'number' && nutr.servings > 0)) { frontmatter.calories = nutr.calories; updated.calories = nutr.calories; } @@ -398,3 +401,60 @@ export function mergeRecoveredMetadata( return updated; } + +/** + * Fields that are suggestions rather than independently supported facts. They + * may be displayed for manual review, but must never be selected by default or + * applied automatically by bulk recovery. + */ +const MANUAL_ONLY_RECOVERED_FIELDS = new Set([ + 'category', + 'cuisine', + 'difficulty', + 'suggestedTags', + 'calories', + 'nutrition', +]); + +/** + * Default checkbox state for the single-recipe recovery review. Only a missing, + * HIGH-confidence, non-speculative field is selected. Category/cuisine/tags/ + * difficulty/nutrition guesses and every medium/low-confidence inference remain + * explicit opt-ins. + */ +export function defaultAcceptedRecoveredFields( + recovered: RecoveredRecipeMetadata, + missingFields: readonly string[], +): Record { + const accepted: Record = {}; + for (const field of Object.keys(recovered) as (keyof RecoveredRecipeMetadata)[]) { + const item = recovered[field]; + accepted[field] = + missingFields.includes(field) && + !MANUAL_ONLY_RECOVERED_FIELDS.has(field) && + item?.confidence === 'high'; + } + return accepted; +} + +/** + * Bulk recovery may apply ONLY independently supported, high-confidence fields + * that were missing. Inferred category/cuisine/tags/nutrition, difficulty, and + * every culinary-inference value are excluded; they remain available only via + * the explicit per-recipe review. + */ +export function selectBatchAcceptedRecoveredFields( + recovered: RecoveredRecipeMetadata, + missingFields: readonly string[], +): (keyof RecoveredRecipeMetadata)[] { + const accepted: (keyof RecoveredRecipeMetadata)[] = []; + for (const field of Object.keys(recovered) as (keyof RecoveredRecipeMetadata)[]) { + if (!missingFields.includes(field)) continue; + if (MANUAL_ONLY_RECOVERED_FIELDS.has(field)) continue; + const item = recovered[field]; + if (!item || item.confidence !== 'high') continue; + if (item.source !== 'instructions_explicit' && item.source !== 'body_parsed') continue; + accepted.push(field); + } + return accepted; +} diff --git a/tests/fixtures/smokedChicken.ts b/tests/fixtures/smokedChicken.ts new file mode 100644 index 0000000..f11c200 --- /dev/null +++ b/tests/fixtures/smokedChicken.ts @@ -0,0 +1,76 @@ +/** + * Disposable smoked-chicken fixture reconstructed from the owner's confirmed + * Vault Intelligence symptoms. It is intentionally not read from any personal + * Vault and contains no credentials or provider data. + * + * It reproduces: + * - a long ingredient name/preparation that previously hit the 80-char cut; + * - a baking-sheet instruction that must not classify the dish as Baking; + * - four hours of refrigeration plus five minutes of resting; + * - 45–60 minutes of active smoking plus 1–3 minutes of broiling; + * - a barbecue title/ingredient marker; + * - a low-coverage nutrition shape that must not be offered as credible. + */ +export const SMOKED_CHICKEN_INGREDIENT_NAME = + 'whole chicken (about 5 pounds), preferably air-chilled, humanely raised, and patted completely dry'; + +export const SMOKED_CHICKEN_INGREDIENT_PREPARATION = + 'trimmed of excess fat, patted completely dry, and seasoned evenly under the skin and inside the cavity'; + +export const SMOKED_CHICKEN_MARKDOWN = `--- +title: "Smoked Chicken Dinner" +category: +cuisine: +servings: +--- +# Smoked Chicken Dinner + +## Ingredients + +- 1 whole chicken (about 5 pounds), preferably air-chilled, humanely raised, and patted completely dry +- 1 cup barbecue sauce +- 1 tbsp olive oil + +## Instructions + +1. Pat the chicken dry and coat it with barbecue sauce and olive oil. +2. Place the chicken on a baking sheet. +3. Refrigerate uncovered for 4 hours to dry-brine. +4. Smoke at 225°F for approximately 45–60 minutes, until the internal temperature reaches 165°F. +5. Broil for 1–3 minutes to crisp the skin. +6. Rest for 5 minutes before carving. +`; + +export const SMOKED_CHICKEN_REQUEST = { + title: 'Smoked Chicken Dinner', + rawMarkdown: SMOKED_CHICKEN_MARKDOWN, + ingredients: [ + { + original: `1 ${SMOKED_CHICKEN_INGREDIENT_NAME}`, + amount: 1, + unit: '', + name: SMOKED_CHICKEN_INGREDIENT_NAME, + }, + { original: '1 cup barbecue sauce', amount: 1, unit: 'cup', name: 'barbecue sauce' }, + { original: '1 tbsp olive oil', amount: 1, unit: 'tbsp', name: 'olive oil' }, + ], + instructions: [ + { text: 'Pat the chicken dry and coat it with barbecue sauce and olive oil.' }, + { text: 'Place the chicken on a baking sheet.' }, + { text: 'Refrigerate uncovered for 4 hours to dry-brine.' }, + { text: 'Smoke at 225°F for approximately 45–60 minutes, until the internal temperature reaches 165°F.' }, + { text: 'Broil for 1–3 minutes to crisp the skin.' }, + { text: 'Rest for 5 minutes before carving.' }, + ], +}; + +/** + * Low-coverage "Chicken Dinner" shape. The baseline estimator resolved only + * 1/2 tsp black pepper (3 kcal total) and the UI displayed that total as + * "3 kcal / serving". It must never be offered as recovered nutrition. + */ +export const CHICKEN_DINNER_LOW_COVERAGE_REQUEST = { + title: 'Chicken Dinner', + ingredients: ['1 whole chicken', '1/2 tsp black pepper', '1 tsp salt'], + instructions: ['Cook the chicken.'], +}; diff --git a/tests/unit/aiConsumerMigration.test.ts b/tests/unit/aiConsumerMigration.test.ts index d80f0a4..92c4096 100644 --- a/tests/unit/aiConsumerMigration.test.ts +++ b/tests/unit/aiConsumerMigration.test.ts @@ -67,10 +67,12 @@ describe("metadataRecovery — provider-neutral migration (v0.7 1C #31)", () => fetchMock = vi.fn(async () => new Response(JSON.stringify({ choices: [{ message: { content: "{ not json" } }] }))); vi.stubGlobal("fetch", fetchMock); const result = await recoverRecipeMetadata({ title: "T", ingredients: ["1 cup flour"], instructions: ["Mix."] }); - // Invalid structured output -> algorithmic fallback; no fabrication of cookTime/servings. + // Invalid structured output -> algorithmic fallback; no fabrication of + // cookTime, servings, or category from one flour ingredient. expect(result.cookTime).toBeUndefined(); expect(result.servings).toBeUndefined(); - expect(result.category?.value).toBeDefined(); + expect(result.category).toBeUndefined(); + expect(result.suggestedTags?.confidence).toBe("low"); }); it("missing metadata stays missing (zero-fabrication) across the provider path", async () => { diff --git a/tests/unit/createForMeDraftView.test.tsx b/tests/unit/createForMeDraftView.test.tsx index f8a245c..f6bfb33 100644 --- a/tests/unit/createForMeDraftView.test.tsx +++ b/tests/unit/createForMeDraftView.test.tsx @@ -14,7 +14,13 @@ import { CreateForMeDraftView, formatElapsedSeconds, } from '../../src/components/CreateForMeModal'; -import type { GeneratedRecipeDraft, GeneratedRecipeProvenance } from '../../src/schema/generatedRecipe'; +import { normalizeGeneratedRecipeDraft, type GeneratedRecipeDraft, type GeneratedRecipeProvenance } from '../../src/schema/generatedRecipe'; +import { generatedDraftToObsidianRecipe } from '../../src/application/createForMe'; +import { parseObsidianRecipeMarkdown, serializeRecipeToObsidianMarkdown } from '../../src/utils/markdownParser'; +import { + SMOKED_CHICKEN_INGREDIENT_NAME, + SMOKED_CHICKEN_INGREDIENT_PREPARATION, +} from '../fixtures/smokedChicken'; const PROVENANCE: GeneratedRecipeProvenance = { generated: true, @@ -145,6 +151,47 @@ describe('CreateForMeDraftView', () => { expect(draft.steps[1].text).toBe('Bake until golden.'); }); + it('renders the complete long smoked-chicken name and preparation in the editor', () => { + const longDraft: GeneratedRecipeDraft = { + title: 'Smoked Chicken Dinner', + ingredients: [{ + amount: 1, + name: SMOKED_CHICKEN_INGREDIENT_NAME, + preparation: SMOKED_CHICKEN_INGREDIENT_PREPARATION, + }], + steps: [{ text: 'Smoke until done.' }], + }; + render( {}} />); + expect((screen.getByLabelText('Ingredient 1 name') as HTMLInputElement).value).toBe( + SMOKED_CHICKEN_INGREDIENT_NAME + ); + expect((screen.getByLabelText('Ingredient 1 preparation') as HTMLInputElement).value).toBe( + SMOKED_CHICKEN_INGREDIENT_PREPARATION + ); + }); + + it('keeps the smoked-chicken ingredient through normalized draft, editor, Markdown save, and reload', () => { + const draft = normalizeGeneratedRecipeDraft({ + title: 'Smoked Chicken Dinner', + ingredients: [{ + amount: 1, + name: SMOKED_CHICKEN_INGREDIENT_NAME, + preparation: SMOKED_CHICKEN_INGREDIENT_PREPARATION, + }], + steps: [{ text: 'Smoke until done.' }], + }); + const { unmount } = render( {}} />); + expect((screen.getByLabelText('Ingredient 1 name') as HTMLInputElement).value).toBe(SMOKED_CHICKEN_INGREDIENT_NAME); + expect((screen.getByLabelText('Ingredient 1 preparation') as HTMLInputElement).value).toBe(SMOKED_CHICKEN_INGREDIENT_PREPARATION); + unmount(); + + const recipe = generatedDraftToObsidianRecipe({ draft, provenance: PROVENANCE }); + const markdown = serializeRecipeToObsidianMarkdown(recipe); + const reloaded = parseObsidianRecipeMarkdown(markdown, recipe.fileName ?? 'recipe.md', recipe.filePath ?? 'recipe.md'); + expect(reloaded.ingredients[0].original).toContain(SMOKED_CHICKEN_INGREDIENT_NAME); + expect(reloaded.ingredients[0].original).toContain(SMOKED_CHICKEN_INGREDIENT_PREPARATION); + }); + it('formats elapsed feedback in clearly labelled seconds', () => { expect(formatElapsedSeconds(0)).toBe('0.0s'); expect(formatElapsedSeconds(1234)).toBe('1.2s'); diff --git a/tests/unit/createForMeSave.test.ts b/tests/unit/createForMeSave.test.ts index 32ce919..496fe70 100644 --- a/tests/unit/createForMeSave.test.ts +++ b/tests/unit/createForMeSave.test.ts @@ -2,6 +2,10 @@ import { describe, it, expect } from "vitest"; import { generatedDraftToObsidianRecipe } from "../../src/application/createForMe.js"; import { serializeRecipeToObsidianMarkdown, parseObsidianRecipeMarkdown } from "../../src/utils/markdownParser.js"; import type { GeneratedRecipeDraft, GeneratedRecipeProvenance } from "../../src/schema/generatedRecipe.js"; +import { + SMOKED_CHICKEN_INGREDIENT_NAME, + SMOKED_CHICKEN_INGREDIENT_PREPARATION, +} from "../fixtures/smokedChicken.js"; const PROVENANCE: GeneratedRecipeProvenance = { generated: true, providerId: "gemini", model: "gemini-test" }; @@ -78,6 +82,26 @@ describe("generatedDraftToObsidianRecipe (v0.7 2A) — save adaptation", () => { expect(md).not.toContain("source: http"); }); + it("round-trips the complete smoked-chicken name and preparation through Markdown save and reload", () => { + const input = draft({ + title: "Smoked Chicken Dinner", + ingredients: [{ + amount: 1, + name: SMOKED_CHICKEN_INGREDIENT_NAME, + preparation: SMOKED_CHICKEN_INGREDIENT_PREPARATION, + }], + }); + const recipe = generatedDraftToObsidianRecipe({ draft: input, provenance: PROVENANCE }); + expect(recipe.ingredients[0].name).toBe(SMOKED_CHICKEN_INGREDIENT_NAME); + expect(recipe.ingredients[0].note).toBe(SMOKED_CHICKEN_INGREDIENT_PREPARATION); + const md = serializeRecipeToObsidianMarkdown(recipe); + expect(md).toContain(SMOKED_CHICKEN_INGREDIENT_NAME); + expect(md).toContain(SMOKED_CHICKEN_INGREDIENT_PREPARATION); + const reloaded = parseObsidianRecipeMarkdown(md, "Smoked Chicken Dinner.md", "Smoked Chicken Dinner.md"); + expect(reloaded.ingredients[0].original).toContain(SMOKED_CHICKEN_INGREDIENT_NAME); + expect(reloaded.ingredients[0].original).toContain(SMOKED_CHICKEN_INGREDIENT_PREPARATION); + }); + it("never generates ingredient wikilinks", () => { const recipe = generatedDraftToObsidianRecipe({ draft: draft(), provenance: PROVENANCE }); for (const ing of recipe.ingredients) { diff --git a/tests/unit/createForMeSaveUi.test.tsx b/tests/unit/createForMeSaveUi.test.tsx index 88d4705..7ca0b18 100644 --- a/tests/unit/createForMeSaveUi.test.tsx +++ b/tests/unit/createForMeSaveUi.test.tsx @@ -225,3 +225,33 @@ describe('Create for Me save integration', () => { expect(recipe.rawMarkdown).toContain('1.25'); }); }); + +describe('Create for Me oversized-field rejection', () => { + it('shows an explicit field error and never saves an over-limit ingredient name', async () => { + const onSave = vi.fn(async (_recipe: ObsidianRecipe) => {}); + render( + {}} + onSaveRecipe={onSave} + /> + ); + fireEvent.change(document.getElementById('create-me-prompt') as HTMLTextAreaElement, { + target: { value: 'Create a Southern cornbread dressing.' }, + }); + fireEvent.click(screen.getByRole('button', { name: /^Generate$/i })); + await screen.findByText('Traditional Southern Cornbread Dressing'); + fireEvent.click(screen.getByRole('button', { name: /^Edit Recipe$/i })); + await screen.findByLabelText('Recipe title'); + + fireEvent.change(screen.getByLabelText('Ingredient 1 name'), { + target: { value: 'x'.repeat(241) }, + }); + fireEvent.click(screen.getByRole('button', { name: /Save to Vault/i })); + + await screen.findByText(/exceeds 240 characters/i); + expect(onSave).not.toHaveBeenCalled(); + expect(screen.getByLabelText('Recipe title')).toBeTruthy(); + }); +}); diff --git a/tests/unit/generatedRecipeSchema.test.ts b/tests/unit/generatedRecipeSchema.test.ts index 3d6afa2..76cb02e 100644 --- a/tests/unit/generatedRecipeSchema.test.ts +++ b/tests/unit/generatedRecipeSchema.test.ts @@ -5,8 +5,14 @@ import { validateGeneratedRecipeDraft, MAX_GENERATED_INGREDIENTS, MAX_GENERATED_STEPS, + MAX_GENERATED_INGREDIENT_NAME_LENGTH, + MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH, type GeneratedRecipeDraft, } from "../../src/schema/generatedRecipe.js"; +import { + SMOKED_CHICKEN_INGREDIENT_NAME, + SMOKED_CHICKEN_INGREDIENT_PREPARATION, +} from "../fixtures/smokedChicken.js"; import type { AiJsonSchema } from "../../src/core/ai/types.js"; function validDraft(overrides: Record = {}) { @@ -101,6 +107,58 @@ describe("GeneratedRecipeDraft — schema + validation (v0.7 Phase 2A)", () => { }); }); + it("preserves the full smoked-chicken ingredient name and preparation (no 80-char truncation)", () => { + const draft = validDraft({ + ingredients: [{ + amount: 1, + name: SMOKED_CHICKEN_INGREDIENT_NAME, + preparation: SMOKED_CHICKEN_INGREDIENT_PREPARATION, + }], + }); + expect(SMOKED_CHICKEN_INGREDIENT_NAME.length).toBeGreaterThan(80); + expect(SMOKED_CHICKEN_INGREDIENT_PREPARATION.length).toBeGreaterThan(80); + expect(validateGeneratedRecipeDraft(draft).passed).toBe(true); + const normalized = normalizeGeneratedRecipeDraft(draft); + expect(normalized.ingredients[0].name).toBe(SMOKED_CHICKEN_INGREDIENT_NAME); + expect(normalized.ingredients[0].preparation).toBe(SMOKED_CHICKEN_INGREDIENT_PREPARATION); + // The original defect cut at exactly 80 characters. Prove this regression + // crosses that boundary: the old truncated prefix must not be the result. + const legacy80 = SMOKED_CHICKEN_INGREDIENT_NAME.slice(0, 80); + expect(legacy80).toHaveLength(80); + expect(normalized.ingredients[0].name).not.toBe(legacy80); + expect(normalized.ingredients[0].name.slice(0, 80)).toBe(legacy80); + expect(normalized.ingredients[0].name.length).toBeGreaterThan(80); + }); + + it("explicitly rejects oversized ingredient name/preparation instead of silently cutting them", () => { + const longName = "x".repeat(MAX_GENERATED_INGREDIENT_NAME_LENGTH + 1); + const longPreparation = "y".repeat(MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH + 1); + const byName = validateGeneratedRecipeDraft(validDraft({ + ingredients: [{ name: longName }], + })); + expect(byName.passed).toBe(false); + expect(byName.errors.some((error) => error.includes("ingredients[0].name") && error.includes("exceeds"))).toBe(true); + + const byPreparation = validateGeneratedRecipeDraft(validDraft({ + ingredients: [{ name: "chicken", preparation: longPreparation }], + })); + expect(byPreparation.passed).toBe(false); + expect(byPreparation.errors.some((error) => error.includes("ingredients[0].preparation") && error.includes("exceeds"))).toBe(true); + + expect(() => normalizeGeneratedRecipeDraft(validDraft({ + ingredients: [{ name: longName }], + }))).toThrow(/ingredients\[0\]\.name exceeds/); + }); + + it("rejects a non-string preparation and a malformed string ingredient shape", () => { + expect(validateGeneratedRecipeDraft(validDraft({ + ingredients: [{ name: "chicken", preparation: 42 }], + })).passed).toBe(false); + expect(validateGeneratedRecipeDraft(validDraft({ + ingredients: ["z".repeat(MAX_GENERATED_INGREDIENT_NAME_LENGTH + 1)], + })).passed).toBe(false); + }); + it("rejects missing title", () => { expect(validateGeneratedRecipeDraft(validDraft({ title: "" })).passed).toBe(false); }); diff --git a/tests/unit/imageSaveRefresh.test.ts b/tests/unit/imageSaveRefresh.test.ts new file mode 100644 index 0000000..190be64 --- /dev/null +++ b/tests/unit/imageSaveRefresh.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest'; +import { canPublishSavedImage } from '../../src/application/imageSaveRefresh'; + +describe('image save immediate-refresh revision reconciliation', () => { + it('publishes after the save’s OWN expected invalidation', () => { + expect(canPublishSavedImage({ + startRevision: 5, + committedRevision: 5, + postMarkRevision: 6, + currentRevision: 6, + })).toBe(true); + }); + + it('refuses to publish when a concurrent write intervened during the save', () => { + expect(canPublishSavedImage({ + startRevision: 5, + committedRevision: 6, + postMarkRevision: 7, + currentRevision: 7, + })).toBe(false); + }); + + it('refuses to publish when a concurrent write intervened after the save invalidation', () => { + expect(canPublishSavedImage({ + startRevision: 5, + committedRevision: 5, + postMarkRevision: 6, + currentRevision: 7, + })).toBe(false); + }); + + it('fails closed when the Vault session or any revision is unavailable', () => { + expect(canPublishSavedImage({ + startRevision: null, + committedRevision: null, + postMarkRevision: null, + currentRevision: null, + })).toBe(false); + }); +}); + +describe('image save immediate-refresh revision sequence', () => { + it('publishes after the real authority advances for this save, and still blocks a later write', async () => { + const { createVaultSessionAuthority } = await import('../../src/core/vaultSession'); + const authority = createVaultSessionAuthority(); + const session = (await authority.commitTransition(authority.beginTransition('filesystem'), () => {})).session!; + const startRevision = authority.collectionRevision(session)!; + // The save has committed both files; no concurrent writer. + const committedRevision = authority.collectionRevision(session)!; + // The save flow's own invalidation: + authority.markCollectionChanged(session); + const postMarkRevision = authority.collectionRevision(session)!; + expect(canPublishSavedImage({ + startRevision, + committedRevision, + postMarkRevision, + currentRevision: authority.collectionRevision(session), + })).toBe(true); + // A later genuine mutation must still block publication. + authority.markCollectionChanged(session); + expect(canPublishSavedImage({ + startRevision, + committedRevision, + postMarkRevision, + currentRevision: authority.collectionRevision(session), + })).toBe(false); + }); +}); diff --git a/tests/unit/metadataRecovery.test.ts b/tests/unit/metadataRecovery.test.ts index 0c1f9c0..0a9f9ac 100644 --- a/tests/unit/metadataRecovery.test.ts +++ b/tests/unit/metadataRecovery.test.ts @@ -4,6 +4,7 @@ import { mergeRecoveredMetadata } from "../../src/utils/vaultIntelligence.js"; import { ObsidianRecipe, RecoveredRecipeMetadata } from "../../src/types"; import { getGemini } from "../../server/geminiClient.js"; import { MODEL_CONFIG } from "../../server/modelConfig.js"; +import { CHICKEN_DINNER_LOW_COVERAGE_REQUEST, SMOKED_CHICKEN_REQUEST } from "../fixtures/smokedChicken.js"; vi.mock("../../server/geminiClient.js", () => ({ getGemini: vi.fn(() => null), @@ -45,13 +46,15 @@ describe("metadata recovery — zero-fabrication & inference labelling", () => { it("marks an explicit instruction duration as high-confidence explicit evidence", () => { const result = recoverMetadataAlgorithmically({ title: "Roast Chicken", + rawMarkdown: "Prep time: 5 mins", ingredients: ["1 whole chicken"], instructions: ["Bake for 45 minutes at 400 degrees."], }); expect(result.cookTime?.value).toBe("45 mins"); expect(result.cookTime?.confidence).toBe("high"); expect(result.cookTime?.source).toBe("instructions_explicit"); - // totalTime = inferred prep (5 mins for one ingredient) + explicit cook (45). + // totalTime = explicit prep (5 mins) + explicit active cook (45). + expect(result.prepTime?.value).toBe("5 mins"); expect(result.totalTime?.value).toBe("50 mins"); expect(result.totalTime?.source).toBe("culinary_inference"); }); @@ -67,17 +70,17 @@ describe("metadata recovery — zero-fabrication & inference labelling", () => { expect(result.servings?.confidence).toBe("high"); }); - it("labels inference-only values as culinary inference with a hypothesis reason", () => { + it("does not fabricate cook time, prep time, or a batch yield for a dry rub", () => { const result = recoverMetadataAlgorithmically({ title: "Dry Rub", ingredients: ["2 tbsp paprika", "1 tbsp brown sugar"], instructions: ["Mix the seasonings."], }); - expect(result.cookTime?.value).toBe("0 mins"); - expect(result.cookTime?.source).toBe("culinary_inference"); - expect(result.cookTime?.confidence).toBe("medium"); - expect(result.cookTime?.explanation).toMatch(/requires no cooking time/); - expect(result.servings?.value).toBe(12); + expect(result.cookTime).toBeUndefined(); + expect(result.prepTime).toBeUndefined(); + expect(result.servings).toBeUndefined(); + expect(result.category?.value).toBe("Seasonings & Rubs"); + expect(result.suggestedTags?.confidence).toBe("low"); }); it("never overwrites an existing value for a field that was not accepted", () => { @@ -128,7 +131,113 @@ describe("metadata recovery — zero-fabrication & inference labelling", () => { instructions: ["Mix."], }); expect(result.cookTime).toBeUndefined(); - expect(result.category?.value).toBeDefined(); + expect(result.prepTime).toBeUndefined(); + expect(result.suggestedTags?.confidence).toBe("low"); + }); +}); + +describe("metadata recovery — owner smoked-chicken data integrity", () => { + it("does not classify a baking-sheet chicken as Baking & Breads or add baking/bread tags", () => { + const result = recoverMetadataAlgorithmically(SMOKED_CHICKEN_REQUEST); + expect(result.category?.value).not.toBe("Baking & Breads"); + expect(result.category?.value).not.toBe("Seasonings & Rubs"); + expect(result.cuisine?.value).toBe("American BBQ"); + expect(result.suggestedTags?.value).toContain("bbq"); + expect(result.suggestedTags?.value).not.toContain("baking"); + expect(result.suggestedTags?.value).not.toContain("bread"); + expect(result.suggestedTags?.confidence).toBe("low"); + }); + + it("omits the imprecise 45–60 / 1–3 minute cook time from the owner's actual sequence", () => { + const result = recoverMetadataAlgorithmically(SMOKED_CHICKEN_REQUEST); + // The owner's smoke and broil steps are RANGES. A precise cook time cannot + // be established, so a high-confidence estimate must be omitted. + expect(result.cookTime).toBeUndefined(); + expect(result.prepTime).toBeUndefined(); + expect(result.totalTime).toBeUndefined(); + }); + + it("never classifies passive refrigeration/resting as cook time", () => { + const result = recoverMetadataAlgorithmically({ + title: "Smoked Chicken Dinner", + ingredients: ["1 whole chicken"], + instructions: [ + "Refrigerate uncovered for 4 hours to dry-brine.", + "Rest for 20 minutes before carving.", + ], + }); + expect(result.cookTime).toBeUndefined(); + expect(result.totalTime).toBeUndefined(); + }); + + it("sums only precise ACTIVE cooking while excluding passive durations", () => { + const result = recoverMetadataAlgorithmically({ + title: "Smoked Chicken Dinner", + ingredients: ["1 whole chicken"], + instructions: [ + "Refrigerate uncovered for 4 hours to dry-brine.", + "Smoke at 225°F for 45 minutes.", + "Broil for 2 minutes.", + "Rest for 5 minutes before carving.", + ], + }); + expect(result.cookTime?.value).toBe("47 mins"); + expect(result.cookTime?.source).toBe("instructions_explicit"); + expect(result.cookTime?.explanation).toMatch(/Passive durations \(4 hr 5 mins\) were excluded/i); + expect(result.totalTime).toBeUndefined(); + }); + + it("preserves existing authored timing and serving values instead of proposing replacements", () => { + const result = recoverMetadataAlgorithmically({ + ...SMOKED_CHICKEN_REQUEST, + existingMetadata: { + prepTime: "4 hrs", + cookTime: "4 hrs", + totalTime: "8 hrs", + servings: 4, + category: "Main Course", + cuisine: "American BBQ", + }, + }); + expect(result.prepTime).toBeUndefined(); + expect(result.cookTime).toBeUndefined(); + expect(result.totalTime).toBeUndefined(); + expect(result.servings).toBeUndefined(); + expect(result.category).toBeUndefined(); + expect(result.cuisine).toBeUndefined(); + }); + + it("does not offer low-coverage or serving-ambiguous nutrition as credible recovered nutrition", () => { + const result = recoverMetadataAlgorithmically(SMOKED_CHICKEN_REQUEST); + expect(result.calories).toBeUndefined(); + expect(result.nutrition).toBeUndefined(); + }); + + it("suppresses the formerly displayed 3 kcal/serving low-coverage chicken dinner", () => { + const result = recoverMetadataAlgorithmically(CHICKEN_DINNER_LOW_COVERAGE_REQUEST); + expect(result.calories).toBeUndefined(); + expect(result.nutrition).toBeUndefined(); + }); + + it("reports complete batch nutrition as per-serving calories plus total-batch macros", () => { + const result = recoverMetadataAlgorithmically({ + title: "Simple Chicken Bowl", + rawMarkdown: "---\nservings: 4\n---\n# Simple Chicken Bowl", + ingredients: [ + "1 lb boneless skinless chicken breast", + "1 tbsp olive oil", + "1 tsp salt", + ], + instructions: ["Cook the chicken in olive oil for 10 minutes."], + }); + expect(result.calories).toBeDefined(); + expect(result.calories?.confidence).toBe("low"); + expect(result.calories?.value).toBeGreaterThanOrEqual(20); + expect(result.nutrition?.value?.servings).toBe(4); + expect(result.nutrition?.value?.calories).toBeGreaterThan(result.calories!.value); + expect(result.nutrition?.value?.calories).toBe(Math.round(result.calories!.value * 4)); + expect(result.calories?.explanation).toMatch(/kcal per serving/i); + expect(result.nutrition?.confidence).toBe("low"); }); }); @@ -195,8 +304,8 @@ describe("metadata recovery — provider abstraction parity (direct gemini remov modelAwareGemini(() => ({ text: "{ not valid json" })); try { const result = await recoverRecipeMetadata({ title: "Test Recipe", ingredients: ["1 cup flour"] }); - expect(result.prepTime?.value).toBe("5 mins"); - expect(result.category?.value).toBeDefined(); + expect(result.prepTime).toBeUndefined(); + expect(result.suggestedTags?.confidence).toBe("low"); } finally { vi.mocked(getGemini).mockReturnValue(null); } @@ -210,7 +319,7 @@ describe("metadata recovery — provider abstraction parity (direct gemini remov }); vi.mocked(getGemini).mockReturnValue(null); const result = await recoverRecipeMetadata({ title: "Test Recipe", ingredients: ["1 cup flour"] }); - expect(result.prepTime?.value).toBe("5 mins"); + expect(result.prepTime).toBeUndefined(); expect(aiCalls).toBe(0); }); @@ -222,7 +331,7 @@ describe("metadata recovery — provider abstraction parity (direct gemini remov }); try { const result = await recoverRecipeMetadata({ title: "Test Recipe", ingredients: ["1 cup flour"] }); - expect(result.prepTime?.value).toBe("5 mins"); + expect(result.prepTime).toBeUndefined(); expect(seenModels).toEqual([MODEL_CONFIG.metadataRecoveryPrimary, MODEL_CONFIG.metadataRecoveryFallback]); } finally { vi.mocked(getGemini).mockReturnValue(null); diff --git a/tests/unit/nutritionEstimatorSafety.test.ts b/tests/unit/nutritionEstimatorSafety.test.ts index 97362cb..8e4b48d 100644 --- a/tests/unit/nutritionEstimatorSafety.test.ts +++ b/tests/unit/nutritionEstimatorSafety.test.ts @@ -574,13 +574,14 @@ describe('metadata recovery — empty ingredients, trustedBasis, copy, legacy', const result = recoverMetadataAlgorithmically({ title: 'Empty', ingredients: [], instructions: [] }); expect(result.nutrition).toBeUndefined(); expect(result.calories).toBeUndefined(); - expect(result.category?.value).toBeDefined(); + expect(result.category).toBeUndefined(); expect(JSON.stringify(result)).not.toContain('1 portion ingredients'); }); it('15. recovery copy describes the curated local reference (no stale/unsupported claims)', () => { const result = recoverMetadataAlgorithmically({ title: 'X', + rawMarkdown: '---\nservings: 4\n---\n# X', ingredients: ['1 cup All-Purpose Flour'], instructions: ['Mix.'], }); diff --git a/tests/unit/vaultIntelligenceBatchRecovery.test.tsx b/tests/unit/vaultIntelligenceBatchRecovery.test.tsx new file mode 100644 index 0000000..1faae91 --- /dev/null +++ b/tests/unit/vaultIntelligenceBatchRecovery.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { VaultIntelligenceModal } from '../../src/components/VaultIntelligenceModal'; +import { hydrateAiSelections } from '../../src/application/aiSelection'; +import type { NetworkAdapter } from '../../src/application/adapters/NetworkAdapter'; +import type { ObsidianRecipe, RecoveredRecipeMetadata } from '../../src/types'; + +beforeAll(async () => { + await hydrateAiSelections({ get: async () => undefined }); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +function legacyRecipe(): ObsidianRecipe { + return { + id: 'smoked-chicken', + fileName: 'Smoked Chicken Dinner.md', + filePath: 'Smoked Chicken Dinner.md', + rawMarkdown: '---\ntitle: Smoked Chicken Dinner\n---\n# Smoked Chicken Dinner', + title: 'Smoked Chicken Dinner', + tags: ['food/recipes'], + category: '', + cuisine: '', + ingredients: [{ original: '1 whole chicken', name: 'whole chicken' }], + instructions: [{ stepNumber: 1, text: 'Smoke for 4 hours.' }], + callouts: [], + wikilinks: [], + dataviewFields: {}, + } as ObsidianRecipe; +} + +function network(): NetworkAdapter { + const recovered: RecoveredRecipeMetadata = { + cookTime: { value: '4 hrs', confidence: 'high', source: 'instructions_explicit', explanation: 'explicit active smoke' }, + servings: { value: 4, confidence: 'high', source: 'body_parsed', explanation: 'explicit yield' }, + category: { value: 'Baking & Breads', confidence: 'low', source: 'culinary_inference', explanation: 'guess' }, + cuisine: { value: 'French', confidence: 'low', source: 'culinary_inference', explanation: 'guess' }, + suggestedTags: { value: ['food/recipes', 'baking', 'bread'], confidence: 'low', source: 'culinary_inference', explanation: 'guess' }, + calories: { value: 3, confidence: 'low', source: 'culinary_inference', explanation: 'guess' }, + }; + return { + post: async (path: string) => { + if (path === '/api/recover-metadata') return { status: 200, ok: true, data: { recovered } }; + return { status: 200, ok: true, data: { ok: true } }; + }, + get: async () => ({ status: 200, ok: true, data: { ok: true } }), + request: async () => ({ status: 200, ok: true, data: { ok: true } }), + } as unknown as NetworkAdapter; +} + +describe('Vault Intelligence bulk recovery safety', () => { + it('applies only high-confidence supported fields and leaves speculative metadata untouched', async () => { + vi.spyOn(window, 'confirm').mockReturnValue(true); + const onSaveRecipe = vi.fn(async (_recipe: ObsidianRecipe) => {}); + render( + {}} + recipes={[legacyRecipe()]} + onSaveRecipe={onSaveRecipe} + network={network()} + />, + ); + + fireEvent.click(await screen.findByRole('button', { name: /Auto-Recover Missing/i })); + await waitFor(() => expect(onSaveRecipe).toHaveBeenCalledTimes(1), { timeout: 10000 }); + + const saved = onSaveRecipe.mock.calls[0][0]; + expect(saved.cookTime).toBe('4 hrs'); + expect(saved.servings).toBe(4); + expect(saved.category).toBe(''); + expect(saved.cuisine).toBe(''); + expect(saved.tags).toEqual(['food/recipes']); + expect(saved.calories).toBeUndefined(); + expect(saved.nutrition).toBeUndefined(); + expect(saved.rawMarkdown).not.toContain('baking'); + expect(saved.rawMarkdown).not.toContain('bread'); + }); +}); diff --git a/tests/unit/vaultIntelligenceRecoverySafety.test.ts b/tests/unit/vaultIntelligenceRecoverySafety.test.ts new file mode 100644 index 0000000..317d823 --- /dev/null +++ b/tests/unit/vaultIntelligenceRecoverySafety.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest'; +import { + assessRecipeHealth, + defaultAcceptedRecoveredFields, + selectBatchAcceptedRecoveredFields, +} from '../../src/utils/vaultIntelligence'; +import type { ObsidianRecipe, RecoveredRecipeMetadata } from '../../src/types'; +import { recoverMetadataAlgorithmically } from '../../server/metadataRecovery'; +import { SMOKED_CHICKEN_REQUEST } from '../fixtures/smokedChicken'; + +function recipe(overrides: Partial = {}): ObsidianRecipe { + return { + id: 'r1', + fileName: 'r1.md', + filePath: 'Recipes/r1.md', + rawMarkdown: '---\ntitle: Test\n---\n# Test', + title: 'Test', + tags: ['food/recipes', 'dinner'], + category: 'Main Course', + cuisine: 'American', + prepTime: '10 mins', + cookTime: '20 mins', + totalTime: '30 mins', + servings: 4, + calories: 300, + nutrition: { calories: 1200, protein: 40, carbohydrates: 50, fat: 20, servings: 4 }, + difficulty: 'Easy', + ingredients: [{ original: '1 cup rice', name: 'rice' }], + instructions: [{ stepNumber: 1, text: 'Cook.' }], + callouts: [], + wikilinks: [], + dataviewFields: {}, + ...overrides, + } as ObsidianRecipe; +} + +const recovered: RecoveredRecipeMetadata = { + prepTime: { value: '5 mins', confidence: 'high', source: 'body_parsed', explanation: 'explicit' }, + cookTime: { value: '20 mins', confidence: 'high', source: 'instructions_explicit', explanation: 'explicit' }, + servings: { value: 4, confidence: 'high', source: 'body_parsed', explanation: 'explicit' }, + category: { value: 'Baking & Breads', confidence: 'low', source: 'culinary_inference', explanation: 'suggested' }, + cuisine: { value: 'French', confidence: 'low', source: 'culinary_inference', explanation: 'suggested' }, + suggestedTags: { value: ['food/recipes', 'baking', 'bread'], confidence: 'low', source: 'culinary_inference', explanation: 'suggested' }, + calories: { value: 3, confidence: 'low', source: 'culinary_inference', explanation: 'estimate' }, + nutrition: { + value: { calories: 12, protein: 1, carbohydrates: 1, fat: 1, fiber: 0, sodium: 1, servings: 4 }, + confidence: 'low', + source: 'culinary_inference', + explanation: 'estimate', + }, +}; + +describe('Vault Intelligence recovery safety', () => { + it('defaults only supported missing fields and leaves category/cuisine/tags/nutrition opt-in', () => { + const accepted = defaultAcceptedRecoveredFields(recovered, ['prepTime', 'cookTime', 'servings', 'category', 'cuisine', 'suggestedTags', 'calories', 'nutrition']); + expect(accepted.prepTime).toBe(true); + expect(accepted.cookTime).toBe(true); + expect(accepted.servings).toBe(true); + expect(accepted.category).toBe(false); + expect(accepted.cuisine).toBe(false); + expect(accepted.suggestedTags).toBe(false); + expect(accepted.calories).toBe(false); + expect(accepted.nutrition).toBe(false); + }); + + it('bulk recovery applies only high-confidence explicit/body-parsed missing fields', () => { + const fields = selectBatchAcceptedRecoveredFields(recovered, ['prepTime', 'cookTime', 'servings', 'category', 'cuisine', 'suggestedTags', 'calories', 'nutrition']); + expect(fields).toEqual(['prepTime', 'cookTime', 'servings']); + expect(fields).not.toContain('category'); + expect(fields).not.toContain('cuisine'); + expect(fields).not.toContain('suggestedTags'); + expect(fields).not.toContain('calories'); + expect(fields).not.toContain('nutrition'); + }); + + it('does not apply a supported value when the recipe already has it', () => { + const fields = selectBatchAcceptedRecoveredFields(recovered, ['category', 'cuisine', 'suggestedTags', 'calories', 'nutrition']); + expect(fields).toEqual([]); + }); + + it('rejects a low-confidence or inference-only field even when it is missing', () => { + const unsafe: RecoveredRecipeMetadata = { + cookTime: { value: '4 hrs', confidence: 'medium', source: 'culinary_inference', explanation: 'guess' }, + servings: { value: 4, confidence: 'high', source: 'culinary_inference', explanation: 'guess' }, + }; + expect(selectBatchAcceptedRecoveredFields(unsafe, ['cookTime', 'servings'])).toEqual([]); + }); + + it('cannot bulk-persist the incorrect four-hour cook time from the owner sequence', () => { + const recovered = recoverMetadataAlgorithmically(SMOKED_CHICKEN_REQUEST); + expect(recovered.cookTime).toBeUndefined(); + const fields = selectBatchAcceptedRecoveredFields(recovered, ['prepTime', 'cookTime', 'totalTime', 'servings']); + expect(fields).not.toContain('cookTime'); + expect(fields).not.toContain('totalTime'); + }); + + it('treats a missing personal rating as optional rather than missing metadata', () => { + const report = assessRecipeHealth(recipe({ rating: undefined })); + expect(report.missingFields).not.toContain('rating'); + expect(report.status).toBe('complete'); + }); +});