From f543aad6458b16922bd694473fdb4f0c61620070 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 19:55:12 -0500 Subject: [PATCH] feat(shiso): introduce master culinary agent phase 1 --- server/shiso/conversationTurn.ts | 73 ++- src/application-ui/useShisoRecipeContext.ts | 49 +- src/application/shisoConversation.ts | 98 +++- src/application/shisoTools.ts | 418 ++++++++++++++++-- src/application/shisoVaultCapabilities.ts | 15 +- src/components/ShisoModal.tsx | 4 +- src/core/nutritionV2/phase4/index.ts | 1 + .../phase4/ingredientInvestigation.ts | 250 +++++++++++ src/core/shiso/protocol.ts | 11 +- .../shisoAgentFoundationAppOnDisk.test.tsx | 238 ++++++++++ .../advancedNutritionPhase4Isolation.test.ts | 1 + tests/unit/shisoNutritionCompletion.test.ts | 4 +- tests/unit/shisoPhase1Culinary.test.ts | 279 ++++++++++++ 13 files changed, 1370 insertions(+), 71 deletions(-) create mode 100644 src/core/nutritionV2/phase4/ingredientInvestigation.ts create mode 100644 tests/unit/shisoPhase1Culinary.test.ts diff --git a/server/shiso/conversationTurn.ts b/server/shiso/conversationTurn.ts index d78573a..c0cd663 100644 --- a/server/shiso/conversationTurn.ts +++ b/server/shiso/conversationTurn.ts @@ -77,10 +77,11 @@ const SYSTEM_PROMPT = [ " it, and — when the user asked you to FIX or APPLY — apply the supported corrections", " and recalculate. Do it all in this conversation.", "- When the user explicitly asks to RESOLVE, FINISH or COMPLETE the missing/unresolved", - " nutrition (for example 'resolve the last two ingredients', 'finish the nutrition',", - " 'estimate whatever is missing'), call complete_nutrition IMMEDIATELY. That single", - " capability runs the bounded source-first pipeline and prepares the review; do not", - " merely suggest searches or tell the user to do it manually.", + " nutrition and MORE THAN ONE line is unresolved, first call", + " investigate_unresolved_ingredients ONCE. Act on its select_source next_actions,", + " ask one consolidated question for genuine choices, then call complete_nutrition", + " for what remains. For one simple unresolved line, complete_nutrition directly.", + " Do not merely suggest searches or tell the user to do it manually.", "- When the user asks you to FIX, CORRECT, CHANGE or UPDATE the recipe or its nutrition", " ('fix this recipe', 'apply all supported fixes', 'change the chicken to turkey and", " update the nutrition'), their instruction IS the authorization. Execute the supported", @@ -95,6 +96,42 @@ const SYSTEM_PROMPT = [ " never about whether you are allowed to look something up or change what they asked", " you to change.", "", + "AGENT EXECUTION — UNDERSTAND, PLAN, ACT, OBSERVE, VERIFY", + "- For a multi-step goal, identify the requested outcome, inspect the current recipe/review,", + " choose the existing capabilities that can do the work, and execute a bounded plan.", + " Research is not completion. A search result is not a fix. Continue to the authorized", + " next action when the tool observation gives you one; stop only for a genuine user", + " decision, missing evidence, missing permission, or a failed operation.", + "- VERIFY every write from the tool observation. Never claim a source was selected,", + " nutrition applied, a recipe changed, or a save occurred unless the corresponding tool", + " returned success. If a step failed, say what failed and what remains.", + "- Do not repeat an identical read, search, inspection, or failed correction. Use the", + " evidence already returned. If a tool has a next_action, use it or explain why it is", + " blocked. Do not exhaust the reasoning budget on rediscovery.", + "- Full recipe: get_current_recipe is paged. Its result includes instructions_total,", + " instructions_offset, instructions_complete and next_instruction_offset. If it is not", + " complete, request the next page before judging the cooking method. Never say the", + " instructions were cut off without making that bounded pagination attempt.", + "- If get_vault_recipe reports instructions_truncated, select that recipe and use", + " get_current_recipe pagination before making a method judgement.", + "- Culinary investigation: for unresolved nutrition with several ingredients, call", + " investigate_unresolved_ingredients ONCE. It returns a culinary projection per line", + " (identity, quantity, preparation, alternatives, flexible mixture, measurement note),", + " compatible candidates, next_actions and pending_user_choices. Use the culinary", + " evidence, not raw token overlap.", + "- For a next_action with kind='select_source', call select_usda_nutrition_source with", + " its line_ref/fdc_id/portion_index. A successful search or inspection alone is not a", + " resolution. For equal authored alternatives, flexible mixtures, or vague measures,", + " ask the user; do not silently choose.", + "- If pending_user_choices is not empty, ask ONE consolidated question covering those", + " choices (use consolidated_question when present). Do not ask the same thing six times.", + " After the user answers, continue the unfinished task and reuse still-valid evidence;", + " revalidate if the recipe, review, Vault or catalogue identity changed.", + "- Chef analysis: read the complete instructions first, distinguish verified source", + " facts from your own culinary judgement, and give recommendations tied to the actual", + " steps/ingredients. You may propose/perform supported ingredient edits when authorized.", + " Never claim an instruction step was edited unless a tool actually changed it.", + "", "CONFIRMATIONS — A SHORT \"YES\" IS THE GO-AHEAD", "- If YOUR previous message asked whether to make a supported change (for example", " \"Shall I rename that ingredient to jalapeño?\" or \"Want me to correct the nutrition?\")", @@ -213,6 +250,10 @@ const SYSTEM_PROMPT = [ " not stall on a list of possibilities when the application can complete the work.", "- Proposals remain the right answer when the user should CHOOSE between options: they", " appear in the chat for review, and the user confirms them explicitly.", + "- When a culinary block is present, it overrides raw token-overlap candidates. Never", + " propose a different food head or a composite dish it marked incompatible. If", + " pending_user_choices is non-empty, ask the consolidated question rather than six", + " separate clarifications.", "", "WHAT YOU CANNOT DO", "- You cannot generate, edit, or retrieve recipe images. If asked for an image, say", @@ -242,7 +283,7 @@ const SYSTEM_PROMPT = [ "", "TOOLS", ...[ - "get_current_recipe read the recipe the user is looking at (each ingredient carries its line_ref handle)", + "get_current_recipe read the recipe the user is looking at; instructions are paged (line_ref handles included)", "get_vault_status read the authoritative active Vault recipe count and source", "search_vault_recipes search the active Vault by title, ingredient, category, or metadata", "get_vault_recipe retrieve a bounded recipe detail from the active Vault", @@ -254,7 +295,7 @@ const SYSTEM_PROMPT = [ "inspect_usda_food read one authenticated record and its portions", "select_usda_nutrition_source place one authenticated food + portion into the working review", "investigate_ingredient_amount diagnose ONE unresolved ingredient line", - "investigate_unresolved_ingredients diagnose EVERY unresolved line in one step (use this for 'all'/'investigate these')", + "investigate_unresolved_ingredients diagnose every unresolved line in one step; returns culinary identity, alternatives, next_actions and consolidated choices (use this for 'all'/'these')", "run_nutrition_analysis prepare source-backed and validated AI-estimated nutrition in the unsaved review", "complete_nutrition COMPLETE the missing nutrition: generic USDA first, then USDA Branded manufacturer evidence, then bounded external research, then validated AI estimates for what remains (unsaved review only)", "get_capability_status say what is missing and the one action that fixes it", @@ -266,8 +307,9 @@ const SYSTEM_PROMPT = [ "", "TOOL ARGUMENTS — EXACT JSON KEYS (never invent key names)", "- A tool call is {\"kind\":\"tool_request\",\"tool\":\"\",\"args\":{...}}.", - "- No arguments: get_current_recipe, get_nutrition_review, get_branded_evidence, investigate_unresolved_ingredients,", + "- No arguments: get_nutrition_review, get_branded_evidence, investigate_unresolved_ingredients,", " get_vault_status, load_usda_catalog, run_nutrition_analysis, complete_nutrition, get_capability_status, apply_nutrition_review, save_working_recipe.", + "- {\"tool\":\"get_current_recipe\",\"instruction_offset\":0,\"instruction_limit\":20} (use next_instruction_offset until complete)", "- {\"tool\":\"investigate_ingredient_amount\",\"line_ref\":\"\"}", "- {\"tool\":\"search_usda_foods\",\"query\":\"...\"}", "- {\"tool\":\"inspect_usda_food\",\"fdc_id\":123}", @@ -505,8 +547,21 @@ export function parseShisoDecision(raw: unknown): ShisoModelDecision | null { function readToolArgs(tool: ShisoToolName, raw: unknown): ShisoToolArgs | null { const rec = (raw === null || typeof raw !== "object" || Array.isArray(raw) ? {} : raw) as Record; switch (tool) { - case 'get_current_recipe': - return { tool }; + case 'get_current_recipe': { + const offsetRaw = rec['instruction_offset']; + const limitRaw = rec['instruction_limit']; + const instruction_offset = typeof offsetRaw === 'number' && Number.isFinite(offsetRaw) && offsetRaw >= 0 + ? Math.min(1000, Math.floor(offsetRaw)) + : undefined; + const instruction_limit = typeof limitRaw === 'number' && Number.isFinite(limitRaw) && limitRaw > 0 + ? Math.max(1, Math.min(SHISO_LIMITS.maxInstructionPage, Math.floor(limitRaw))) + : undefined; + return { + tool, + ...(instruction_offset !== undefined ? { instruction_offset } : {}), + ...(instruction_limit !== undefined ? { instruction_limit } : {}), + }; + } case 'get_vault_status': return { tool }; case 'search_vault_recipes': { diff --git a/src/application-ui/useShisoRecipeContext.ts b/src/application-ui/useShisoRecipeContext.ts index 41f471a..f63ea3d 100644 --- a/src/application-ui/useShisoRecipeContext.ts +++ b/src/application-ui/useShisoRecipeContext.ts @@ -21,7 +21,15 @@ import { parseIngredient } from '../core/nutritionV2/matching/parse'; export interface ShisoRecipeView { readonly title: string; + readonly description?: string; readonly servings: number | null; + readonly category?: string; + readonly cuisine?: string; + readonly difficulty?: string; + readonly tags?: readonly string[]; + readonly prepTime?: string; + readonly cookTime?: string; + readonly totalTime?: string; readonly ingredients: ReadonlyArray<{ readonly text: string; readonly name: string; @@ -29,18 +37,33 @@ export interface ShisoRecipeView { readonly amount?: number; /** Canonical authored unit, retained for nutrition actions. */ readonly unit?: string; + /** Authored preparation after the first comma, when present. */ + readonly preparation?: string; /** H-2 stable edit handle; null when the recipe cannot be adapted. */ readonly line_ref?: string | null; }>; - readonly instructions: ReadonlyArray<{ readonly text: string }>; + readonly instructions: ReadonlyArray<{ + readonly text: string; + /** Stable, non-secret step handle used by instruction reads. */ + readonly step_ref: string; + }>; } export interface ShisoRecipeLike { readonly title: string; + readonly description?: string; readonly servings?: number | string; + readonly category?: string; + readonly cuisine?: string; + readonly difficulty?: string; + readonly tags?: readonly string[]; + readonly prepTime?: string; + readonly cookTime?: string; + readonly totalTime?: string; readonly ingredients: ReadonlyArray<{ readonly name: string; readonly original?: string; + readonly note?: string; readonly quantity?: number; readonly amount?: number | null; readonly unit?: string; @@ -112,14 +135,36 @@ export function toShisoRecipeView(recipe: ShisoRecipeLike | null): ShisoRecipeVi name, ...(amount !== undefined ? { amount } : {}), ...(typeof unit === 'string' && unit.length > 0 ? { unit } : {}), + ...(typeof i.note === 'string' && i.note.trim().length > 0 ? { preparation: i.note.trim().slice(0, 240) } : {}), line_ref: typeof lineRefs[index] === 'string' ? lineRefs[index] : null, }; }); return { title: String(recipe.title ?? '').slice(0, 200), + ...(typeof recipe.description === 'string' && recipe.description.trim().length > 0 + ? { description: recipe.description.trim().slice(0, 1200) } + : {}), servings: parseServings(recipe.servings), + ...(typeof recipe.category === 'string' && recipe.category.trim().length > 0 + ? { category: recipe.category.trim().slice(0, 120) } + : {}), + ...(typeof recipe.cuisine === 'string' && recipe.cuisine.trim().length > 0 + ? { cuisine: recipe.cuisine.trim().slice(0, 120) } + : {}), + ...(typeof recipe.difficulty === 'string' && recipe.difficulty.trim().length > 0 + ? { difficulty: recipe.difficulty.trim().slice(0, 40) } + : {}), + ...(Array.isArray(recipe.tags) ? { tags: recipe.tags.slice(0, 30).map((tag) => String(tag).slice(0, 60)) } : {}), + ...(typeof recipe.prepTime === 'string' && recipe.prepTime.trim().length > 0 ? { prepTime: recipe.prepTime.trim().slice(0, 40) } : {}), + ...(typeof recipe.cookTime === 'string' && recipe.cookTime.trim().length > 0 ? { cookTime: recipe.cookTime.trim().slice(0, 40) } : {}), + ...(typeof recipe.totalTime === 'string' && recipe.totalTime.trim().length > 0 ? { totalTime: recipe.totalTime.trim().slice(0, 40) } : {}), ingredients, - instructions: rawInstructions.slice(0, 60).map((s) => ({ text: String(s.text ?? '').slice(0, 400) })), + // Instructions stay available for bounded retrieval. They are NEVER sent in + // the conversation context automatically; the read capability pages them. + instructions: rawInstructions.slice(0, 200).map((step, index) => ({ + text: String(step.text ?? '').slice(0, 4000), + step_ref: `step:${index}`, + })), }; } diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index cc3884e..4a2810f 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -214,6 +214,82 @@ function requestsVaultCount(message: string): boolean { ); } + +interface CulinaryProgress { + readonly tools: readonly string[]; + readonly pending: readonly Record[]; + readonly question: string | null; + readonly selected: number; + readonly selectedSources: readonly string[]; +} + +/** + * Deterministic identity-first progress for an explicitly broad "resolve the + * remaining nutrition" request. It asks the existing batch investigation what + * is genuinely selectable, promotes only candidates the application already + * authenticated, and leaves authored choices/mixtures/measurements to the user. + * It never invents a food, portion, gram, or nutrient. + */ +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: [] }; + } + let investigation: ShisoObservation; + try { + investigation = await executeShisoTool({ tool: 'investigate_unresolved_ingredients' }, toolContext, signal); + } catch { + return { tools: [], pending: [], question: null, selected: 0, selectedSources: [] }; + } + if (signal?.aborted || !investigation.ok) { + return { tools: [], pending: [], question: null, selected: 0, selectedSources: [] }; + } + const data = investigation.data; + const tools: string[] = ['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[] = []; + for (const action of actions.slice(0, 8)) { + if (action['kind'] !== 'select_source') continue; + const lineRef = action['line_ref']; + const fdcId = action['fdc_id']; + const portionIndex = action['portion_index']; + if (typeof lineRef !== 'string' || typeof fdcId !== 'number' || typeof portionIndex !== 'number') continue; + let selection: ShisoObservation; + try { + selection = await executeShisoTool({ + tool: 'select_usda_nutrition_source', + line_ref: lineRef, + fdc_id: fdcId, + portion_index: portionIndex, + }, toolContext, signal); + } catch { + continue; + } + tools.push('select_usda_nutrition_source'); + if (selection.ok) { + 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)` : ''}`); + // 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)); + } + } + const pending = Array.isArray(data['pending_user_choices']) + ? data['pending_user_choices'].filter((entry): entry is Record => + 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 }; +} + export interface ShisoConversationState { readonly messages: readonly ShisoConversationMessage[]; readonly proposals: readonly ShisoBoundProposal[]; @@ -531,6 +607,11 @@ export async function runShisoConversationTurn( !classifySaveIntent(trimmed).authorized ) { if (deps.signal?.aborted) return cancelled(working, toolsUsed); + 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[] }; + if (deps.signal?.aborted) return cancelled(working, toolsUsed); let result: ShisoObservation; try { result = await executeShisoTool({ tool: 'complete_nutrition' }, deps.toolContext, deps.signal); @@ -585,20 +666,27 @@ export async function runShisoConversationTurn( typeof nutrientCoverage === 'object' && !Array.isArray(nutrientCoverage) && typeof (nutrientCoverage as Record)['gap_lines_examined'] === 'number'; - const requiresAlternativeChoice = Array.isArray(data['alternative_scenarios']) && + const requiresAlternativeChoice = (Array.isArray(data['alternative_scenarios']) && data['alternative_scenarios'].some((scenario) => scenario !== null && typeof scenario === 'object' && !Array.isArray(scenario) && (scenario as Record)['definitive_choice_required'] === true - ); + )) || culinaryProgress.pending.length > 0; // `complete_nutrition` is deliberately honest about its own unsaved stage, // but that sentence must not survive into a final response after a later // Apply/Save transaction succeeds. The transaction outcome below is the // sole persistence claim in the delivered message. const calculatedSummary = summary.replace(/\s*Nothing was applied or saved\.\s*$/i, '').trim(); + const selectedProgress = culinaryProgress.selectedSources.length > 0 + ? `I selected ${culinaryProgress.selectedSources.slice(0, 4).join('; ')}${culinaryProgress.selectedSources.length > 4 ? `; and ${culinaryProgress.selectedSources.length - 4} more` : ''} before completing the review. ` + : culinaryProgress.selected > 0 + ? `I selected ${culinaryProgress.selected} authenticated source${culinaryProgress.selected === 1 ? '' : 's'} before completing the review. ` + : ''; let persistenceMessage = requiresAlternativeChoice - ? 'An equal ingredient alternative still needs your choice. Select the branch actually used before Apply or Save. Nothing was applied or saved.' - : 'Calculated only: the prepared contributions remain in the UNSAVED Advanced Nutrition review. Nothing was applied or saved.'; - const shortcutTools = ['complete_nutrition']; + ? `${selectedProgress}${culinaryProgress.question ?? 'I still need one or more ingredient choices.'} Nothing was applied or saved.` + : culinaryProgress.selected > 0 + ? `${selectedProgress}The prepared contributions remain in the UNSAVED Advanced Nutrition review. Nothing was applied or saved.` + : 'Calculated only: the prepared contributions remain in the UNSAVED Advanced Nutrition review. Nothing was applied or saved.'; + const shortcutTools = [...culinaryProgress.tools, 'complete_nutrition']; let shortcutState = working; if (!requiresAlternativeChoice && result.ok && deps.nutritionAuthority?.enabled === true && classifySaveIntent(trimmed).reason !== 'save_negated') { shortcutTools.push('apply_nutrition_review'); diff --git a/src/application/shisoTools.ts b/src/application/shisoTools.ts index 3c05dbf..f4dc478 100644 --- a/src/application/shisoTools.ts +++ b/src/application/shisoTools.ts @@ -41,6 +41,8 @@ import { runBatchInvestigation } from '../core/shiso/batchInvestigation'; import { adaptRecipe, analyzeRecipe, + candidateIdentityVerdict, + projectCulinaryIngredient, projectIngredientAlternatives, type AdvancedNutritionSession, } from '../core/nutritionV2/phase4'; @@ -97,7 +99,15 @@ export interface ShisoToolContext { readonly session: AdvancedNutritionSession | null; readonly recipe: { readonly title: string; + readonly description?: string; readonly servings: number | null; + readonly category?: string; + readonly cuisine?: string; + readonly difficulty?: string; + readonly tags?: readonly string[]; + readonly prepTime?: string; + readonly cookTime?: string; + readonly totalTime?: string; readonly ingredients: ReadonlyArray<{ readonly text: string; readonly name: string; @@ -107,7 +117,7 @@ export interface ShisoToolContext { /** H-2 stable handle for edits; null when the recipe cannot be adapted. */ readonly line_ref?: string | null; }>; - readonly instructions: ReadonlyArray<{ readonly text: string }>; + readonly instructions: ReadonlyArray<{ readonly text: string; readonly step_ref?: string }>; } | null; readonly nutrition: { readonly rows: ReadonlyArray; @@ -229,23 +239,58 @@ function fail( // --------------------------------------------------------------------------- -function getCurrentRecipe(ctx: ShisoToolContext): ShisoObservation { +function getCurrentRecipe( + ctx: ShisoToolContext, + instructionOffset = 0, + instructionLimit = 12, +): ShisoObservation { const recipe = ctx.recipe ?? ctx.vault?.getSelectedRecipe(); if (recipe === null || recipe === undefined) { return fail('get_current_recipe', 'no_active_recipe', 'No recipe is currently open.'); } - return ok('get_current_recipe', `${recipe.title} — ${recipe.ingredients.length} ingredients`, { + const totalSteps = recipe.instructions.length; + const offset = Math.max(0, Math.min(totalSteps, Math.floor(instructionOffset))); + const limit = Math.max(1, Math.min(SHISO_LIMITS.maxInstructionPage, Math.floor(instructionLimit))); + const page = recipe.instructions.slice(offset, offset + limit).map((step, index) => ({ + index: offset + index, + text: step.text.slice(0, SHISO_LIMITS.maxInstructionTextChars), + step_ref: typeof step.step_ref === 'string' ? step.step_ref : `step:${offset + index}`, + text_truncated: step.text.length > SHISO_LIMITS.maxInstructionTextChars, + })); + const returned = page.length; + const nextOffset = offset + returned; + const instructionsComplete = nextOffset >= totalSteps; + return ok('get_current_recipe', `${recipe.title} — ${recipe.ingredients.length} ingredients, ${totalSteps} step(s)`, { title: recipe.title, + ...(recipe.description !== undefined ? { description: recipe.description } : {}), servings: recipe.servings, - ingredients: recipe.ingredients.slice(0, 60).map((i) => ({ - text: i.text.slice(0, 200), - name: i.name.slice(0, 120), + ...(recipe.category !== undefined ? { category: recipe.category } : {}), + ...(recipe.cuisine !== undefined ? { cuisine: recipe.cuisine } : {}), + ...(recipe.difficulty !== undefined ? { difficulty: recipe.difficulty } : {}), + ...(recipe.tags !== undefined ? { tags: recipe.tags } : {}), + ...(recipe.prepTime !== undefined ? { prep_time: recipe.prepTime } : {}), + ...(recipe.cookTime !== undefined ? { cook_time: recipe.cookTime } : {}), + ...(recipe.totalTime !== undefined ? { total_time: recipe.totalTime } : {}), + ingredients: recipe.ingredients.slice(0, 80).map((i) => ({ + text: i.text.slice(0, 300), + name: i.name.slice(0, 160), + ...(i.amount !== undefined ? { amount: i.amount } : {}), + ...(i.unit !== undefined ? { unit: i.unit } : {}), + ...(i.preparation !== undefined ? { preparation: i.preparation } : {}), // H-2: the stable handle an edit is addressed by. It is INTERNAL plumbing // (like the review line_ref) and is revalidated against live recipe state // before any edit is applied; it is never shown to the user. line_ref: typeof i.line_ref === 'string' ? i.line_ref : null, })), - instructions: recipe.instructions.slice(0, 40).map((s) => ({ text: s.text.slice(0, 400) })), + ingredients_total: recipe.ingredients.length, + ingredients_truncated: recipe.ingredients.length > 80, + instructions: page, + instructions_total: totalSteps, + instructions_offset: offset, + instructions_returned: returned, + instructions_complete: instructionsComplete, + next_instruction_offset: instructionsComplete ? null : nextOffset, + instructions_page_truncated: !instructionsComplete, }); } @@ -632,40 +677,91 @@ function searchUsdaFoods(ctx: ShisoToolContext, query: string, limit: number): S return fail('search_usda_foods', 'no_nutrition_review', 'The USDA catalogue is not loaded.'); } - // Manual discovery uses the same identity projection as the Phase 4 analyzer. - // Raw token search over-authored wording (for example "toasted pecans") can - // miss a valid ordinary food, while broad overlap can surface an unrelated - // product that merely contains one word. The review authority separates food - // identity from preparation and exposes bounded same-family candidates. This - // remains discovery only; any later selection is re-authenticated by the - // calculation engine. const boundedLimit = Math.min(limit, SHISO_LIMITS.maxSearchResults); const numericId = /^\d+$/.test(query.trim()); - const direct = numericId ? ctx.session.searchFoods(query, boundedLimit) : null; - const review = numericId ? null : ctx.session.reviewIngredient({ name: query }); - const candidates = direct?.ok === true - ? direct.results - : review?.outcome === 'matched_exact' + if (numericId) { + const direct = ctx.session.searchFoods(query, boundedLimit); + if (!direct.ok || direct.results.length === 0) { + return fail('search_usda_foods', 'catalog_search_empty', 'No matching USDA record was found.'); + } + return ok('search_usda_foods', `${direct.results.length} matching USDA record(s)`, { + query, + identity: query, + total_matches: direct.total, + results: direct.results.map((result) => ({ + fdc_id: result.fdc_id, + description: result.description.slice(0, 160), + data_type: result.data_type, + match_class: result.match_class, + has_portion: result.has_portion, + portion_summary: result.portion_summary ?? null, + record_digest: result.record_digest, + })), + }); + } + + // The model may pass an authored phrase or a whole ingredient line. Project + // the culinary identity first so preparation/quantity words never become + // mandatory search tokens. The authenticated review still ranks; this layer + // only rejects a different food head or a composite dish before the model sees + // it. Exact authority results are never filtered. + const projection = projectCulinaryIngredient(query); + const results: Array> = []; + const seen = new Set(); + let rejected = 0; + for (const identity of projection.identities.slice(0, 4)) { + const review = ctx.session.reviewIngredient({ name: identity }); + const exact = review.outcome === 'matched_exact'; + const candidates = exact ? review.candidates.filter((candidate) => candidate.fdc_id === review.selected_fdc_id) - : review?.outcome === 'review_required' + : review.outcome === 'review_required' ? bestEffortDiscoveryCandidates(review) : []; - if (candidates.length === 0) { - return fail('search_usda_foods', 'catalog_search_empty', 'No matching USDA record was found.'); + for (const candidate of candidates) { + const verdict = exact ? { compatible: true, reason: null } : candidateIdentityVerdict(identity, candidate.description); + if (!verdict.compatible) { + rejected += 1; + continue; + } + if (seen.has(candidate.fdc_id)) continue; + seen.add(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) + : []; + results.push({ + fdc_id: candidate.fdc_id, + description: candidate.description.slice(0, 160), + data_type: candidate.data_type, + match_class: candidate.match_class, + has_portion: usable.length > 0, + portion_summary: usable[0]?.display_label ?? null, + record_digest: candidate.record_digest, + branch: identity, + authority_exact: exact, + compatible: true, + }); + } + } + if (results.length === 0) { + return fail( + 'search_usda_foods', + 'catalog_search_empty', + `No identity-compatible USDA record was found for “${projection.identity.slice(0, 100)}”. Do not substitute an unrelated record; ask for a more specific ingredient or use a measured amount.`, + ); } - const rows = candidates.slice(0, boundedLimit); - return ok('search_usda_foods', `${rows.length} matching USDA record(s)`, { + return ok('search_usda_foods', `${results.length} matching USDA record(s) — identity-compatible`, { query, - total_matches: direct?.ok === true ? direct.total : candidates.length, - results: rows.map((r) => ({ - fdc_id: r.fdc_id, - description: r.description.slice(0, 160), - data_type: r.data_type, - match_class: r.match_class, - has_portion: r.has_portion, - portion_summary: r.portion_summary ?? null, - record_digest: r.record_digest, - })), + identity: projection.identity, + identities: projection.identities, + alternatives: projection.alternatives, + flexible_mixture: projection.flexible_mixture, + equal_choice: projection.equal_choice, + choice_required: projection.choice_required, + measurement_note: projection.measurement_note, + total_matches: results.length, + rejected_matches: rejected, + results: results.slice(0, boundedLimit), }); } @@ -889,6 +985,184 @@ function investigateIngredientAmount(ctx: ShisoToolContext, lineRef: string): Sh * authenticated session; when it cannot cover every line it reports exactly how * many it examined and hands back a cursor so the user can continue. */ + +/** + * One culinary investigation for an unresolved line. Pure/read-only; it + * separates identity, quantity, authored alternatives, flexible composition, + * and measurable evidence before the model sees candidates. It never selects a + * source or returns a gram weight that is not an authenticated portion. + */ +function culinaryLineInvestigation( + ctx: ShisoToolContext, + row: LiveRowState, +): Record { + if (ctx.session === null) { + return { identity: null, candidates: [], next_action: { kind: 'no_source', reason: 'catalogue_unavailable' } }; + } + const authored = ctx.recipe?.ingredients.find((entry) => entry.line_ref === row.line_ref); + const original = authored?.text ?? row.original_text; + const projection = projectCulinaryIngredient(original); + const candidates: Array> = []; + 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 exact = review.outcome === 'matched_exact'; + const ranked = exact + ? review.candidates.filter((candidate) => candidate.fdc_id === review.selected_fdc_id) + : review.outcome === 'review_required' + ? bestEffortDiscoveryCandidates(review) + : []; + const branchCandidates: Array> = []; + for (const candidate of ranked.slice(0, 12)) { + const verdict = exact + ? { compatible: true, reason: null } + : candidateIdentityVerdict(identity, candidate.description); + if (!verdict.compatible) { + rejected += 1; + continue; + } + 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) + : []; + const record = { + branch: identity, + fdc_id: candidate.fdc_id, + description: candidate.description.slice(0, 160), + match_class: candidate.match_class, + record_digest: candidate.record_digest, + review_digest: review.review_digest ?? null, + authority_exact: exact, + usable_portions: usable.slice(0, 6).map((portion) => ({ + index: portion.index, + 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, + }; + const key = `${identity}:${candidate.fdc_id}`; + if (seen.has(key)) continue; + seen.add(key); + branchCandidates.push(record); + candidates.push(record); + } + branchReports.push({ + identity, + authority_exact: exact, + compatible_candidates: branchCandidates, + }); + } + + const primaryIdentity = projection.identities[0] ?? projection.identity; + const primaryCandidates = candidates.filter((candidate) => candidate['branch'] === primaryIdentity); + const selectable = primaryCandidates.find((candidate) => candidate['preferred_portion_index'] !== null); + let nextAction: Record; + let pendingChoice: Record | null = null; + if (projection.measurement_note !== null) { + nextAction = { + kind: 'needs_measurement', + line_ref: row.line_ref, + note: projection.measurement_note, + candidates, + }; + pendingChoice = { + kind: 'measurement', + line_ref: row.line_ref, + label: original.slice(0, 160), + note: projection.measurement_note, + }; + } else if (projection.flexible_mixture) { + nextAction = { + kind: 'composition_choice', + line_ref: row.line_ref, + options: projection.identities, + candidates, + note: 'This line is a flexible mixture. A precise composition and proportions require the user’s choice; do not present an invented mixture as verified.', + }; + pendingChoice = { + kind: 'composition', + line_ref: row.line_ref, + label: original.slice(0, 160), + options: projection.identities, + }; + } else if (projection.equal_choice) { + nextAction = { + kind: 'ingredient_choice', + line_ref: row.line_ref, + options: projection.identities, + candidates, + note: 'These are equal authored alternatives. Ask which one was actually used; do not choose one silently.', + }; + pendingChoice = { + kind: 'ingredient', + line_ref: row.line_ref, + label: original.slice(0, 160), + options: projection.identities, + }; + } else if (selectable !== undefined) { + nextAction = { + kind: 'select_source', + line_ref: row.line_ref, + fdc_id: selectable['fdc_id'], + portion_index: selectable['preferred_portion_index'], + gram_weight: selectable['preferred_grams'], + description: selectable['description'], + note: 'Select this authenticated source through select_usda_nutrition_source, then continue the task.', + }; + } else if (primaryCandidates.length > 0) { + nextAction = { + 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.', + }; + pendingChoice = { + kind: 'candidate', + line_ref: row.line_ref, + label: original.slice(0, 160), + options: primaryCandidates.slice(0, 3).map((candidate) => candidate['description']), + }; + } else { + nextAction = { + kind: 'no_compatible_source', + line_ref: row.line_ref, + note: 'No identity-compatible authenticated record was found. Do not substitute an unrelated food; ask for a more specific ingredient or a measured amount.', + }; + } + + return { + line_ref: row.line_ref, + label: original.slice(0, 160), + identity: projection.identity, + identities: projection.identities, + quantity: { + amount: projection.amount, + unit: projection.unit, + measurement_kind: projection.measurement_kind, + }, + preparation: authored?.preparation ?? null, + alternatives: projection.alternatives, + primary_index: projection.primary_index, + flexible_mixture: projection.flexible_mixture, + equal_choice: projection.equal_choice, + choice_required: projection.choice_required, + measurement_note: projection.measurement_note, + current_food: row.selected_description ?? null, + current_fdc_id: row.selected_fdc_id ?? null, + resolved_grams: row.resolved_grams ?? null, + status: row.status, + compatible_candidates: candidates.slice(0, 8), + rejected_candidates: rejected, + branches: branchReports, + next_action: nextAction, + pending_choice: pendingChoice, + }; +} + function investigateUnresolvedIngredients( ctx: ShisoToolContext, cursor: string | undefined, @@ -936,19 +1210,19 @@ function investigateUnresolvedIngredients( : `Investigated ${report.examined} of ${report.total_unresolved} unresolved ingredient(s) — ` + `${report.remaining} ingredient(s) are still to investigate.`; - return ok('investigate_unresolved_ingredients', summary, { - ai_estimated: acceptedAi.size, - source_backed_contributions: acceptedSource.size, - partial_known: coverage.partial_known, - source_backed: coverage.source_backed, - needs_attention: report.total_unresolved, - examined: report.examined, - total_unresolved: report.total_unresolved, - remaining: report.remaining, - complete: report.complete, - next_cursor: report.next_cursor, - classification_counts: report.counts, - lines: report.lines.map((l) => ({ + const lineReports = report.lines.map((l) => { + const row = findRow(ctx, l.line_ref); + // Culinary enrichment is additive. A minimal/injected surface that cannot + // support it must still receive the existing authoritative batch report. + let culinary: Record | null = null; + if (row !== undefined) { + try { + culinary = culinaryLineInvestigation(ctx, row); + } catch { + culinary = null; + } + } + return { // Internal handle, for binding and staleness only. NEVER printed to the // user — `label` is the ingredient's own text and is what may be shown. line_ref: l.line_ref, @@ -975,7 +1249,53 @@ function investigateUnresolvedIngredients( usable_portions: a.usable_portions, })), candidates: l.candidates, - })), + // The model should reason from this culinary projection, not from raw + // token-overlap candidates above. + culinary, + compatible_candidates: culinary?.['compatible_candidates'] ?? [], + next_action: culinary?.['next_action'] ?? null, + pending_choice: culinary?.['pending_choice'] ?? null, + }; + }); + const pendingChoices = lineReports + .map((line) => line.pending_choice) + .filter((choice): choice is Record => choice !== null && choice !== undefined); + const nextActions = lineReports + .map((line) => line.next_action) + .filter((action): action is Record => action !== null && action !== undefined); + const questionParts = pendingChoices.slice(0, 6).map((choice, index) => { + const label = typeof choice['label'] === 'string' ? choice['label'] : 'an ingredient'; + const options = Array.isArray(choice['options']) + ? choice['options'].filter((option): option is string => typeof option === 'string') + : []; + if (choice['kind'] === 'measurement') { + return `${index + 1}) For “${label}”, what measured amount was used?`; + } + if (choice['kind'] === 'composition') { + return `${index + 1}) For “${label}”, which vegetables and roughly what proportions were used${options.length > 0 ? ` (for example ${options.slice(0, 4).join(', ')})` : ''}?`; + } + return `${index + 1}) For “${label}”, which did you actually use${options.length > 0 ? `: ${options.join(' or ')}` : ''}?`; + }); + const consolidatedQuestion = questionParts.length === 0 + ? null + : `I can finish more of the nutrition after one consolidated choice set: ${questionParts.join(' ')}`; + + return ok('investigate_unresolved_ingredients', summary, { + ai_estimated: acceptedAi.size, + source_backed_contributions: acceptedSource.size, + partial_known: coverage.partial_known, + source_backed: coverage.source_backed, + needs_attention: report.total_unresolved, + examined: report.examined, + total_unresolved: report.total_unresolved, + remaining: report.remaining, + complete: report.complete, + next_cursor: report.next_cursor, + classification_counts: report.counts, + lines: lineReports, + next_actions: nextActions, + pending_user_choices: pendingChoices, + consolidated_question: consolidatedQuestion, continuation_hint: report.complete ? null : `${report.remaining} ingredient(s) remain. Ask me to continue and I will investigate the rest without repeating this work.`, @@ -2687,7 +3007,7 @@ export function executeShisoTool( try { switch (args.tool) { case 'get_current_recipe': - return getCurrentRecipe(ctx); + return getCurrentRecipe(ctx, args.instruction_offset ?? 0, args.instruction_limit ?? 12); case 'get_vault_status': return getVaultStatus(ctx); case 'search_vault_recipes': diff --git a/src/application/shisoVaultCapabilities.ts b/src/application/shisoVaultCapabilities.ts index 76a1163..10ced59 100644 --- a/src/application/shisoVaultCapabilities.ts +++ b/src/application/shisoVaultCapabilities.ts @@ -48,8 +48,13 @@ export interface ShisoVaultRecipeDetail extends ShisoVaultRecipeSummary { readonly preparation?: string; readonly line_ref?: string; }[]; - readonly instructions: readonly { readonly text: string }[]; + readonly instructions: readonly { readonly text: string; readonly step_ref: string }[]; + readonly instructions_total: number; + readonly instructions_truncated: boolean; readonly metadata: Readonly>; + readonly prepTime?: string; + readonly cookTime?: string; + readonly totalTime?: string; } export interface ShisoVaultSearchRequest { @@ -154,10 +159,16 @@ function detailOf(recipe: ObsidianRecipe, matchedFields: readonly string[] = []) ...(typeof ingredient.note === 'string' && ingredient.note.trim() ? { preparation: boundedText(ingredient.note, 160) } : {}), ...(typeof lineRefs[index] === 'string' ? { line_ref: lineRefs[index] } : {}), }))), - instructions: Object.freeze(recipe.instructions.slice(0, MAX_INSTRUCTIONS).map((step) => Object.freeze({ + instructions: Object.freeze(recipe.instructions.slice(0, MAX_INSTRUCTIONS).map((step, index) => Object.freeze({ text: boundedText(step.text, MAX_TEXT_CHARS), + step_ref: `step:${index}`, }))), + instructions_total: recipe.instructions.length, + instructions_truncated: recipe.instructions.length > MAX_INSTRUCTIONS || recipe.instructions.some((step) => step.text.length > MAX_TEXT_CHARS), metadata: recipeMetadata(recipe), + ...(boundedText(recipe.prepTime, 40) ? { prepTime: boundedText(recipe.prepTime, 40) } : {}), + ...(boundedText(recipe.cookTime, 40) ? { cookTime: boundedText(recipe.cookTime, 40) } : {}), + ...(boundedText(recipe.totalTime, 40) ? { totalTime: boundedText(recipe.totalTime, 40) } : {}), }); } diff --git a/src/components/ShisoModal.tsx b/src/components/ShisoModal.tsx index 2e10162..8050c65 100644 --- a/src/components/ShisoModal.tsx +++ b/src/components/ShisoModal.tsx @@ -1409,9 +1409,9 @@ export function ShisoModal({ {entry.role === 'assistant' ? : entry.text} {entry.tools.length > 0 && (
- {entry.tools.map((tool) => ( + {entry.tools.map((tool, toolIndex) => ( diff --git a/src/core/nutritionV2/phase4/index.ts b/src/core/nutritionV2/phase4/index.ts index 3552d23..b480799 100644 --- a/src/core/nutritionV2/phase4/index.ts +++ b/src/core/nutritionV2/phase4/index.ts @@ -35,4 +35,5 @@ export * from './aiPlanReconcile'; // reviewed projection through the boundary rather than reaching into the // isolated matching namespace directly. export { projectIngredientAlternatives } from '../matching/query'; +export * from './ingredientInvestigation'; export type { AiResolutionIssueKind } from '../aiResolution'; diff --git a/src/core/nutritionV2/phase4/ingredientInvestigation.ts b/src/core/nutritionV2/phase4/ingredientInvestigation.ts new file mode 100644 index 0000000..b03145f --- /dev/null +++ b/src/core/nutritionV2/phase4/ingredientInvestigation.ts @@ -0,0 +1,250 @@ +/** + * Phase 4 — culinary ingredient investigation. + * + * Pure, offline projection helpers used by SHISO to separate food identity from + * preparation, quantity, authored alternatives, and flexible mixtures BEFORE a + * catalogue search is shown to the model. This module owns no matching, + * nutrition, or persistence authority: + * + * - identity/projection reuse the canonical Phase 2 parser/projector through + * the Phase 4 boundary; + * - every candidate still comes from the authenticated session's own review; + * - compatibility is only a bounded relevance filter over that ranked set; + * - selection, portions, grams, and nutrients remain the existing Phase 4/5 + * authorities. + */ + +import { parseIngredient } from '../matching/parse'; +import { + projectIngredientAlternatives, + projectQueryText, +} from '../matching/query'; + +export type CulinaryMeasurementKind = + | 'mass' + | 'volume' + | 'count' + | 'unknown'; + +export interface CulinaryAlternative { + readonly label: string; + readonly primary: boolean; +} + +export interface CulinaryIngredientProjection { + readonly original: string; + /** The food identity used for catalogue discovery. */ + readonly identity: string; + /** Every identity branch that may be investigated (primary/equal/mixture). */ + readonly identities: readonly string[]; + readonly amount: number | null; + readonly unit: string | null; + readonly measurement_kind: CulinaryMeasurementKind; + readonly alternatives: readonly CulinaryAlternative[]; + readonly primary_index: number | null; + /** Authored flexible mixture such as `(such as red onion, pepper or broccoli)`. */ + readonly flexible_mixture: boolean; + /** True when the user must choose a branch/composition before a definitive result. */ + readonly choice_required: boolean; + /** True only for equal authored alternatives (`a or b`), not a primary + alternate. */ + readonly equal_choice: boolean; + /** Present when the authored measure cannot be converted without invention. */ + readonly measurement_note: string | null; +} + +export interface CandidateIdentityVerdict { + readonly compatible: boolean; + readonly reason: string | null; +} + +const COMPOSITE_DISH_TOKENS: ReadonlySet = new Set([ + 'biscuit', + 'burger', + 'burrito', + 'casserole', + 'curry', + 'entree', + 'meal', + 'mix', + 'nacho', + 'noodle', + 'pasta', + 'pizza', + 'platter', + 'prepared', + 'quesadilla', + 'restaurant', + 'salad', + 'sandwich', + 'soup', + 'stew', + 'taco', + 'wrap', +]); + +const VAGUE_MEASURES: ReadonlySet = new Set([ + 'pinch', + 'pinches', + 'dash', + 'dashes', + 'handful', + 'handfuls', + 'sprinkle', + 'sprinkles', + 'smidgen', + 'smidgens', +]); + +function normalTokens(value: string): string[] { + return value + .toLowerCase() + .replace(/[^a-z0-9]+/g, ' ') + .split(/\s+/) + .filter(Boolean) + .map((token) => token.length > 3 && token.endsWith('s') ? token.slice(0, -1) : token); +} + +function tokenSet(value: string): ReadonlySet { + return new Set(normalTokens(value)); +} + +function splitFlexibleMixture(text: string): readonly string[] { + const match = /\(\s*such as\s+([^)]+)\)/i.exec(text) ?? /\bsuch as\s+(.+)$/i.exec(text); + if (!match) return []; + return (match[1] ?? '') + .split(/\s*,\s*|\s+or\s+/i) + .map((part) => part.trim()) + .filter(Boolean) + .slice(0, 8); +} + +/** + * Projects one authored ingredient line into bounded culinary facts. It never + * chooses an alternative or invents a composition. + */ +export function projectCulinaryIngredient(text: string): CulinaryIngredientProjection { + const original = String(text).normalize('NFKC').trim().slice(0, 500); + const parsed = parseIngredient(original); + const identitySource = parsed.ok ? parsed.parsed.query : original; + const projected = projectQueryText(identitySource); + const identity = projected.food_identity.trim() || identitySource.trim(); + const alternativesProjection = projectIngredientAlternatives(original); + const flexibleOptions = splitFlexibleMixture(original); + const flexibleMixture = flexibleOptions.length > 1; + + let alternatives: CulinaryAlternative[]; + let primaryIndex: number | null = null; + let equalChoice = false; + if (flexibleMixture) { + alternatives = flexibleOptions.map((label) => ({ label, primary: false })); + equalChoice = false; + } else if (alternativesProjection !== null) { + primaryIndex = alternativesProjection.primary_index; + equalChoice = primaryIndex === null; + alternatives = alternativesProjection.alternatives.map((label, index) => ({ + label, + primary: primaryIndex === index, + })); + } else { + alternatives = []; + } + + const identities = flexibleMixture + ? flexibleOptions + : alternatives.length > 0 + ? equalChoice + ? alternatives.map((entry) => entry.label) + : [alternatives.find((entry) => entry.primary)?.label ?? identity] + : [identity]; + + const amount = parsed.ok ? parsed.parsed.amount : null; + const unit = parsed.ok ? parsed.parsed.raw_unit ?? null : null; + const measurementKind: CulinaryMeasurementKind = parsed.ok + ? parsed.parsed.measurement_kind === 'mass' + ? 'mass' + : parsed.parsed.measurement_kind === 'volume' + ? 'volume' + : parsed.parsed.measurement_kind === 'count' + ? 'count' + : 'unknown' + : 'unknown'; + const vagueMeasure = unit !== null && VAGUE_MEASURES.has(unit.toLowerCase()); + const measurementNote = vagueMeasure + ? `“${unit}” has no documented exact mass conversion. Use a measured amount or a clearly labeled estimate; do not treat a pinch as a verified weight.` + : !parsed.ok + ? 'The authored quantity could not be parsed safely.' + : null; + + return Object.freeze({ + original, + identity, + identities: Object.freeze(identities.filter((entry) => entry.length > 0)), + amount, + unit, + measurement_kind: measurementKind, + alternatives: Object.freeze(alternatives), + primary_index: primaryIndex, + flexible_mixture: flexibleMixture, + choice_required: flexibleMixture || equalChoice || vagueMeasure, + equal_choice: equalChoice, + measurement_note: measurementNote, + }); +} + +/** + * Bounded relevance check over the session's already-ranked candidates. + * + * It rejects a candidate whose primary head is a different food (sunflower seed + * butter for butter), and prepared/composite dishes when the query did not ask + * for one. It does not score, select, or authenticate anything. + */ +export function candidateIdentityVerdict( + identity: string, + description: string, +): CandidateIdentityVerdict { + const queryTokens = normalTokens(projectQueryText(identity).food_identity || identity); + const candidateTokens = normalTokens(description); + if (queryTokens.length === 0 || candidateTokens.length === 0) { + return { compatible: false, reason: 'empty_identity' }; + } + const querySet = new Set(queryTokens); + const candidateSet = new Set(candidateTokens); + const primaryToken = queryTokens[queryTokens.length - 1]!; + const headTokens = normalTokens(description.split(',')[0] ?? ''); + const headSet = new Set(headTokens); + const headMatchesPrimary = headSet.has(primaryToken); + + const composite = candidateTokens.find( + (token) => COMPOSITE_DISH_TOKENS.has(token) && !querySet.has(token), + ); + if (composite !== undefined) { + return { compatible: false, reason: `prepared_or_composite:${composite}` }; + } + + if (headMatchesPrimary) return { compatible: true, reason: null }; + // USDA descriptions frequently put the specific food after a broad category + // (`Nuts, pecans`; `Cheese, monterey jack`). A complete comma segment equal to + // the identity is much stronger evidence than mere token overlap. + const segments = description.split(',').map((segment) => normalTokens(segment)); + if (segments.some((segment) => + segment.length === queryTokens.length && + queryTokens.every((token) => segment.includes(token)) + )) { + return { compatible: true, reason: null }; + } + if (queryTokens.length === 1) { + return { compatible: false, reason: 'different_food_head' }; + } + if (queryTokens.every((token) => candidateSet.has(token))) { + return { compatible: true, reason: null }; + } + return { compatible: false, reason: 'missing_query_identity' }; +} + +/** True when a candidate description should be shown as the authored primary. */ +export function candidateMatchesAnyIdentity( + identities: readonly string[], + description: string, +): boolean { + return identities.some((identity) => candidateIdentityVerdict(identity, description).compatible); +} diff --git a/src/core/shiso/protocol.ts b/src/core/shiso/protocol.ts index d136dfe..5fd001f 100644 --- a/src/core/shiso/protocol.ts +++ b/src/core/shiso/protocol.ts @@ -115,6 +115,10 @@ export const SHISO_LIMITS = Object.freeze({ maxCorrectionLineRefs: 24, /** Bound for one authenticated SHISO-directed USDA source selection. */ maxSelectionLineRefChars: 240, + /** Instruction steps returned by one bounded recipe read. */ + maxInstructionPage: 20, + /** Characters retained for one instruction step. */ + maxInstructionTextChars: 4000, /** Request body ceiling in bytes. */ maxRequestBytes: 64 * 1024, }); @@ -225,7 +229,12 @@ export function isShisoToolName(value: unknown): value is ShisoToolName { /** Arguments are a closed per-tool union; unknown keys are refused whole. */ export type ShisoToolArgs = - | { readonly tool: 'get_current_recipe' } + | { + /** Bounded recipe read; instructions are paged rather than silently cut. */ + readonly tool: 'get_current_recipe'; + readonly instruction_offset?: number; + readonly instruction_limit?: number; + } | { readonly tool: 'get_vault_status' } | { /** Bounded read-only search over the active application's Vault snapshot. */ diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index c5c8aa7..5233055 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -148,6 +148,32 @@ function scriptedNetwork(script: readonly unknown[], otherResponses: Readonly>, +): { readonly network: NetworkAdapter; readonly turns: Array> } { + let index = 0; + const turns: Array> = []; + const response = async (path: string, body?: unknown) => { + if (path === '/api/shiso/turn') { + turns.push((body ?? {}) as Record); + const data = script[Math.min(index, script.length - 1)]; + index += 1; + return { status: 200, ok: true, data }; + } + return { status: 200, ok: true, data: otherResponses[path] ?? { ok: true, access: 'entitled', available: true } }; + }; + return { + network: { + post: response as NetworkAdapter['post'], + get: response as NetworkAdapter['get'], + request: async (request) => response(request.path, request.body) as never, + }, + turns, + }; +} + function OpenGlobal() { const { open } = useShiso(); useEffect(() => open('global'), [open]); @@ -421,4 +447,216 @@ describe('SHISO agent foundation real App save closure', () => { expect(serialized).toContain('"source_food_id":"169640"'); expect(serialized).toContain('"value":84.75'); }, 120000); + it('AUDIT Phase 1 Breakfast Burritos makes identity-first progress and asks one consolidated choice set', async () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-phase1-breakfast-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', 'Breakfast Burritos Phase 1.md'); + await mkdir(dirname(recipePath), { recursive: true }); + const markdown = [ + '---', 'title: "Breakfast Burritos Phase 1"', 'tags:', ' - food/recipes', + 'category: Breakfast', 'servings: 4', '---', '# Breakfast Burritos Phase 1', + '## 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 the tortillas.', '', + ].join('\n'); + await writeFile(recipePath, markdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable Phase 1 Breakfast Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + + const { manifest, records } = buildMatchingBundle([ + { fdcId: 31, dataType: 'sr_legacy', description: 'Butter, without salt', portions: [{ amount: 1, measure: 'tsp', gram_weight: 4.7, sequence: 1 }] }, + { fdcId: 32, dataType: 'sr_legacy', description: 'Cheese, cheddar', portions: [{ amount: 1, measure: 'cup', gram_weight: 105, sequence: 1 }] }, + { fdcId: 33, dataType: 'sr_legacy', description: 'Tortilla, flour', portions: [{ amount: 1, measure: 'tortilla', gram_weight: 45, sequence: 1 }] }, + { fdcId: 34, dataType: 'sr_legacy', description: 'Sausage, turkey, breakfast links, mild, raw', portions: [{ amount: 1, measure: 'link', gram_weight: 28, sequence: 1 }] }, + { fdcId: 35, dataType: 'sr_legacy', description: 'Salt, table', portions: [{ amount: 1, measure: 'tsp', gram_weight: 6, sequence: 1 }] }, + { fdcId: 36, dataType: 'sr_legacy', description: 'Raw vegetable, NFS', portions: [{ amount: 1, measure: 'cup', gram_weight: 120, sequence: 1 }] }, + { fdcId: 37, dataType: 'sr_legacy', description: 'Egg, whole, raw', portions: [{ amount: 1, measure: 'egg', gram_weight: 50, sequence: 1 }] }, + { fdcId: 38, dataType: 'sr_legacy', description: 'Milk, whole', portions: [{ amount: 1, measure: 'cup', gram_weight: 244, 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 Phase 1 Breakfast Vault"/); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: 'Breakfast Burritos Phase 1' })); + fireEvent.click(await screen.findByRole('button', { name: 'Generate Nutrition' })); + await screen.findByRole('dialog', { name: 'Advanced Nutrition' }); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(1)); + fireEvent.click(screen.getByRole('button', { name: 'Close 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, resolve the remaining nutrition for this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toMatch(/which did you actually use|what measured amount|consolidated choice/i), { timeout: 20000 }); + expect(document.body.textContent).toMatch(/I selected .*(?:authenticated source| g\))/i); + + expect(captured.turns).toHaveLength(0); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((entry) => entry.title === 'Breakfast Burritos Phase 1')?.codexNutrition).toBeUndefined(); + }, 120000); + + it('AUDIT Phase 1 reads complete paged instructions for a chef critique', async () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-phase1-chef-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', 'Chef Pagination Fixture.md'); + await mkdir(dirname(recipePath), { recursive: true }); + const steps = Array.from({ length: 25 }, (_, index) => `${index + 1}. Step ${index + 1}: ${index === 22 ? 'Final sear and rest before serving. ' + 'Detail '.repeat(120) : `Cook stage ${index + 1}.`}`).join('\n'); + const markdown = [ + '---', 'title: "Chef Pagination Fixture"', 'tags:', ' - food/recipes', + 'category: Dinner', 'servings: 2', '---', '# Chef Pagination Fixture', + '## Ingredients', '- 2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)', + '## Instructions', steps, '', + ].join('\n'); + await writeFile(recipePath, markdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable Phase 1 Chef Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + const bundle = buildMatchingBundle([{ fdcId: 1, dataType: 'sr_legacy', description: 'Raw vegetable, NFS', portions: [{ amount: 1, measure: 'cup', gram_weight: 120, sequence: 1 }] }]); + const created = createAdvancedNutritionSession(bundle.manifest, bundle.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: 'tool_request', tool: 'get_current_recipe', args: { tool: 'get_current_recipe', instruction_offset: 0, instruction_limit: 20 } }, + { ok: true, kind: 'tool_request', tool: 'get_current_recipe', args: { tool: 'get_current_recipe', instruction_offset: 20, instruction_limit: 20 } }, + { ok: true, kind: 'reply', text: 'Executive critique: the final sear and rest in Step 23 is the critical finish; do not rush it.', 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 Phase 1 Chef Vault"/); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: 'Chef Pagination Fixture' })); + fireEvent.click(await screen.findByTestId('recipe-shiso-entry')); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'Give me an executive-chef critique of this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Step 23 is the critical finish'), { timeout: 20000 }); + + const secondPageObservation = JSON.stringify(captured.turns[2]?.['observation'] ?? {}); + expect(secondPageObservation).toContain('Step 23'); + expect(secondPageObservation).toContain('Final sear and rest before serving'); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + 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 () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-phase1-continuation-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', 'Continuation Chicken Fixture.md'); + await mkdir(dirname(recipePath), { recursive: true }); + const markdown = [ + '---', 'title: "Continuation Chicken Fixture"', 'tags:', ' - food/recipes', + 'category: Dinner', 'servings: 2', '---', '# Continuation Chicken Fixture', + '## Ingredients', '- 2 cups shredded chicken breast or turkey breast', + '## Instructions', '1. Warm and serve.', '', + ].join('\n'); + await writeFile(recipePath, markdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable Phase 1 Continuation Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + + const { manifest, records } = buildMatchingBundle([ + { fdcId: 41, dataType: 'sr_legacy', description: 'Chicken, breast, meat only, cooked, roasted', portions: [{ amount: 1, measure: 'cup', gram_weight: 140, sequence: 1 }] }, + { fdcId: 42, dataType: 'sr_legacy', description: 'Turkey, breast, meat only, cooked, roasted', portions: [{ amount: 1, measure: 'cup', gram_weight: 140, 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: 'tool_request', tool: 'apply_nutrition_review', args: { tool: 'apply_nutrition_review' } }, + { 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: [] }, + ], { + '/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 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' })); + + 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(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.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Chicken breast was applied and saved to the Vault.'), { timeout: 20000 }); + + expect(captured.turns.length).toBeGreaterThan(0); + expect(JSON.stringify(captured.turns[0]?.['observation'] ?? {})).toContain('select_usda_nutrition_source'); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + const block = persisted.recipes.find((entry) => entry.title === 'Continuation Chicken Fixture')?.codexNutrition as any; + expect(block).toMatchObject({ status: 'complete', sources: ['usda_fdc'] }); + expect(block.ingredients).toHaveLength(1); + expect(block.ingredients[0]).toMatchObject({ + source_food_id: '41', + match_status: 'confirmed', + selection_origin: 'shiso_user_directed', + amount: { value: 280, unit: 'g' }, + }); + expect(JSON.stringify(block)).not.toContain('42'); + }, 120000); + }); diff --git a/tests/security/advancedNutritionPhase4Isolation.test.ts b/tests/security/advancedNutritionPhase4Isolation.test.ts index e8900a1..3650fb1 100644 --- a/tests/security/advancedNutritionPhase4Isolation.test.ts +++ b/tests/security/advancedNutritionPhase4Isolation.test.ts @@ -160,6 +160,7 @@ describe('phase 4 isolation — source purity', () => { 'householdPortion.ts', 'hydrate.ts', 'index.ts', + 'ingredientInvestigation.ts', 'liveRow.ts', 'materialize.ts', 'portion.ts', diff --git a/tests/unit/shisoNutritionCompletion.test.ts b/tests/unit/shisoNutritionCompletion.test.ts index c50fad1..d5e5ef6 100644 --- a/tests/unit/shisoNutritionCompletion.test.ts +++ b/tests/unit/shisoNutritionCompletion.test.ts @@ -670,7 +670,9 @@ describe('SINC-3 end-to-end conversational command', () => { }, }, initialShisoConversation(), message); expect(outcome.ok).toBe(true); - expect(outcome.toolsUsed).toEqual(['complete_nutrition']); + const identityFirst = /\b(?:remaining|unresolved)\b/i.test(message) && /\b(?:nutrition|foods?)\b/i.test(message); + expect(outcome.toolsUsed).toContain('complete_nutrition'); + if (identityFirst) expect(outcome.toolsUsed).toContain('investigate_unresolved_ingredients'); expect(fixture.ctx.runAnalysis).toHaveBeenCalledTimes(1); expect(fixture.accepted[0]).toHaveLength(2); }); diff --git a/tests/unit/shisoPhase1Culinary.test.ts b/tests/unit/shisoPhase1Culinary.test.ts new file mode 100644 index 0000000..c3fd0d6 --- /dev/null +++ b/tests/unit/shisoPhase1Culinary.test.ts @@ -0,0 +1,279 @@ +import { describe, expect, it } from 'vitest'; + +import { + candidateIdentityVerdict, + projectCulinaryIngredient, +} from '../../src/core/nutritionV2/phase4/ingredientInvestigation'; +import { executeShisoTool, type ShisoToolContext } from '../../src/application/shisoTools'; +import { createAdvancedNutritionSession } from '../../src/core/nutritionV2/phase4/session'; +import type { AdvancedNutritionSession } from '../../src/core/nutritionV2/phase4'; +import { buildMatchingBundle } from '../fixtures/usdaMatchingFixtures'; + +function toolContext(session: AdvancedNutritionSession): ShisoToolContext { + return { session, recipe: null, nutrition: null }; +} + +function sessionFixture() { + const { manifest, records } = buildMatchingBundle([ + { fdcId: 1, dataType: 'sr_legacy', description: 'Butter, without salt', portions: [{ amount: 1, measure: 'tsp', gram_weight: 4.7, sequence: 1 }] }, + { fdcId: 2, dataType: 'sr_legacy', description: 'Seeds, sunflower seed butter, without salt', portions: [{ amount: 1, measure: 'tbsp', gram_weight: 16, sequence: 1 }] }, + { fdcId: 3, dataType: 'sr_legacy', description: 'Cheese, monterey jack, solid', portions: [{ amount: 1, measure: 'cup', gram_weight: 113, sequence: 1 }] }, + { fdcId: 4, dataType: 'sr_legacy', description: 'Fish, mackerel, jack, canned, drained solids', portions: [{ amount: 1, measure: 'cup', gram_weight: 190, sequence: 1 }] }, + { fdcId: 5, dataType: 'sr_legacy', description: 'Raw vegetable, NFS', portions: [{ amount: 1, measure: 'cup', gram_weight: 120, sequence: 1 }] }, + { fdcId: 6, dataType: 'sr_legacy', description: 'Beef and noodles', portions: [{ amount: 1, measure: 'cup', gram_weight: 200, sequence: 1 }] }, + { fdcId: 7, dataType: 'sr_legacy', description: 'Sausage, turkey, breakfast links, mild, raw', portions: [{ amount: 1, measure: 'link', gram_weight: 28, sequence: 1 }] }, + { fdcId: 8, dataType: 'sr_legacy', description: 'Sausage, egg and cheese breakfast biscuit', portions: [{ amount: 1, measure: 'biscuit', gram_weight: 126, sequence: 1 }] }, + { fdcId: 9, dataType: 'sr_legacy', description: 'Nuts, pecans', portions: [{ amount: 1, measure: 'cup', gram_weight: 109, sequence: 1 }] }, + ]); + const created = createAdvancedNutritionSession(manifest, records); + if (!created.ok) throw new Error('fixture session failed'); + return created.session; +} + +describe('SHISO Phase 1 culinary identity projection', () => { + it('separates authored identity, quantity, alternatives and flexible mixtures', () => { + const vegetables = projectCulinaryIngredient('2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)'); + expect(vegetables.identity).toBe('vegetables'); + expect(vegetables.amount).toBe(2); + expect(vegetables.unit).toBe('cups'); + expect(vegetables.flexible_mixture).toBe(true); + expect(vegetables.choice_required).toBe(true); + expect(vegetables.identities).toEqual(expect.arrayContaining(['red onion', 'bell pepper', 'mushrooms', 'broccoli'])); + + const sausage = projectCulinaryIngredient('1 pound breakfast sausage or Italian sausage'); + expect(sausage.equal_choice).toBe(true); + expect(sausage.choice_required).toBe(true); + expect(sausage.identities).toEqual(['breakfast sausage', 'Italian sausage']); + + const cheese = projectCulinaryIngredient('2 cups shredded cheddar cheese (or Monterey Jack)'); + expect(cheese.primary_index).toBe(0); + expect(cheese.equal_choice).toBe(false); + expect(cheese.identities).toEqual(['cheddar cheese']); + expect(cheese.alternatives.map((entry) => entry.label)).toEqual(['cheddar cheese', 'Monterey Jack']); + + const salt = projectCulinaryIngredient('2 pinches salt'); + expect(salt.identity).toBe('salt'); + expect(salt.measurement_note).toMatch(/no documented exact mass conversion/i); + expect(salt.choice_required).toBe(true); + }); + + it('rejects different food heads and composite dishes without rejecting category-prefixed foods', () => { + expect(candidateIdentityVerdict('unsalted butter', 'Butter, without salt')).toMatchObject({ compatible: true }); + expect(candidateIdentityVerdict('unsalted butter', 'Seeds, sunflower seed butter, without salt')).toMatchObject({ compatible: false }); + expect(candidateIdentityVerdict('chopped vegetables', 'Beef and noodles')).toMatchObject({ compatible: false }); + expect(candidateIdentityVerdict('chopped vegetables', 'Vegetables as ingredient in curry')).toMatchObject({ compatible: false }); + expect(candidateIdentityVerdict('Monterey Jack', 'Cheese, monterey jack, solid')).toMatchObject({ compatible: true }); + expect(candidateIdentityVerdict('Monterey Jack', 'Fish, mackerel, jack, canned, drained solids')).toMatchObject({ compatible: false }); + expect(candidateIdentityVerdict('breakfast sausage', 'Sausage, turkey, breakfast links, mild, raw')).toMatchObject({ compatible: true }); + expect(candidateIdentityVerdict('breakfast sausage', 'Sausage, egg and cheese breakfast biscuit')).toMatchObject({ compatible: false }); + expect(candidateIdentityVerdict('pecans', 'Nuts, pecans')).toMatchObject({ compatible: true }); + }); + + it('filters USDA search results by culinary identity', async () => { + const session = sessionFixture(); + const ctx = toolContext(session); + + const butter = await executeShisoTool({ tool: 'search_usda_foods', query: 'unsalted butter', limit: 10 }, ctx); + expect(butter.ok).toBe(true); + if (butter.ok) { + const descriptions = (butter.data['results'] as Array>).map((entry) => String(entry['description'])); + expect(descriptions).toContain('Butter, without salt'); + expect(descriptions.some((description) => /sunflower/i.test(description))).toBe(false); + } + + const monterey = await executeShisoTool({ tool: 'search_usda_foods', query: 'Monterey Jack', limit: 10 }, ctx); + expect(monterey.ok).toBe(true); + if (monterey.ok) { + const descriptions = (monterey.data['results'] as Array>).map((entry) => String(entry['description'])); + expect(descriptions.some((description) => /monterey jack/i.test(description))).toBe(true); + expect(descriptions.some((description) => /mackerel/i.test(description))).toBe(false); + } + + const vegetables = await executeShisoTool({ tool: 'search_usda_foods', query: 'chopped vegetables', limit: 10 }, ctx); + expect(vegetables.ok).toBe(true); + if (vegetables.ok) { + const descriptions = (vegetables.data['results'] as Array>).map((entry) => String(entry['description'])); + expect(descriptions).toEqual(expect.arrayContaining(['Raw vegetable, NFS'])); + expect(descriptions.some((description) => /beef|noodle|curry/i.test(description))).toBe(false); + } + + const pecans = await executeShisoTool({ tool: 'search_usda_foods', query: 'toasted pecans', limit: 10 }, ctx); + expect(pecans.ok).toBe(true); + if (pecans.ok) { + const descriptions = (pecans.data['results'] as Array>).map((entry) => String(entry['description'])); + expect(descriptions).toEqual(expect.arrayContaining(['Nuts, pecans'])); + } + }); + + it('pages complete recipe instructions with explicit completeness metadata', async () => { + const instructions = Array.from({ length: 23 }, (_, index) => ({ text: `Step ${index + 1}`, step_ref: `step:${index}` })); + const ctx = { + session: null, + recipe: { title: 'Paged Recipe', servings: 4, ingredients: [], instructions }, + nutrition: null, + } as unknown as ShisoToolContext; + const first = await executeShisoTool({ tool: 'get_current_recipe', instruction_offset: 0, instruction_limit: 10 }, ctx); + expect(first.ok).toBe(true); + if (!first.ok) return; + expect(first.data['instructions_total']).toBe(23); + expect(first.data['instructions_offset']).toBe(0); + expect(first.data['instructions_returned']).toBe(10); + expect(first.data['instructions_complete']).toBe(false); + expect(first.data['next_instruction_offset']).toBe(10); + + const third = await executeShisoTool({ tool: 'get_current_recipe', instruction_offset: 20, instruction_limit: 10 }, ctx); + expect(third.ok).toBe(true); + if (!third.ok) return; + expect(third.data['instructions_returned']).toBe(3); + expect(third.data['instructions_complete']).toBe(true); + expect(third.data['next_instruction_offset']).toBeNull(); + }); +}); + +import { createShisoNutritionReviewController } from '../../src/application/shisoNutritionReview'; +import { toShisoRecipeView } from '../../src/application-ui/useShisoRecipeContext'; +import type { ObsidianRecipe } from '../../src/types'; + +describe('SHISO Phase 1 unresolved-line investigation', () => { + it('returns culinary choices, compatible candidates and actionable source selections', async () => { + const { manifest, records } = buildMatchingBundle([ + { fdcId: 11, dataType: 'sr_legacy', description: 'Butter, without salt', portions: [{ amount: 1, measure: 'tsp', gram_weight: 4.7, sequence: 1 }] }, + { fdcId: 12, dataType: 'sr_legacy', description: 'Cheese, cheddar', portions: [{ amount: 1, measure: 'cup', gram_weight: 105, sequence: 1 }] }, + { fdcId: 13, dataType: 'sr_legacy', description: 'Tortilla, flour', portions: [{ amount: 1, measure: 'tortilla', gram_weight: 45, sequence: 1 }] }, + { fdcId: 14, dataType: 'sr_legacy', description: 'Sausage, turkey, breakfast links, mild, raw', portions: [{ amount: 1, measure: 'link', gram_weight: 28, sequence: 1 }] }, + { fdcId: 15, dataType: 'sr_legacy', description: 'Salt, table', portions: [{ amount: 1, measure: 'tsp', gram_weight: 6, sequence: 1 }] }, + { fdcId: 16, dataType: 'sr_legacy', description: 'Raw vegetable, NFS', portions: [{ amount: 1, measure: 'cup', gram_weight: 120, sequence: 1 }] }, + { fdcId: 17, dataType: 'sr_legacy', description: 'Egg, whole, raw', portions: [{ amount: 1, measure: 'egg', gram_weight: 50, sequence: 1 }] }, + { fdcId: 18, dataType: 'sr_legacy', description: 'Milk, whole', portions: [{ amount: 1, measure: 'cup', gram_weight: 244, sequence: 1 }] }, + ]); + const created = createAdvancedNutritionSession(manifest, records); + if (!created.ok) throw new Error('fixture session failed'); + const recipe = { + id: 'breakfast-burritos-phase1', + 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: [ + { original: '2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)', name: 'chopped vegetables', amount: 2, unit: 'cups' }, + { original: '1 pound breakfast sausage or Italian sausage', name: 'breakfast sausage', amount: 1, unit: 'pound' }, + { original: '2 pinches salt', name: 'salt', amount: 2, unit: 'pinches' }, + { original: '2 teaspoons unsalted butter', name: 'unsalted butter', amount: 2, unit: 'teaspoons' }, + { original: '8 burrito-size tortillas', name: 'burrito-size tortillas', amount: 8 }, + { original: '2 cups shredded cheddar cheese (or Monterey Jack)', name: 'cheddar cheese', amount: 2, unit: 'cups' }, + { original: '8 large eggs', name: 'eggs', amount: 8 }, + { original: '1 cup milk', name: 'milk', amount: 1, unit: 'cup' }, + ], + instructions: [{ text: 'Cook the filling.' }, { text: 'Fill and roll 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, created.session); + if (controller === null) throw new Error('review controller failed'); + const snapshot = controller.getSnapshot(); + if (snapshot === null) throw new Error('review snapshot failed'); + const ctx = { + session: created.session, + recipe: view, + nutrition: snapshot, + } as unknown as ShisoToolContext; + const result = await executeShisoTool({ tool: 'investigate_unresolved_ingredients' }, ctx); + expect(result.ok).toBe(true); + if (!result.ok) return; + const lines = result.data['lines'] as Array>; + const cheese = lines.find((line) => String(line['label']).includes('cheddar cheese')); + expect(cheese).toBeDefined(); + const cheeseCulinary = cheese?.['culinary'] as Record; + expect(cheeseCulinary?.['identity']).toBe('cheddar cheese'); + expect(cheeseCulinary?.['next_action']).toMatchObject({ kind: 'select_source', fdc_id: 12 }); + const cheeseCandidates = cheeseCulinary?.['compatible_candidates'] as Array>; + expect(cheeseCandidates.some((candidate) => String(candidate['description']).includes('Cheese, cheddar'))).toBe(true); + + const vegetables = lines.find((line) => String(line['label']).includes('chopped vegetables')); + expect(vegetables?.['culinary']).toMatchObject({ flexible_mixture: true, choice_required: true }); + expect((vegetables?.['culinary'] as Record)?.['next_action']).toMatchObject({ kind: 'composition_choice' }); + + const sausage = lines.find((line) => String(line['label']).includes('breakfast sausage')); + expect(sausage?.['culinary']).toMatchObject({ equal_choice: true, choice_required: true }); + expect((sausage?.['culinary'] as Record)?.['next_action']).toMatchObject({ kind: 'ingredient_choice' }); + + const salt = lines.find((line) => String(line['label']).includes('pinches salt')); + expect((salt?.['culinary'] as Record)?.['next_action']).toMatchObject({ kind: 'needs_measurement' }); + + const pending = result.data['pending_user_choices'] as Array>; + expect(pending.map((entry) => entry['kind'])).toEqual(expect.arrayContaining(['composition', 'ingredient', 'measurement'])); + expect(String(result.data['consolidated_question'])).toMatch(/which|what measured/i); + }); +}); + +import { initialShisoConversation, runShisoConversationTurn } from '../../src/application/shisoConversation'; + +describe('SHISO Phase 1 identity-first completion', () => { + it('selects unambiguous sources and returns one consolidated choice set', async () => { + const { manifest, records } = buildMatchingBundle([ + { fdcId: 21, dataType: 'sr_legacy', description: 'Butter, without salt', portions: [{ amount: 1, measure: 'tsp', gram_weight: 4.7, sequence: 1 }] }, + { fdcId: 22, dataType: 'sr_legacy', description: 'Cheese, cheddar', portions: [{ amount: 1, measure: 'cup', gram_weight: 105, sequence: 1 }] }, + { fdcId: 23, dataType: 'sr_legacy', description: 'Tortilla, flour', portions: [{ amount: 1, measure: 'tortilla', gram_weight: 45, sequence: 1 }] }, + { fdcId: 24, dataType: 'sr_legacy', description: 'Salt, table', portions: [{ amount: 1, measure: 'tsp', gram_weight: 6, sequence: 1 }] }, + { fdcId: 25, 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 session failed'); + const recipe = { + id: 'identity-first', fileName: 'Identity First.md', filePath: 'Recipes/Identity First.md', rawMarkdown: '', + title: 'Identity First', tags: ['food/recipes'], category: 'Breakfast', cuisine: 'Test', difficulty: 'Easy', rating: 0, servings: 4, + ingredients: [ + { original: '2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)', name: 'chopped vegetables', amount: 2, unit: 'cups' }, + { original: '2 pinches salt', name: 'salt', amount: 2, unit: 'pinches' }, + { original: '2 teaspoons unsalted butter', name: 'unsalted butter', amount: 2, unit: 'teaspoons' }, + { original: '8 burrito-size tortillas', name: 'burrito-size tortillas', amount: 8 }, + { original: '2 cups shredded cheddar cheese (or Monterey Jack)', name: 'cheddar cheese', amount: 2, unit: 'cups' }, + ], + instructions: [{ text: 'Cook.' }, { text: 'Fill and roll.' }], callouts: [], dataviewFields: {}, wikilinks: [], frontmatter: {}, + } as unknown as ObsidianRecipe; + const view = toShisoRecipeView(recipe); + if (view === null) throw new Error('view'); + const controller = createShisoNutritionReviewController(recipe, created.session); + if (controller === null) throw new Error('controller'); + const snapshot = controller.getSnapshot(); + if (snapshot === null) throw new Error('snapshot'); + const ctx = { + session: created.session, + recipe: view, + nutrition: snapshot, + runAnalysis: () => controller.analyze(), + acceptNutritionContributions: () => true, + applyNutritionSourceSelection: (input: never) => controller.selectUsdaNutritionSource(input), + } as unknown as ShisoToolContext; + 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: recipe.ingredients.length, stepCount: recipe.instructions.length, servings: 4 }, + nutrition: { available: true, summary: 'unresolved', unresolvedCount: 5, needsAmountCount: 1, needsMatchCount: 4, unsavedWorkingReview: true }, + recipeKey: 'identity-first', + sessionIdentity: 'session-identity-first', + }, + toolContext: ctx, + }, initialShisoConversation(), 'SHISO, resolve the remaining nutrition for this recipe.'); + expect(outcome.ok).toBe(true); + expect(outcome.toolsUsed).toEqual(expect.arrayContaining(['investigate_unresolved_ingredients', 'select_usda_nutrition_source', 'complete_nutrition'])); + expect(outcome.message).toMatch(/choice|which|measured/i); + expect(outcome.message).toContain('Cheese, cheddar'); + expect(outcome.toolsUsed).not.toContain('apply_nutrition_review'); + expect(outcome.toolsUsed).not.toContain('save_working_recipe'); + }, 30000); +});