diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index 4a2810f..16e79a0 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -125,6 +125,20 @@ function requestsManualUsdaChoice(message: string): boolean { return /\b(?:use|choose|select)\b.{0,45}\bthis\s+(?:usda\s+)?(?:food|match|record)\b/i.test(message); } +/** + * Self-initializing a review is a write to the unsaved working state, so it is + * narrower than the read-only investigation of an OPEN review. A generic + * "find a recipe" request must never start a nutrition analysis. Explicit + * repair commands ("resolve/match/investigate ...") may, as may any request + * that names nutrition, an ingredient, USDA evidence, or food. + */ +function requestsNutritionSelfInitialization(message: string): boolean { + if (!requestsNutritionInvestigation(message)) return false; + const text = message.toLowerCase().replace(/[’']/g, ''); + if (/\b(?:nutrition|nutrient|calories?|ingredients?|usda|foods?)\b/.test(text)) return true; + return /^\s*(?:please\s+)?(?:resolve|match|investigate)\b/.test(text); +} + function normalizedFoodTokens(text: string): ReadonlySet { return new Set( text @@ -215,12 +229,73 @@ function requestsVaultCount(message: string): boolean { } +interface NutritionInitResult { + readonly ok: boolean; + readonly tools: readonly string[]; + readonly message: string | null; +} + +/** + * The application already owns a review initializer. A SHISO investigation may + * use it when the user explicitly asked SHISO to investigate/resolve nutrition; + * this is the same loader and analyzer the visible Generate Nutrition action + * uses, and it changes only the UNSAVED working review. + */ +async function ensureNutritionReviewForInvestigation( + toolContext: ShisoToolContext, + signal?: AbortSignal, +): Promise { + if (toolContext.nutrition !== null) return { ok: true, tools: [], message: null }; + const tools: string[] = []; + if (toolContext.session === null) { + if (toolContext.loadBundle === undefined) { + return { ok: false, tools, message: 'The authenticated USDA catalogue is not available in this deployment.' }; + } + try { + await toolContext.loadBundle(); + } catch { + return { ok: false, tools, message: 'The authenticated USDA catalogue could not be loaded.' }; + } + tools.push('load_usda_catalog'); + } + if (signal?.aborted) return { ok: false, tools, message: 'The nutrition investigation was cancelled.' }; + if (toolContext.session === null) { + return { ok: false, tools, message: 'The authenticated USDA catalogue is not available.' }; + } + if (toolContext.runAnalysis === undefined) { + return { ok: false, tools, message: 'The application-owned nutrition analysis is not available for this recipe.' }; + } + let outcome; + try { + outcome = await toolContext.runAnalysis(signal); + } catch { + return { ok: false, tools, message: 'The application-owned nutrition analysis could not be initialized.' }; + } + tools.push('run_nutrition_analysis'); + if (signal?.aborted) return { ok: false, tools, message: 'The nutrition investigation was cancelled.' }; + if (!outcome.ok) { + return { ok: false, tools, message: outcome.message ?? 'The application-owned nutrition analysis could not be initialized.' }; + } + // The owner may publish the review from a React effect. Wait one event-loop + // turn, exactly as the existing post-selection handoff does. + if (toolContext.nutrition === null) { + await new Promise((resolve) => setTimeout(resolve, 0)); + } + if (toolContext.nutrition === null) { + return { ok: false, tools, message: 'The nutrition analysis ran, but its review was not published to SHISO.' }; + } + return { ok: true, tools, message: null }; +} + interface CulinaryProgress { readonly tools: readonly string[]; readonly pending: readonly Record[]; readonly question: string | null; readonly selected: number; readonly selectedSources: readonly string[]; + readonly selectedLineRefs: readonly string[]; + readonly investigation: ShisoObservation | null; + readonly error: string | null; } /** @@ -234,26 +309,34 @@ async function tryCulinaryIdentityProgress( toolContext: ShisoToolContext, signal?: AbortSignal, ): Promise { - if (signal?.aborted || toolContext.nutrition === null || toolContext.session === null) { - return { tools: [], pending: [], question: null, selected: 0, selectedSources: [] }; + if (signal?.aborted) { + return { tools: [], pending: [], question: null, selected: 0, selectedSources: [], selectedLineRefs: [], investigation: null, error: 'The nutrition investigation was cancelled.' }; + } + const initialized = await ensureNutritionReviewForInvestigation(toolContext, signal); + if (!initialized.ok) { + return { tools: initialized.tools, pending: [], question: null, selected: 0, selectedSources: [], selectedLineRefs: [], investigation: null, error: initialized.message }; } let investigation: ShisoObservation; try { investigation = await executeShisoTool({ tool: 'investigate_unresolved_ingredients' }, toolContext, signal); } catch { - return { tools: [], pending: [], question: null, selected: 0, selectedSources: [] }; + return { tools: initialized.tools, pending: [], question: null, selected: 0, selectedSources: [], selectedLineRefs: [], investigation: null, error: 'The nutrition review could not be investigated.' }; } - if (signal?.aborted || !investigation.ok) { - return { tools: [], pending: [], question: null, selected: 0, selectedSources: [] }; + if (signal?.aborted) { + return { tools: initialized.tools, pending: [], question: null, selected: 0, selectedSources: [], selectedLineRefs: [], investigation: null, error: 'The nutrition investigation was cancelled.' }; + } + if (!investigation.ok) { + return { tools: [...initialized.tools, investigation.tool], pending: [], question: null, selected: 0, selectedSources: [], selectedLineRefs: [], investigation: null, error: (investigation as { message: string }).message }; } const data = investigation.data; - const tools: string[] = ['investigate_unresolved_ingredients']; + const tools: string[] = [...initialized.tools, 'investigate_unresolved_ingredients']; const actions = Array.isArray(data['next_actions']) ? data['next_actions'].filter((entry): entry is Record => entry !== null && typeof entry === 'object' && !Array.isArray(entry)) : []; let selected = 0; const selectedSources: string[] = []; + const selectedLineRefs: string[] = []; for (const action of actions.slice(0, 8)) { if (action['kind'] !== 'select_source') continue; const lineRef = action['line_ref']; @@ -276,7 +359,9 @@ async function tryCulinaryIdentityProgress( selected += 1; const description = typeof selection.data['description'] === 'string' ? selection.data['description'] : null; const grams = typeof selection.data['resolved_grams'] === 'number' ? selection.data['resolved_grams'] : null; - if (description !== null) selectedSources.push(`${description}${grams !== null ? ` (${grams} g)` : ''}`); + const roundedGrams = grams === null ? null : Math.round(grams * 100) / 100; + if (description !== null) selectedSources.push(`${description}${roundedGrams !== null ? ` (${roundedGrams} g)` : ''}`); + selectedLineRefs.push(lineRef); // The owning review dispatches asynchronously; let it commit before the // next selection/completion reads the same live owner. await new Promise((resolve) => setTimeout(resolve, 0)); @@ -287,7 +372,7 @@ async function tryCulinaryIdentityProgress( entry !== null && typeof entry === 'object' && !Array.isArray(entry)) : []; const question = typeof data['consolidated_question'] === 'string' ? data['consolidated_question'] : null; - return { tools, pending, question, selected, selectedSources }; + return { tools, pending, question, selected, selectedSources, selectedLineRefs, investigation, error: null }; } export interface ShisoConversationState { @@ -610,7 +695,7 @@ export async function runShisoConversationTurn( const identityFirst = /\b(?:remaining|unresolved)\b/i.test(trimmed) && /\bnutrition\b/i.test(trimmed); const culinaryProgress = identityFirst ? await tryCulinaryIdentityProgress(deps.toolContext, deps.signal) - : { tools: [] as readonly string[], pending: [] as readonly Record[], question: null as string | null, selected: 0, selectedSources: [] as readonly string[] }; + : { tools: [] as readonly string[], pending: [] as readonly Record[], question: null as string | null, selected: 0, selectedSources: [] as readonly string[], selectedLineRefs: [] as readonly string[], investigation: null, error: null }; if (deps.signal?.aborted) return cancelled(working, toolsUsed); let result: ShisoObservation; try { @@ -759,40 +844,73 @@ export async function runShisoConversationTurn( // returns the real alternatives and leaves any choice to the established UI. if ( requestsNutritionInvestigation(trimmed) && - deps.toolContext.nutrition !== null && + ( + deps.toolContext.nutrition !== null || + (deps.toolContext.runAnalysis !== undefined && requestsNutritionSelfInitialization(trimmed)) + ) && !requestsManualUsdaChoice(trimmed) && !classifySaveIntent(trimmed).authorized ) { if (deps.signal?.aborted) return cancelled(working, toolsUsed); - let result: ShisoObservation; - try { - result = await executeShisoTool({ tool: 'investigate_unresolved_ingredients' }, deps.toolContext, deps.signal); - } catch { - result = { ok: false, tool: 'investigate_unresolved_ingredients', code: 'unsupported', message: 'The nutrition review could not be investigated.' }; - } + const progress = await tryCulinaryIdentityProgress(deps.toolContext, deps.signal); if (deps.signal?.aborted) return cancelled(working, toolsUsed); - const lineNotes = result.ok && Array.isArray(result.data['lines']) - ? result.data['lines'].slice(0, 6).flatMap((rawLine) => { + const result = progress.investigation; + if (result === null) { + const message = `${progress.error ?? 'The relevant nutrition review could not be initialized or investigated.'} Nothing was applied or saved.`; + return { + ok: true, + state: appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 }), + message, + status: null, + toolsUsed: Object.freeze([...progress.tools]) as readonly string[], + }; + } + const selectedSet = new Set(progress.selectedLineRefs); + const pendingSet = new Set(progress.pending.flatMap((choice) => + typeof choice['line_ref'] === 'string' ? [choice['line_ref']] : [])); + const data = result.ok ? result.data : {}; + const lineNotes = result.ok && Array.isArray(data['lines']) + ? data['lines'].slice(0, 12).flatMap((rawLine) => { if (rawLine === null || typeof rawLine !== 'object' || Array.isArray(rawLine)) return []; const line = rawLine as Record; if (typeof line['label'] !== 'string') return []; + const lineRef = typeof line['line_ref'] === 'string' ? line['line_ref'] : null; + if (lineRef !== null && (selectedSet.has(lineRef) || pendingSet.has(lineRef))) return []; const label = line['label'].slice(0, 200); - const reason = typeof line['reason'] === 'string' ? ` — ${line['reason'].slice(0, 180)}` : ''; - const alternatives = Array.isArray(line['alternatives']) - ? line['alternatives'].slice(0, 2).flatMap((candidate) => - candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate) && typeof (candidate as Record)['description'] === 'string' - ? [(candidate as Record)['description'].slice(0, 160)] - : []) - : []; - return [`${label}${reason}${alternatives.length ? ` · USDA options: ${alternatives.join('; ')}` : ''}`]; + const culinary = line['culinary'] !== null && typeof line['culinary'] === 'object' && !Array.isArray(line['culinary']) + ? line['culinary'] as Record + : {}; + const nextAction = culinary['next_action'] !== null && typeof culinary['next_action'] === 'object' && !Array.isArray(culinary['next_action']) + ? culinary['next_action'] as Record + : {}; + const note = typeof nextAction['note'] === 'string' + ? nextAction['note'].slice(0, 220) + : typeof line['reason'] === 'string' + ? line['reason'].slice(0, 220) + : null; + return [note === null ? label : `${label} — ${note}`]; }).join('\n') : ''; + const initialized = progress.tools.includes('run_nutrition_analysis'); + const examined = typeof data['examined'] === 'number' ? data['examined'] : progress.selectedLineRefs.length; + const leader = `I ${initialized ? 'initialized the unsaved nutrition review and ' : ''}examined ${examined} unresolved ingredient line(s).`; + const selectedProgress = progress.selectedSources.length > 0 + ? ` Selected ${progress.selectedSources.length} authenticated source(s): ${progress.selectedSources.slice(0, 6).join('; ')}${progress.selectedSources.length > 6 ? `; and ${progress.selectedSources.length - 6} more` : ''}.` + : ' No authenticated source could be selected without guessing.'; + const remainingNotes = lineNotes.length > 0 + ? ` Still unresolved:\n${lineNotes}` + : ''; + const question = progress.question !== null + ? ` ${progress.question}` + : data['remaining'] + ? ' The remaining lines need a specific food or a measured amount that I cannot infer.' + : ''; const message = result.ok - ? `${result.summary}${lineNotes ? `\n${lineNotes}` : ''} ${result.data['remaining'] ? 'Open Advanced Nutrition to review candidate records and choose “Use this match” where appropriate.' : 'No food was changed.'} Nothing was saved.` - : `${(result as { message: string }).message} No recipe edit or save was made.`; + ? `${leader}${selectedProgress}${remainingNotes}${question} Nothing was applied or saved.` + : `${(result as { message: string }).message} Nothing was applied or saved.`; let next = appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 }); if (result.ok) next = recordFinding(next, { tool: result.tool, ok: true, summary: result.summary }); - return { ok: true, state: next, message, status: null, toolsUsed: Object.freeze(['investigate_unresolved_ingredients']) }; + return { ok: true, state: next, message, status: null, toolsUsed: Object.freeze([...progress.tools]) as readonly string[] }; } /** diff --git a/src/application/shisoTools.ts b/src/application/shisoTools.ts index f4dc478..3ba7892 100644 --- a/src/application/shisoTools.ts +++ b/src/application/shisoTools.ts @@ -44,6 +44,7 @@ import { candidateIdentityVerdict, projectCulinaryIngredient, projectIngredientAlternatives, + selectDeterministicVolumePortionIndex, type AdvancedNutritionSession, } from '../core/nutritionV2/phase4'; import { buildPortionChoice } from '../core/nutritionV2/phase4/portion'; @@ -1006,9 +1007,9 @@ function culinaryLineInvestigation( const seen = new Set(); let rejected = 0; const branchReports: Array> = []; - - for (const identity of projection.identities.slice(0, 4)) { - const review = ctx.session.reviewIngredient({ name: identity }); + const branchIdentities = [...projection.identities]; + const searchBranch = (identity: string): void => { + const review = ctx.session!.reviewIngredient({ name: identity }); const exact = review.outcome === 'matched_exact'; const ranked = exact ? review.candidates.filter((candidate) => candidate.fdc_id === review.selected_fdc_id) @@ -1024,10 +1025,67 @@ function culinaryLineInvestigation( rejected += 1; continue; } - const portions = ctx.session.reviewPortions(candidate.fdc_id); + const portions = ctx.session!.reviewPortions(candidate.fdc_id); const usable = portions.ok ? portions.review.candidates.filter((portion) => portion.kind !== 'unusable' && portion.gram_weight > 0 && portion.gram_weight < 100000) : []; + // Match the authored measurement, not merely the first portion on the + // record. Density makes any compatible volume portion equivalent for a + // volume line and any mass portion equivalent for a mass line, but a + // count must name the same thing ("tortilla" is not "slice" or "package"). + let preferred: (typeof usable)[number] | undefined; + const singularTokens = (value: string): readonly string[] => + value + .toLowerCase() + .replace(/[^a-z0-9]+/g, ' ') + .split(/\s+/) + .filter((token) => token.length >= 3) + .map((token) => token.replace(/s$/, '')); + if (projection.measurement_kind === 'volume' && projection.milliliters !== null) { + const milliliters = projection.milliliters; + const index = selectDeterministicVolumePortionIndex( + ctx.session!, + candidate.fdc_id, + milliliters, + projection.normalized_unit ?? projection.unit ?? undefined, + identity, + ); + const volumePortions = usable.filter((portion) => portion.kind === 'volume'); + const gramsFor = (portion: (typeof volumePortions)[number]): number | undefined => { + if (portion.volume_ml === null || !(portion.volume_ml > 0) || !(portion.gram_weight > 0)) return undefined; + const grams = (milliliters / portion.volume_ml) * portion.gram_weight; + return Number.isFinite(grams) && grams > 0 ? grams : undefined; + }; + const first = volumePortions[0]; + const firstGrams = first === undefined ? undefined : gramsFor(first); + // Only use a different volume portion when every usable volume portion + // resolves to the same weight within portion-rounding tolerance. This + // keeps a tablespoon of butter honest while refusing to guess between + // genuinely different preparations of the same food. + const equivalent = firstGrams !== undefined && volumePortions.every((portion) => { + const grams = gramsFor(portion); + return grams !== undefined && Math.abs(grams - firstGrams) <= Math.max(0.1, firstGrams * 0.01); + }); + preferred = index === undefined + ? equivalent ? first : undefined + : usable.find((portion) => portion.index === index) ?? (equivalent ? first : undefined); + } else if (projection.measurement_kind === 'mass' && projection.grams !== null) { + preferred = usable.find((portion) => portion.kind === 'mass'); + } else { + // Count-like lines (including lines whose authored count unit did not + // parse, such as "8 burrito-size tortillas") may use a count portion + // only when its measure names the same item. The authored unit wins when + // present, so "1 can tomatoes" can never fall through to "1 tomato". + const unitTokens = projection.unit !== null ? singularTokens(projection.unit) : []; + const nounTokens = singularTokens(projection.count_noun ?? projection.identity); + const requested = new Set(unitTokens.length > 0 ? unitTokens : nounTokens); + if (projection.amount !== null && requested.size > 0) { + preferred = usable.find((portion) => { + if (portion.kind !== 'count') return false; + return singularTokens(portion.measure).some((token) => requested.has(token)); + }); + } + } const record = { branch: identity, fdc_id: candidate.fdc_id, @@ -1041,8 +1099,8 @@ function culinaryLineInvestigation( measure: portion.display_label.slice(0, 120), gram_weight: portion.gram_weight, })), - preferred_portion_index: usable[0]?.index ?? null, - preferred_grams: usable[0]?.gram_weight ?? null, + preferred_portion_index: preferred?.index ?? null, + preferred_grams: preferred?.gram_weight ?? null, }; const key = `${identity}:${candidate.fdc_id}`; if (seen.has(key)) continue; @@ -1055,10 +1113,23 @@ function culinaryLineInvestigation( authority_exact: exact, compatible_candidates: branchCandidates, }); + }; + + for (const identity of branchIdentities.slice(0, 4)) searchBranch(identity); + // Compound size/format descriptors can hide an otherwise exact food head + // ("burrito tortillas" -> "tortillas"). Only try the head after the full + // identity produced no candidate at all; never broaden a line that already + // has evidence. + if (candidates.length === 0 && branchIdentities.length === 1) { + for (const identity of projection.fallback_identities) { + if (!branchIdentities.includes(identity)) searchBranch(identity); + } } const primaryIdentity = projection.identities[0] ?? projection.identity; - const primaryCandidates = candidates.filter((candidate) => candidate['branch'] === primaryIdentity); + const primaryCandidates = (projection.equal_choice || projection.flexible_mixture) + ? candidates.filter((candidate) => candidate['branch'] === primaryIdentity) + : candidates; const selectable = primaryCandidates.find((candidate) => candidate['preferred_portion_index'] !== null); let nextAction: Record; let pendingChoice: Record | null = null; @@ -1118,13 +1189,13 @@ function culinaryLineInvestigation( kind: 'choose_candidate', line_ref: row.line_ref, candidates: primaryCandidates.slice(0, 3), - note: 'Compatible candidates exist but none has a usable authenticated portion. Ask for a measured amount or inspect a candidate; do not invent a weight.', + note: 'Compatible candidates exist, but none has an authenticated portion that matches the authored measurement without guessing. Ask for the measured weight actually used; do not substitute a package, slice, or different preparation.', }; pendingChoice = { - kind: 'candidate', + kind: 'measurement', line_ref: row.line_ref, label: original.slice(0, 160), - options: primaryCandidates.slice(0, 3).map((candidate) => candidate['description']), + note: 'A compatible authenticated record exists, but its portions do not match the authored measurement. Only a measured weight from the user can resolve it.', }; } else { nextAction = { diff --git a/src/components/ShisoModal.tsx b/src/components/ShisoModal.tsx index 8050c65..585db51 100644 --- a/src/components/ShisoModal.tsx +++ b/src/components/ShisoModal.tsx @@ -719,13 +719,26 @@ export function ShisoModal({ : undefined; }, get applyNutritionSourceSelection() { - if (shisoRef.current.canApplyNutritionSourceSelection) { - return (input: Parameters>[0]) => - shisoRef.current.applyNutritionSourceSelection(input); - } - return applyIndependentNutritionSourceSelection - ? async (input) => applyIndependentNutritionSourceSelection(input) - : undefined; + const cardOwnerAvailable = shisoRef.current.canApplyNutritionSourceSelection; + if (!cardOwnerAvailable && applyIndependentNutritionSourceSelection === undefined) return undefined; + return async (input: Parameters>[0]) => { + let result = cardOwnerAvailable + ? await shisoRef.current.applyNutritionSourceSelection(input) + : await applyIndependentNutritionSourceSelection!(input); + // A mounted recipe card can be registered while its own review has + // never been initialized (for example, a Chat-driven self-init). Its + // ownership failure must not hide the independent review the current + // turn just created. Real selection rejections are not retried. + if ( + cardOwnerAvailable && + applyIndependentNutritionSourceSelection !== undefined && + !result.ok && + (result.code === 'no_active_review' || result.code === 'no_nutrition_review' || result.code === 'stale_recipe') + ) { + result = await applyIndependentNutritionSourceSelection(input); + } + return result; + }; }, isTrustedNutritionSourceSelection: (lineRef, description) => { const message = trustedNutritionSelectionMessageRef.current.toLocaleLowerCase(); diff --git a/src/core/nutritionV2/phase4/ingredientInvestigation.ts b/src/core/nutritionV2/phase4/ingredientInvestigation.ts index b03145f..63e263b 100644 --- a/src/core/nutritionV2/phase4/ingredientInvestigation.ts +++ b/src/core/nutritionV2/phase4/ingredientInvestigation.ts @@ -37,9 +37,17 @@ export interface CulinaryIngredientProjection { readonly identity: string; /** Every identity branch that may be investigated (primary/equal/mixture). */ readonly identities: readonly string[]; + /** Safe head-noun fallbacks tried only when the full identity has no candidates. */ + readonly fallback_identities: readonly string[]; readonly amount: number | null; readonly unit: string | null; + readonly normalized_unit: string | null; readonly measurement_kind: CulinaryMeasurementKind; + /** Canonical millilitres/mass from the authored quantity, when parsed. */ + readonly milliliters: number | null; + readonly grams: number | null; + /** The authored count noun (`clove`, `slice`), never an inferred substitute. */ + readonly count_noun: string | null; readonly alternatives: readonly CulinaryAlternative[]; readonly primary_index: number | null; /** Authored flexible mixture such as `(such as red onion, pepper or broccoli)`. */ @@ -156,9 +164,21 @@ export function projectCulinaryIngredient(text: string): CulinaryIngredientProje ? alternatives.map((entry) => entry.label) : [alternatives.find((entry) => entry.primary)?.label ?? identity] : [identity]; + const identityTokens = projected.food_tokens; + // A compound size/format descriptor (for example `burrito-size tortillas`) + // can hide the food head even though the head itself is an exact identity. + // Restrict the fallback to that shape: dropping a varietal adjective from + // `cheddar cheese` to generic `cheese` would be a broader substitution than + // the user asked for. + const hasCompositeDescriptor = identityTokens.length > 1 + && identityTokens.some((token) => COMPOSITE_DISH_TOKENS.has(token)); + const fallbackIdentities = !flexibleMixture && !equalChoice && hasCompositeDescriptor + ? [identityTokens[identityTokens.length - 1]!] + : []; - const amount = parsed.ok ? parsed.parsed.amount : null; - const unit = parsed.ok ? parsed.parsed.raw_unit ?? null : null; + const facts = parsed.ok ? parsed.parsed : null; + const amount = facts?.amount ?? null; + const unit = facts?.raw_unit ?? null; const measurementKind: CulinaryMeasurementKind = parsed.ok ? parsed.parsed.measurement_kind === 'mass' ? 'mass' @@ -179,9 +199,14 @@ export function projectCulinaryIngredient(text: string): CulinaryIngredientProje original, identity, identities: Object.freeze(identities.filter((entry) => entry.length > 0)), + fallback_identities: Object.freeze(fallbackIdentities.filter((entry) => entry.length >= 3)), amount, unit, + normalized_unit: facts?.normalized_unit ?? null, measurement_kind: measurementKind, + milliliters: facts?.milliliters ?? null, + grams: facts?.grams ?? null, + count_noun: facts?.count_noun ?? null, alternatives: Object.freeze(alternatives), primary_index: primaryIndex, flexible_mixture: flexibleMixture, diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index 5233055..6ff69f1 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -578,7 +578,7 @@ describe('SHISO agent foundation real App save closure', () => { expect(persisted.recipes.find((entry) => entry.title === 'Chef Pagination Fixture')?.codexNutrition).toBeUndefined(); }, 120000); - it('AUDIT Phase 1 continues after a user choice and persists the completed review', async () => { + it('AUDIT Phase 1 self-initializes, continues after a user choice, and persists the completed review without opening Advanced Nutrition', async () => { await hydrateAiSelections(settings); const rootPath = await mkdtemp(join('/tmp', 'tkc-phase1-continuation-')); roots.push(rootPath); @@ -605,6 +605,7 @@ describe('SHISO agent foundation real App save closure', () => { })); const captured = capturingNetwork([ { ok: true, kind: 'tool_request', tool: 'apply_nutrition_review', args: { tool: 'apply_nutrition_review' } }, + { ok: true, kind: 'reply', text: 'Chicken breast was applied to the working recipe. It is not saved.', proposals: [] }, { ok: true, kind: 'tool_request', tool: 'save_working_recipe', args: { tool: 'save_working_recipe' } }, { ok: true, kind: 'reply', text: 'Chicken breast was applied and saved to the Vault.', proposals: [] }, ], { @@ -624,25 +625,24 @@ describe('SHISO agent foundation real App save closure', () => { await screen.findByText(/Connected live to vault "Disposable Phase 1 Continuation Vault"/); fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); fireEvent.click(await screen.findByRole('button', { name: 'Continuation Chicken Fixture' })); - fireEvent.click(await screen.findByRole('button', { name: 'Generate Nutrition' })); - await screen.findByRole('dialog', { name: 'Advanced Nutrition' }); - await waitFor(() => expect(loader).toHaveBeenCalledTimes(1)); - const authorityToggle = await screen.findByTestId('shiso-nutrition-authority-toggle') as HTMLInputElement; - expect(authorityToggle.checked).toBe(false); - fireEvent.click(authorityToggle); - await waitFor(() => expect(authorityToggle.checked).toBe(true)); - fireEvent.click(screen.getByRole('button', { name: 'Close Advanced Nutrition' })); + // Deliberately do NOT open Advanced Nutrition. Chat must initialize the + // application-owned review, ask its one genuine choice, then continue. fireEvent.click(await screen.findByTestId('recipe-shiso-entry')); const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; fireEvent.change(composer, { target: { value: 'SHISO, resolve the remaining nutrition for this recipe.' } }); fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(1)); await waitFor(() => expect(document.body.textContent).toMatch(/which did you actually use|chicken breast or turkey breast/i), { timeout: 20000 }); expect(captured.turns).toHaveLength(0); - fireEvent.change(composer, { target: { value: 'Use chicken breast. Apply and save the nutrition.' } }); + fireEvent.change(composer, { target: { value: 'Use chicken breast. Apply the nutrition.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Nutrition was applied to the working recipe. It is not saved'), { timeout: 20000 }); + + fireEvent.change(composer, { target: { value: 'Save my changes.' } }); fireEvent.click(screen.getByRole('button', { name: 'Send' })); - await waitFor(() => expect(document.body.textContent).toContain('Chicken breast was applied and saved to the Vault.'), { timeout: 20000 }); + await waitFor(() => expect(document.body.textContent).toMatch(/saved to the Vault|canonical Vault save confirmed persistence|Chicken breast was applied and saved/i), { timeout: 20000 }); expect(captured.turns.length).toBeGreaterThan(0); expect(JSON.stringify(captured.turns[0]?.['observation'] ?? {})).toContain('select_usda_nutrition_source'); @@ -656,7 +656,83 @@ describe('SHISO agent foundation real App save closure', () => { selection_origin: 'shiso_user_directed', amount: { value: 280, unit: 'g' }, }); - expect(JSON.stringify(block)).not.toContain('42'); + // Assert the rejected food structurally: a raw substring match against the + // whole block would also catch the ISO timestamp. + expect((block.ingredients as Array<{ source_food_id?: string }>).map((entry) => entry.source_food_id)).not.toContain('42'); + }, 120000); + + it('AUDIT Phase 1 self-initializes nutrition from Chat and resolves defensible lines without opening Advanced Nutrition', async () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-live-selfinit-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', 'Live Acceptance Breakfast.md'); + await mkdir(dirname(recipePath), { recursive: true }); + const markdown = [ + '---', 'title: "Live Acceptance Breakfast"', 'tags:', ' - food/recipes', + 'category: Breakfast', 'servings: 4', '---', '# Live Acceptance Breakfast', + '## Ingredients', + '- 2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)', + '- 1 pound breakfast sausage or Italian sausage', + '- 2 pinches salt', + '- 2 teaspoons unsalted butter', + '- 8 burrito-size tortillas', + '- 2 cups shredded cheddar cheese (or Monterey Jack)', + '- 8 large eggs', + '- 1 cup milk', + '## Instructions', '1. Cook the filling.', '2. Fill and roll.', '', + ].join('\n'); + await writeFile(recipePath, markdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable Live Acceptance Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + + const { manifest, records } = buildMatchingBundle([ + { fdcId: 51, dataType: 'sr_legacy', description: 'Butter, without salt', portions: [{ amount: 1, measure: 'tbsp', gram_weight: 14.2, sequence: 1 }, { amount: 1, measure: 'cup', gram_weight: 227, sequence: 2 }] }, + { fdcId: 52, dataType: 'sr_legacy', description: 'Cheese, cheddar', portions: [{ amount: 1, measure: 'slice', gram_weight: 17, sequence: 1 }, { amount: 1, measure: 'cup', gram_weight: 105, sequence: 2 }] }, + { fdcId: 53, dataType: 'sr_legacy', description: 'Egg, whole, raw', portions: [{ amount: 1, measure: 'egg', gram_weight: 50, sequence: 1 }] }, + { fdcId: 54, dataType: 'sr_legacy', description: 'Milk, whole', portions: [{ amount: 1, measure: 'cup', gram_weight: 244, sequence: 1 }] }, + { fdcId: 55, dataType: 'sr_legacy', description: 'Tortilla, flour', portions: [{ amount: 1, measure: 'tortilla', gram_weight: 45, sequence: 1 }] }, + { fdcId: 56, dataType: 'sr_legacy', description: 'Sausage, turkey, breakfast links, mild, raw', portions: [{ amount: 1, measure: 'link', gram_weight: 28, sequence: 1 }] }, + { fdcId: 57, dataType: 'sr_legacy', description: 'Salt, table', portions: [{ amount: 1, measure: 'tsp', gram_weight: 6, sequence: 1 }] }, + { fdcId: 58, dataType: 'sr_legacy', description: 'Raw vegetable, NFS', portions: [{ amount: 1, measure: 'cup', gram_weight: 120, sequence: 1 }] }, + ]); + const created = createAdvancedNutritionSession(manifest, records); + if (!created.ok) throw new Error('fixture USDA session failed'); + const loader = vi.fn(async (): Promise => ({ + ok: true, session: created.session, metadata: created.session.metadata(), attribution: USDA_ATTRIBUTION, + })); + const captured = capturingNetwork([ + { ok: true, kind: 'reply', text: 'No provider step was required.', proposals: [] }, + ], { + '/api/nutrition/product-access': { ok: true, version: NUTRITION_PRODUCT_ACCESS_VERSION, tier: 'ai_advanced' }, + '/api/providers': { providers: [] }, + }); + + render( + + + , + ); + + fireEvent.click(await screen.findByRole('button', { name: 'Connect Vault' })); + fireEvent.click(await screen.findByRole('tab', { name: 'Live Directory Sync' })); + fireEvent.click(await screen.findByRole('button', { name: 'Choose Local Obsidian Vault Folder' })); + await screen.findByText(/Connected live to vault "Disposable Live Acceptance Vault"/); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: 'Live Acceptance Breakfast' })); + + // Deliberately do NOT open Advanced Nutrition. + fireEvent.click(await screen.findByTestId('recipe-shiso-entry')); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: "SHISO, investigate the unresolved nutrition for my Breakfast Burritos recipe. Use your available tools to identify the correct ingredients, find authenticated USDA sources, and resolve everything you can confidently resolve. Reject inappropriate food matches. Don't guess which ingredient alternatives I used. If you need information from me, ask one consolidated question covering all outstanding choices. Show me exactly what you've accomplished and what remains unresolved. Do not Apply or Save anything yet." } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toMatch(/Selected .*authenticated source.*\(.*g\)/i), { timeout: 25000 }); + await waitFor(() => expect(document.body.textContent).toMatch(/consolidated choice|which did you actually use|what measured amount/i), { timeout: 15000 }); + + expect(loader).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('dialog', { name: 'Advanced Nutrition' })).toBeNull(); + expect(captured.turns).toHaveLength(0); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((entry) => entry.title === 'Live Acceptance Breakfast')?.codexNutrition).toBeUndefined(); }, 120000); }); diff --git a/tests/unit/shisoEstimatedNutrition.test.ts b/tests/unit/shisoEstimatedNutrition.test.ts index 142a080..090a965 100644 --- a/tests/unit/shisoEstimatedNutrition.test.ts +++ b/tests/unit/shisoEstimatedNutrition.test.ts @@ -186,12 +186,53 @@ describe('SHISO AI-estimated nutrition resolution', () => { recipeKey: 'oatmeal-bars', sessionIdentity: 'session' }, }, initialShisoConversation(), 'Resolve the light brown sugar.'); expect(result.toolsUsed).toEqual(['investigate_unresolved_ingredients']); - expect(result.message).toContain('Investigated all 1 unresolved ingredient'); + expect(result.message).toContain('I examined 1 unresolved ingredient line'); + expect(result.message).toContain('1/2 white onion, finely diced'); expect(tools.runAnalysis).not.toHaveBeenCalled(); expect(tools.runAiNutrition).not.toHaveBeenCalled(); expect(tools.applyIngredientEdits).not.toHaveBeenCalled(); }); + it('does not initialize a review for a nutrition question that did not request investigation', async () => { + const runAnalysis = vi.fn(async () => ({ + ok: true, analyzed: true, summary: 'must not run', matched: 0, + needs_amount: 0, needs_match: 0, total_lines: 0, + unresolved_line_refs: [], preview_state: 'absent' as const, + })); + const tools = { ...context(), nutrition: null, runAnalysis } as unknown as ShisoToolContext; + const network = { ...noProviderNetwork, post: vi.fn(async () => ({ ok: true, status: 200, data: { + ok: true, kind: 'reply', text: 'Two ingredient lines remain unresolved.', proposals: [], model_invocations_used: 1, tool_calls_used: 0, + } })) } as unknown as NetworkAdapter; + const result = await runShisoConversationTurn({ network, toolContext: tools, + context: { recipe: { title: 'Oatmeal Bars', servings: 8, ingredientCount: 2, stepCount: 0 }, + nutrition: { available: false, summary: null, unresolvedCount: 2, needsAmountCount: 0, needsMatchCount: 2, unsavedWorkingReview: false }, + recipeKey: 'oatmeal-bars', sessionIdentity: 'session' }, + }, initialShisoConversation(), 'Which nutrition values are still unresolved?'); + expect(runAnalysis).not.toHaveBeenCalled(); + expect(result.toolsUsed).not.toContain('run_nutrition_analysis'); + expect(result.message).toContain('Two ingredient lines remain unresolved.'); + }); + + it('does not self-initialize nutrition for a generic find-a-recipe request', async () => { + const runAnalysis = vi.fn(async () => ({ + ok: true, analyzed: true, summary: 'must not run', matched: 0, + needs_amount: 0, needs_match: 0, total_lines: 0, + unresolved_line_refs: [], preview_state: 'absent' as const, + })); + const tools = { ...context(), nutrition: null, runAnalysis } as unknown as ShisoToolContext; + const network = { ...noProviderNetwork, post: vi.fn(async () => ({ ok: true, status: 200, data: { + ok: true, kind: 'reply', text: 'Here are three dinner recipes.', proposals: [], model_invocations_used: 1, tool_calls_used: 0, + } })) } as unknown as NetworkAdapter; + const result = await runShisoConversationTurn({ network, toolContext: tools, + context: { recipe: { title: 'Guacamole', servings: 4, ingredientCount: 1, stepCount: 0 }, + nutrition: { available: false, summary: null, unresolvedCount: 1, needsAmountCount: 0, needsMatchCount: 1, unsavedWorkingReview: false }, + recipeKey: 'guacamole', sessionIdentity: 'session' }, + }, initialShisoConversation(), 'Find a recipe for dinner.'); + expect(runAnalysis).not.toHaveBeenCalled(); + expect(result.toolsUsed).not.toContain('run_nutrition_analysis'); + expect(result.message).toContain('Here are three dinner recipes.'); + }); + it('directs USDA food choices to the explicit Advanced Nutrition control', async () => { const result = await runShisoConversationTurn({ network: noProviderNetwork, toolContext: context(), context: { recipe: { title: 'Guacamole', servings: 4, ingredientCount: 1, stepCount: 0 }, diff --git a/tests/unit/shisoLiveAcceptance.test.ts b/tests/unit/shisoLiveAcceptance.test.ts new file mode 100644 index 0000000..9216b4d --- /dev/null +++ b/tests/unit/shisoLiveAcceptance.test.ts @@ -0,0 +1,127 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { composeAdvancedNutritionSessionFromBundle } from '../../src/core/nutritionV2/runtime'; +import { USDA_BUNDLE_RELEASE_LOCK } from '../../src/core/nutritionV2/usda/releaseLock'; +import { createShisoNutritionReviewController } from '../../src/application/shisoNutritionReview'; +import { initialShisoConversation, runShisoConversationTurn } from '../../src/application/shisoConversation'; +import { toShisoRecipeView } from '../../src/application-ui/useShisoRecipeContext'; +import { parseIngredient } from '../../src/core/nutritionV2/matching/parse'; +import type { AdvancedNutritionSession } from '../../src/core/nutritionV2/phase4'; +import type { ObsidianRecipe } from '../../src/types'; + +const ROOT = process.cwd(); +const BUNDLE_DIR = join(ROOT, 'data/advanced-nutrition/usda', USDA_BUNDLE_RELEASE_LOCK.bundle_release); +const LINES = [ + '2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)', + '1 pound breakfast sausage or Italian sausage', + '2 pinches salt', + '2 teaspoons unsalted butter', + '8 burrito-size tortillas', + '2 cups shredded cheddar cheese (or Monterey Jack)', + '8 large eggs', + '1 cup milk', +]; + +let session: AdvancedNutritionSession; + +beforeAll(async () => { + const composed = await composeAdvancedNutritionSessionFromBundle({ + files: USDA_BUNDLE_RELEASE_LOCK.artifact_filenames.map((name) => ({ + name, + bytes: new Uint8Array(readFileSync(join(BUNDLE_DIR, name))), + })), + } as never); + if (!composed.ok) throw new Error('authenticated USDA fixture did not load'); + session = composed.session; +}, 180000); + +describe('SHISO live acceptance — self-initialized real-catalogue investigation', () => { + it('initializes without Advanced Nutrition, selects defensible real USDA lines, and asks once', async () => { + const recipe = { + id: 'breakfast-live', + fileName: 'Breakfast Burritos.md', + filePath: 'Recipes/Breakfast Burritos.md', + rawMarkdown: '', + title: 'Breakfast Burritos', + tags: ['food/recipes'], + category: 'Breakfast', + cuisine: 'Mexican', + difficulty: 'Easy', + rating: 0, + servings: 4, + ingredients: LINES.map((original) => { + const parsed = parseIngredient(original); + return { + original, + name: parsed.ok ? parsed.parsed.query : original, + ...(parsed.ok && parsed.parsed.amount !== null ? { amount: parsed.parsed.amount } : {}), + ...(parsed.ok && parsed.parsed.raw_unit !== undefined ? { unit: parsed.parsed.raw_unit } : {}), + }; + }), + instructions: [{ text: 'Cook the filling and fill the tortillas.' }], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, + } as unknown as ObsidianRecipe; + const view = toShisoRecipeView(recipe); + if (view === null) throw new Error('recipe view failed'); + const controller = createShisoNutritionReviewController(recipe, session); + if (controller === null) throw new Error('review controller failed'); + let currentSnapshot: ReturnType = null; + const toolContext = { + session, + recipe: view, + get nutrition() { return currentSnapshot; }, + runAnalysis: () => { + const outcome = controller.analyze(); + currentSnapshot = controller.getSnapshot(); + return outcome; + }, + acceptNutritionContributions: () => true, + applyNutritionSourceSelection: (input: never) => controller.selectUsdaNutritionSource(input), + } as never; + + const outcome = await runShisoConversationTurn({ + network: { + request: async () => ({ status: 200, ok: true, data: {} }), + get: async () => ({ status: 200, ok: true, data: {} }), + post: async () => ({ status: 200, ok: true, data: { ok: true, kind: 'reply', text: 'unused', model_invocations_used: 1, tool_calls_used: 1 } }), + } as never, + context: { + recipe: { title: recipe.title, ingredientCount: 8, stepCount: 1, servings: 4 }, + nutrition: { available: false, summary: null, unresolvedCount: 8, needsAmountCount: 0, needsMatchCount: 8, unsavedWorkingReview: false }, + recipeKey: 'breakfast-live', + sessionIdentity: 'session-breakfast-live', + }, + toolContext, + }, initialShisoConversation(), "SHISO, investigate the unresolved nutrition for my Breakfast Burritos recipe. Use your available tools to identify the correct ingredients, find authenticated USDA sources, and resolve everything you can confidently resolve. Reject inappropriate food matches. Don't guess which ingredient alternatives I used. If you need information from me, ask one consolidated question covering all outstanding choices. Show me exactly what you've accomplished and what remains unresolved. Do not Apply or Save anything yet."); + + expect(outcome.ok).toBe(true); + expect(outcome.toolsUsed).toContain('run_nutrition_analysis'); + expect(outcome.toolsUsed).toContain('investigate_unresolved_ingredients'); + expect(outcome.toolsUsed).toContain('select_usda_nutrition_source'); + expect(outcome.toolsUsed).not.toContain('apply_nutrition_review'); + expect(outcome.toolsUsed).not.toContain('save_working_recipe'); + expect(outcome.message).toMatch(/initialized the unsaved nutrition review/i); + expect(outcome.message).toMatch(/Selected 2 authenticated source\(s\).*Butter, without salt.*Cheese, cheddar/i); + expect(outcome.message).toMatch(/consolidated choice set|which did you actually use|what measured amount/i); + expect(outcome.message).toMatch(/chopped vegetables/i); + expect(outcome.message).toMatch(/breakfast sausage/i); + expect(outcome.message).toMatch(/pinches salt/i); + expect(outcome.message).toMatch(/“8 burrito-size tortillas”.*what measured amount/i); + expect(outcome.message).not.toMatch(/Open Advanced Nutrition/i); + + const rows = controller.getSnapshot()!.rows; + const butter = rows.find((row) => row.original_text.includes('unsalted butter')); + const cheddar = rows.find((row) => row.original_text.includes('cheddar cheese')); + expect(butter).toMatchObject({ status: 'matched', selected_description: 'Butter, without salt', resolved_grams: 9.466666666666667 }); + expect(cheddar).toMatchObject({ status: 'matched', selected_description: 'Cheese, cheddar', resolved_grams: 210 }); + const tortillas = rows.find((row) => row.original_text.includes('burrito-size tortillas')); + expect(tortillas?.status).not.toBe('matched'); + expect(tortillas?.selected_fdc_id ?? null).toBeNull(); + expect(rows.filter((row) => row.status !== 'matched').length).toBeGreaterThan(0); + }, 180000); +}); diff --git a/tests/unit/shisoPhase1Culinary.test.ts b/tests/unit/shisoPhase1Culinary.test.ts index c3fd0d6..1390815 100644 --- a/tests/unit/shisoPhase1Culinary.test.ts +++ b/tests/unit/shisoPhase1Culinary.test.ts @@ -50,6 +50,11 @@ describe('SHISO Phase 1 culinary identity projection', () => { expect(cheese.equal_choice).toBe(false); expect(cheese.identities).toEqual(['cheddar cheese']); expect(cheese.alternatives.map((entry) => entry.label)).toEqual(['cheddar cheese', 'Monterey Jack']); + expect(cheese.fallback_identities).toEqual([]); + + const tortillas = projectCulinaryIngredient('8 burrito-size tortillas'); + expect(tortillas.identity).toBe('burrito tortillas'); + expect(tortillas.fallback_identities).toEqual(['tortillas']); const salt = projectCulinaryIngredient('2 pinches salt'); expect(salt.identity).toBe('salt');