From d97ad7ede988f4d38ce96a6a95ae6fdef68ca6a9 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 17:30:47 -0500 Subject: [PATCH 1/4] fix(shiso): complete agent nutrition execution and Apply workflow --- server/shiso/conversationTurn.ts | 19 ++ src/App.tsx | 22 +++ src/application-ui/shisoEntryPoints.tsx | 73 ++++++- src/application-ui/useShisoRecipeContext.ts | 38 +++- src/application/shisoConversation.ts | 163 +++++++++++++++- src/application/shisoNutritionReview.ts | 79 +++++++- src/application/shisoTools.ts | 82 ++++++++ src/components/AdvancedNutritionCard.tsx | 122 +++++++++++- src/components/AdvancedNutritionModal.tsx | 2 + src/components/ShisoModal.tsx | 55 +++++- src/core/nutritionV2/calculation/calculate.ts | 13 +- src/core/nutritionV2/calculation/types.ts | 3 +- src/core/nutritionV2/phase4/hydrate.ts | 6 +- src/core/nutritionV2/phase4/liveRow.ts | 3 + src/core/nutritionV2/phase4/rows.ts | 1 + src/core/nutritionV2/phase4/types.ts | 6 + src/core/nutritionV2/phase5/authorize.ts | 13 +- src/core/nutritionV2/schema.ts | 2 + src/core/nutritionV2/validate.ts | 7 +- src/core/shiso/protocol.ts | 32 +++ .../shisoAgentFoundationAppOnDisk.test.tsx | 105 +++++++++- tests/unit/shisoAgentExecution.test.ts | 184 ++++++++++++++++++ tests/unit/shisoAgentExecutionUi.test.tsx | 113 +++++++++++ tests/unit/useShisoRecipeContext.test.tsx | 31 +++ 24 files changed, 1138 insertions(+), 36 deletions(-) create mode 100644 tests/unit/shisoAgentExecution.test.ts create mode 100644 tests/unit/shisoAgentExecutionUi.test.tsx create mode 100644 tests/unit/useShisoRecipeContext.test.tsx diff --git a/server/shiso/conversationTurn.ts b/server/shiso/conversationTurn.ts index 4d00174..d78573a 100644 --- a/server/shiso/conversationTurn.ts +++ b/server/shiso/conversationTurn.ts @@ -132,6 +132,12 @@ const SYSTEM_PROMPT = [ " when applied_count is 0, and never claim an ingredient was fixed unless it is in", " `applied`. Never invent authenticated matches or portions — the application decides what", " is supported and reports what is not.", + "- select_usda_nutrition_source: after search_usda_foods/inspect_usda_food identifies", + " an authenticated record and portion for an unresolved line, use this capability to", + " place that exact food and portion into the live review. Send the exact line_ref,", + " fdc_id and portion_index returned by tools; the application re-authenticates them", + " and calculates grams. This is a SHISO-directed working-review change, not a human", + " confirmation, and it is never a reason to invent a value or save without authorization.", "- apply_nutrition_review: apply the complete application-owned Phase 4 review through", " the same trusted Apply authority used by Advanced Nutrition. It changes only the", " UNSAVED working recipe; it never saves to the Vault. Treat its observation as the", @@ -246,6 +252,7 @@ const SYSTEM_PROMPT = [ "get_branded_evidence read accepted USDA Branded product evidence in the working review", "search_usda_foods search the authenticated pinned USDA catalogue", "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')", "run_nutrition_analysis prepare source-backed and validated AI-estimated nutrition in the unsaved review", @@ -264,6 +271,7 @@ const SYSTEM_PROMPT = [ "- {\"tool\":\"investigate_ingredient_amount\",\"line_ref\":\"\"}", "- {\"tool\":\"search_usda_foods\",\"query\":\"...\"}", "- {\"tool\":\"inspect_usda_food\",\"fdc_id\":123}", + "- {\"tool\":\"select_usda_nutrition_source\",\"line_ref\":\"\",\"fdc_id\":123,\"portion_index\":0}", "- {\"tool\":\"search_vault_recipes\",\"query\":\"chicken\",\"field\":\"ingredient\"}", "- {\"tool\":\"get_vault_recipe\",\"recipe_id\":\"\"}", "- {\"tool\":\"select_vault_recipe\",\"recipe_id\":\"\"}", @@ -439,6 +447,8 @@ function salvageToolArgs(tool: ShisoToolName): ShisoToolArgs { return { tool, query: '', limit: 1 }; case 'inspect_usda_food': return { tool, fdc_id: 0 }; + case 'select_usda_nutrition_source': + return { tool, line_ref: '', fdc_id: 0, portion_index: -1 }; case 'investigate_ingredient_amount': return { tool, line_ref: '' }; case 'investigate_unresolved_ingredients': @@ -550,6 +560,15 @@ function readToolArgs(tool: ShisoToolName, raw: unknown): ShisoToolArgs | null { if (fdcId <= 0) return null; return { tool, fdc_id: fdcId }; } + case 'select_usda_nutrition_source': { + const lineRef = rec['line_ref']; + const fdcId = rec['fdc_id']; + const portionIndex = rec['portion_index']; + if (typeof lineRef !== 'string' || lineRef.trim().length === 0 || lineRef.trim().length > SHISO_LIMITS.maxSelectionLineRefChars) return null; + if (typeof fdcId !== 'number' || !Number.isSafeInteger(fdcId) || fdcId <= 0) return null; + if (typeof portionIndex !== 'number' || !Number.isSafeInteger(portionIndex) || portionIndex < 0) return null; + return { tool, line_ref: lineRef.trim(), fdc_id: fdcId, portion_index: portionIndex }; + } case 'investigate_ingredient_amount': { const lineRef = rec['line_ref']; if (typeof lineRef !== 'string') return null; diff --git a/src/App.tsx b/src/App.tsx index e1c96ca..30b1bdd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -203,6 +203,7 @@ import { import type { ShisoAnalysisOutcome, ShisoIngredientEditArgs, + ShisoNutritionSourceSelectionOutcome, ShisoRecipeEditOutcome, ShisoRecipeSaveOutcome, } from './core/shiso/protocol'; @@ -3039,6 +3040,26 @@ export default function App({ : null; }, []); + const applyIndependentShisoNutritionSourceSelection = useCallback((input: { + readonly lineRef: string; + readonly fdcId: number; + readonly portionIndex: number; + }): ShisoNutritionSourceSelectionOutcome => { + const controller = shisoNutritionReviewRef.current; + const currentRecipe = shisoSelectedRecipeForReviewRef.current; + if (controller === null || currentRecipe === null || !sameCanonicalRecipeIdentity(controller.recipe, currentRecipe)) { + return { + ok: false, + line_ref: input.lineRef, + summary: 'No current SHISO nutrition review is available for that source selection.', + recalculation: 'absent', + working_unsaved: false, + code: 'no_active_review', + }; + } + return controller.selectUsdaNutritionSource(input); + }, []); + const acceptIndependentShisoNutrition = useCallback(( contributions: readonly import('./core/nutritionV2/aiContribution').AiNutrientContribution[], supplements?: readonly import('./core/nutritionV2/aiContribution').AiNutrientSupplement[], @@ -5552,6 +5573,7 @@ export default function App({ getIndependentNutritionSnapshot={getIndependentShisoNutritionSnapshot} acceptIndependentNutrition={acceptIndependentShisoNutrition} applyIndependentNutritionReview={applyIndependentShisoNutritionReview} + applyIndependentNutritionSourceSelection={applyIndependentShisoNutritionSourceSelection} nutritionRows={shiso.snapshot?.rows ?? []} nutritionAiContributions={shiso.snapshot?.aiContributions ?? []} nutritionReviewRows={shiso.snapshot?.reviewRows ?? []} diff --git a/src/application-ui/shisoEntryPoints.tsx b/src/application-ui/shisoEntryPoints.tsx index f487fcd..7d33d09 100644 --- a/src/application-ui/shisoEntryPoints.tsx +++ b/src/application-ui/shisoEntryPoints.tsx @@ -31,6 +31,7 @@ import type { ShisoBoundProposal, ShisoIngredientEditArgs, ShisoNutritionCorrectionsOutcome, + ShisoNutritionSourceSelectionOutcome, ShisoRecipeEditOutcome, ShisoRecipeSaveOutcome, } from '../core/shiso/protocol'; @@ -44,6 +45,21 @@ export interface ShisoNutritionAnalysisOutcome { readonly message: string; } +/** + * Result of an Apply through a nutrition-review owner. + * + * `not_eligible` is an ownership signal, not a successful Apply: the card owner + * has no current eligible review, so SHISO may use the independent review owner + * instead. Real Apply failures (stale review, authorization, persistence) do not + * carry this code and must not be retried against another review. + */ +export interface ShisoNutritionReviewApplyResult { + readonly ok: boolean; + readonly applied: boolean; + readonly message: string; + readonly code?: 'not_eligible'; +} + export type ShisoEntrySource = 'global' | 'recipe' | 'nutrition' | 'create'; export interface ShisoNutritionSnapshot { @@ -159,10 +175,10 @@ export interface ShisoEntryPoints { readonly canRunAnalysis: boolean; readonly registerAnalysisApplier: (applier: () => Promise) => () => void; /** Applies the currently displayed authoritative review through Phase 5. */ - readonly applyNutritionReview: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>; + readonly applyNutritionReview: () => Promise; readonly canApplyNutritionReview: boolean; readonly registerNutritionReviewApplier: ( - applier: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>, + applier: () => Promise, ) => () => void; // ------------------------------------------------------------------------- @@ -213,6 +229,15 @@ export interface ShisoEntryPoints { readonly registerCorrectionsApplier: ( applier: (lineRefs?: readonly string[]) => Promise, ) => () => void; + readonly applyNutritionSourceSelection: (input: { + readonly lineRef: string; + readonly fdcId: number; + readonly portionIndex: number; + }) => Promise; + readonly canApplyNutritionSourceSelection: boolean; + readonly registerNutritionSourceSelectionApplier: ( + applier: (input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise, + ) => () => void; readonly acceptAiNutrition: (contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean; readonly canAcceptAiNutrition: boolean; readonly registerAiNutritionApplier: (applier: (contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean) => () => void; @@ -272,6 +297,16 @@ const INERT: ShisoEntryPoints = { }), canApplyNutritionCorrections: false, registerCorrectionsApplier: () => () => {}, + applyNutritionSourceSelection: async () => ({ + ok: false, + line_ref: '', + summary: 'The nutrition review owner is not available.', + recalculation: 'absent', + working_unsaved: false, + code: 'no_active_review', + }), + canApplyNutritionSourceSelection: false, + registerNutritionSourceSelectionApplier: () => () => {}, acceptAiNutrition: () => false, canAcceptAiNutrition: false, registerAiNutritionApplier: () => () => {}, @@ -288,12 +323,15 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode const [snapshot, setSnapshot] = useState(null); const [applier, setApplier] = useState<((b: ShisoBoundProposal) => Promise) | null>(null); const [analysisApplier, setAnalysisApplier] = useState<(() => Promise) | null>(null); - const [nutritionReviewApplier, setNutritionReviewApplier] = useState<(() => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>) | null>(null); + const [nutritionReviewApplier, setNutritionReviewApplier] = useState<(() => Promise) | null>(null); const [nutritionAnalysisRunner, setNutritionAnalysisRunner] = useState<(() => Promise) | null>(null); const [recipeEditApplier, setRecipeEditApplier] = useState(null); const [correctionsApplier, setCorrectionsApplier] = useState< ((lineRefs?: readonly string[]) => Promise) | null >(null); + const [nutritionSourceSelectionApplier, setNutritionSourceSelectionApplier] = useState< + ((input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise) | null + >(null); const [aiNutritionApplier, setAiNutritionApplier] = useState<((contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean) | null>(null); const [workingRecipe, setWorkingRecipe] = useState(null); /** @@ -338,7 +376,7 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode setNutritionAnalysisRunner(() => next); return () => setNutritionAnalysisRunner((current) => current === next ? null : current); }, []); - const registerNutritionReviewApplier = useCallback((next: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>) => { + const registerNutritionReviewApplier = useCallback((next: () => Promise) => { setNutritionReviewApplier(() => next); return () => setNutritionReviewApplier((current) => current === next ? null : current); }, []); @@ -365,6 +403,13 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode }, [], ); + const registerNutritionSourceSelectionApplier = useCallback( + (next: (input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise) => { + setNutritionSourceSelectionApplier(() => next); + return () => setNutritionSourceSelectionApplier((current) => current === next ? null : current); + }, + [], + ); const registerAiNutritionApplier = useCallback((next: (contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean) => { setAiNutritionApplier(() => next); return () => setAiNutritionApplier(null); @@ -532,6 +577,22 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode }, [correctionsApplier], ); + const applyNutritionSourceSelection = useCallback( + async (input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => { + if (nutritionSourceSelectionApplier === null) { + return { + ok: false, + line_ref: input.lineRef, + summary: 'The nutrition review is not open for this recipe.', + recalculation: 'absent', + working_unsaved: false, + code: 'no_active_review', + } as ShisoNutritionSourceSelectionOutcome; + } + return nutritionSourceSelectionApplier(input); + }, + [nutritionSourceSelectionApplier], + ); const value = useMemo( () => ({ @@ -567,6 +628,9 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode applyNutritionCorrections, canApplyNutritionCorrections: correctionsApplier !== null, registerCorrectionsApplier, + applyNutritionSourceSelection, + canApplyNutritionSourceSelection: nutritionSourceSelectionApplier !== null, + registerNutritionSourceSelectionApplier, acceptAiNutrition, canAcceptAiNutrition: aiNutritionApplier !== null, registerAiNutritionApplier, @@ -581,6 +645,7 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode clearSaveAuthorizationEntry, discardWorkingRecipe, workingRecipe, publishWorkingRecipe, applyNutritionCorrections, correctionsApplier, registerCorrectionsApplier, + applyNutritionSourceSelection, nutritionSourceSelectionApplier, registerNutritionSourceSelectionApplier, acceptAiNutrition, aiNutritionApplier, registerAiNutritionApplier, ], ); diff --git a/src/application-ui/useShisoRecipeContext.ts b/src/application-ui/useShisoRecipeContext.ts index a7b0eb4..41f471a 100644 --- a/src/application-ui/useShisoRecipeContext.ts +++ b/src/application-ui/useShisoRecipeContext.ts @@ -17,6 +17,7 @@ import { useMemo } from 'react'; import { adaptRecipe } from '../core/nutritionV2/phase4'; +import { parseIngredient } from '../core/nutritionV2/matching/parse'; export interface ShisoRecipeView { readonly title: string; @@ -24,6 +25,10 @@ export interface ShisoRecipeView { readonly ingredients: ReadonlyArray<{ readonly text: string; readonly name: string; + /** Canonical authored quantity, retained for nutrition actions. */ + readonly amount?: number; + /** Canonical authored unit, retained for nutrition actions. */ + readonly unit?: string; /** H-2 stable edit handle; null when the recipe cannot be adapted. */ readonly line_ref?: string | null; }>; @@ -70,14 +75,43 @@ export function toShisoRecipeView(recipe: ShisoRecipeLike | null): ShisoRecipeVi const ingredients = rawIngredients.slice(0, 80).map((i, index) => { const name = typeof i.name === 'string' ? i.name.slice(0, 160) : ''; const authored = typeof i.original === 'string' ? i.original.trim() : ''; + const structuredAmount = + typeof i.amount === 'number' && Number.isFinite(i.amount) + ? i.amount + : typeof i.quantity === 'number' && Number.isFinite(i.quantity) + ? i.quantity + : undefined; + const parsedStructured = parseIngredient({ + ...(authored.length > 0 ? { original: authored } : {}), + ...(structuredAmount !== undefined ? { amount: structuredAmount } : {}), + ...(typeof i.unit === 'string' && i.unit.length > 0 ? { unit: i.unit } : {}), + ...(name.length > 0 ? { name } : {}), + }); + const parsedAuthored = authored.length > 0 ? parseIngredient(authored) : null; + const amount = structuredAmount ?? ( + parsedAuthored?.ok === true && parsedAuthored.parsed.amount !== null + ? parsedAuthored.parsed.amount + : parsedStructured.ok && parsedStructured.parsed.amount !== null + ? parsedStructured.parsed.amount + : undefined + ); + const unit = typeof i.unit === 'string' && i.unit.length > 0 + ? i.unit + : parsedAuthored?.ok === true + ? parsedAuthored.parsed.raw_unit + : parsedStructured.ok + ? parsedStructured.parsed.raw_unit + : i.unit; const parts: string[] = []; - if (typeof i.quantity === 'number' && Number.isFinite(i.quantity)) parts.push(String(i.quantity)); - if (typeof i.unit === 'string' && i.unit.length > 0) parts.push(i.unit); + if (amount !== undefined) parts.push(String(amount)); + if (typeof unit === 'string' && unit.length > 0) parts.push(unit); parts.push(name); const text = (authored.length > 0 ? authored : parts.join(' ').trim()).slice(0, 200); return { text, name, + ...(amount !== undefined ? { amount } : {}), + ...(typeof unit === 'string' && unit.length > 0 ? { unit } : {}), line_ref: typeof lineRefs[index] === 'string' ? lineRefs[index] : null, }; }); diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index a6bf382..cc3884e 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -43,6 +43,11 @@ import { buildAiSelectionRequestOptions } from './aiSelection'; import { executeShisoTool, type ShisoToolContext } from './shisoTools'; import { planDeterministicIngredientEdit } from '../core/shiso/deterministicEdit'; import { classifySaveIntent } from '../core/shiso/saveAuthorization'; +import { + projectIngredientAlternatives, + selectDeterministicVolumePortionIndex, +} from '../core/nutritionV2/phase4'; +import { parseIngredient } from '../core/nutritionV2/matching/parse'; /** How many verified findings survive across turns for continuation. */ const MAX_RETAINED_FINDINGS = 12; @@ -120,6 +125,87 @@ function requestsManualUsdaChoice(message: string): boolean { return /\b(?:use|choose|select)\b.{0,45}\bthis\s+(?:usda\s+)?(?:food|match|record)\b/i.test(message); } +function normalizedFoodTokens(text: string): ReadonlySet { + return new Set( + text + .toLowerCase() + .replace(/[^a-z0-9]+/g, ' ') + .split(/\s+/) + .filter(Boolean) + .map((token) => token.length > 3 && token.endsWith('s') ? token.slice(0, -1) : token), + ); +} + +function userNamedBranch(userMessage: string, branch: string): boolean { + const messageTokens = normalizedFoodTokens(userMessage); + return [...normalizedFoodTokens(branch)].every((token) => messageTokens.has(token)); +} + +/** + * Executes the one safe autonomous-selection step that the owner asked for in + * plain language ("pick the honey"). This is intentionally generic: it only + * operates on a currently unresolved authored alternative, derives the food + * and portion from the authenticated session, and re-enters the normal + * `select_usda_nutrition_source` tool. It never invents an FDC id or a weight. + */ +async function tryDeterministicNutritionSourceSelection( + toolContext: ShisoToolContext, + userMessage: string, + signal?: AbortSignal, +): Promise { + if (signal?.aborted || toolContext.session === null || toolContext.nutrition === null || toolContext.recipe === null) return null; + if (toolContext.applyNutritionSourceSelection === undefined) return null; + if (!/\b(?:pick|choose|select|use|go\s+with)\b/i.test(userMessage)) return null; + + for (const line of toolContext.recipe.ingredients) { + if (typeof line.line_ref !== 'string') continue; + const projection = projectIngredientAlternatives(line.text); + if (projection === null) continue; + const branch = projection.alternatives.find((candidate) => userNamedBranch(userMessage, candidate)); + if (branch === undefined) continue; + const parsed = parseIngredient({ + original: line.text, + name: branch, + ...(line.amount !== undefined ? { amount: line.amount } : {}), + ...(line.unit !== undefined ? { unit: line.unit } : {}), + }); + if (!parsed.ok || parsed.parsed.measurement_kind !== 'volume' || parsed.parsed.milliliters === undefined) continue; + + const search = toolContext.session.searchFoods(branch, 12); + if (!search.ok) continue; + const branchTokens = normalizedFoodTokens(branch); + for (const candidate of search.results) { + const candidateTokens = normalizedFoodTokens(candidate.description); + if (![...branchTokens].every((token) => candidateTokens.has(token))) continue; + const portionIndex = selectDeterministicVolumePortionIndex( + toolContext.session, + candidate.fdc_id, + parsed.parsed.milliliters, + parsed.parsed.raw_unit, + branch, + ); + if (portionIndex === undefined) continue; + const trustedContext: ShisoToolContext = { + ...toolContext, + isTrustedNutritionSourceSelection: (lineRef, description) => + (toolContext.isTrustedNutritionSourceSelection?.(lineRef, description) === true) || + (lineRef === line.line_ref && userNamedBranch(userMessage, description)), + }; + return executeShisoTool( + { + tool: 'select_usda_nutrition_source', + line_ref: line.line_ref, + fdc_id: candidate.fdc_id, + portion_index: portionIndex, + }, + trustedContext, + signal, + ); + } + } + return null; +} + function requestsVaultCount(message: string): boolean { const text = message.toLowerCase().replace(/[’']/g, ''); return ( @@ -332,6 +418,7 @@ export interface ShisoBlock { const USDA_DEPENDENT_TOOLS: ReadonlySet = new Set([ 'search_usda_foods', 'inspect_usda_food', + 'select_usda_nutrition_source', 'investigate_ingredient_amount', 'investigate_unresolved_ingredients', 'run_nutrition_analysis', @@ -562,13 +649,14 @@ export async function runShisoConversationTurn( }; } - // USDA choices remain an explicit action in the open Advanced Nutrition - // review. Explain the scoped control directly instead of sending a selection - // request through recipe-edit interpretation or silently choosing a record. - if (requestsManualUsdaChoice(trimmed)) { + // Compatibility fallback for isolated surfaces that do not expose the new + // authenticated selection port. The full App surface takes the normal model + // path and can execute select_usda_nutrition_source; a surface without that + // owner must still explain the existing manual control honestly. + if (requestsManualUsdaChoice(trimmed) && deps.toolContext.applyNutritionSourceSelection === undefined) { const message = deps.toolContext.nutrition === null - ? 'Open Advanced Nutrition for this recipe, then choose the intended USDA record from that ingredient row. I cannot apply a food choice from chat without the review selection control. Nothing was changed or saved.' - : 'In the open Advanced Nutrition review, use the “Use this match” control on the intended ingredient row. That explicit selection is bound to this recipe and its current USDA review. I will not choose or apply a USDA record from chat. Nothing was changed or saved.'; + ? 'Open Advanced Nutrition for this recipe, then choose the intended USDA record from that ingredient row. The nutrition owner is not mounted here. Nothing was changed or saved.' + : 'This nutrition surface does not expose the authenticated source-selection owner yet. Use the “Use this match” control in Advanced Nutrition. Nothing was changed or saved.'; return { ok: true, state: appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 }), @@ -584,6 +672,7 @@ export async function runShisoConversationTurn( if ( requestsNutritionInvestigation(trimmed) && deps.toolContext.nutrition !== null && + !requestsManualUsdaChoice(trimmed) && !classifySaveIntent(trimmed).authorized ) { if (deps.signal?.aborted) return cancelled(working, toolsUsed); @@ -656,6 +745,35 @@ export async function runShisoConversationTurn( working = recordFinding(working, { tool: next.tool, ok: next.ok, summary }); }; + // A plain-language branch choice is already a trusted current-user decision. + // Execute the authenticated source-selection capability before asking the + // model for its next step, so the model cannot burn the turn rediscovering a + // record/portion that the application can safely promote itself. + const deterministicSelection = await tryDeterministicNutritionSourceSelection( + deps.toolContext, + trimmed, + deps.signal, + ); + if (deterministicSelection !== null) { + if (deps.signal?.aborted) return cancelled(working, toolsUsed); + observation = deterministicSelection; + toolsUsed.push(deterministicSelection.tool); + toolCalls = 1; + if (deterministicSelection.ok) retain(deterministicSelection); + deps.onProgress?.({ + kind: 'tool', + step: toolCalls, + tool: deterministicSelection.tool, + ok: deterministicSelection.ok, + }); + // A mounted React review owner may commit its dispatch on the next event + // loop turn. The following model/tool step reads the same live owner, not a + // stale render snapshot. + if (deterministicSelection.ok) { + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } + /** * H-2S — REPEATED EQUIVALENT FAILURES ARE TERMINAL. * @@ -719,6 +837,28 @@ export async function runShisoConversationTurn( const EDITING_TOOLS: ReadonlySet = new Set([ 'apply_ingredient_edits', 'apply_nutrition_corrections', + 'select_usda_nutrition_source', + 'apply_nutrition_review', + 'save_working_recipe', + ]); + const NON_PROGRESS_REPEAT_TOOLS: ReadonlySet = new Set([ + 'get_vault_status', + 'search_vault_recipes', + 'get_vault_recipe', + 'select_vault_recipe', + 'load_usda_catalog', + 'get_current_recipe', + 'get_nutrition_review', + 'get_branded_evidence', + 'search_usda_foods', + 'inspect_usda_food', + 'investigate_ingredient_amount', + 'investigate_unresolved_ingredients', + 'get_capability_status', + 'select_usda_nutrition_source', + 'run_nutrition_analysis', + 'complete_nutrition', + 'apply_nutrition_corrections', 'apply_nutrition_review', 'save_working_recipe', ]); @@ -939,6 +1079,17 @@ export async function runShisoConversationTurn( toolsUsed, }; } + if (cached.ok && NON_PROGRESS_REPEAT_TOOLS.has(turn.tool)) { + return { + ok: true, + state: working, + message: deterministicReport( + `I already verified the same ${turn.tool} request in this message, so I stopped instead of repeating it.`, + ), + status: null, + toolsUsed, + }; + } const terminal = noteFailure(signature, cached); if (terminal !== null) return terminal; retain(cached); diff --git a/src/application/shisoNutritionReview.ts b/src/application/shisoNutritionReview.ts index 6f8e003..d450421 100644 --- a/src/application/shisoNutritionReview.ts +++ b/src/application/shisoNutritionReview.ts @@ -27,7 +27,9 @@ import { import { combineAiContributionsWithPreview, type AiNutrientContribution, type AiNutrientSupplement } from '../core/nutritionV2/aiContribution'; import { buildShisoNutrientCoverage, deriveNutritionCoverage, nutritionCoverageSummary } from '../core/shiso/nutritionCoverage'; import type { ShisoNutritionSnapshot } from '../application-ui/shisoEntryPoints'; -import type { ShisoAnalysisOutcome } from '../core/shiso/protocol'; +import type { ShisoAnalysisOutcome, ShisoNutritionSourceSelectionOutcome } from '../core/shiso/protocol'; +import { buildPortionChoice } from '../core/nutritionV2/phase4/portion'; +import { selectionFromMatchChoice } from '../core/nutritionV2/phase4/rows'; export interface ShisoNutritionReviewController { readonly recipe: ObsidianRecipe; @@ -37,6 +39,11 @@ export interface ShisoNutritionReviewController { contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[], ) => boolean; + readonly selectUsdaNutritionSource: (input: { + readonly lineRef: string; + readonly fdcId: number; + readonly portionIndex: number; + }) => ShisoNutritionSourceSelectionOutcome; readonly getState: () => Phase4State; readonly getSnapshot: () => ShisoNutritionSnapshot | null; } @@ -196,6 +203,76 @@ export function createShisoNutritionReviewController( state = next; return recalculate(); }, + selectUsdaNutritionSource: ({ lineRef, fdcId, portionIndex }) => { + const row = state.rows.find((candidate) => candidate.line_ref === lineRef); + const entry = adapted.find((candidate) => candidate.line_ref === lineRef); + const fail = (code: string, summary: string): ShisoNutritionSourceSelectionOutcome => ({ + ok: false, + line_ref: lineRef, + summary, + recalculation: 'absent', + working_unsaved: state.status === 'preview_stale' || state.status === 'preview_current', + code, + }); + if (!row || !entry) return fail('stale_recipe', 'The ingredient line is no longer part of the current nutrition review.'); + if (!Number.isSafeInteger(fdcId) || fdcId <= 0 || !Number.isSafeInteger(portionIndex) || portionIndex < 0) { + return fail('invalid_request', 'The USDA food or portion selection is invalid.'); + } + const exact = session.searchFoods(String(fdcId), 5); + const hit = exact.ok ? exact.results.find((result) => result.fdc_id === fdcId && result.exact_fdc_id) : undefined; + if (!hit) return fail('invalid_selection', 'That USDA record is not available in the authenticated catalog.'); + const match = Object.freeze({ + kind: 'manual' as const, + fdc_id: fdcId, + review_digest: row.review_digest ?? '', + record_digest: hit.record_digest, + catalog_digest: session.metadata().catalog_digest, + selectionOrigin: 'shiso_user_directed' as const, + description: hit.description, + }); + const selection = selectionFromMatchChoice(match, lineRef); + const portion = buildPortionChoice(session, { + lineRef, + ingredient: entry.ingredient, + review: row.review, + selection, + fdcId, + portionIndex, + }); + if (!portion.ok) return fail('invalid_selection', 'That USDA portion could not be authenticated for this ingredient.'); + let next = phase4Reducer(state, { type: 'select_match', lineRef, choice: match }); + next = phase4Reducer(next, { type: 'select_portion', lineRef, choice: portion.choice }); + const calculated = session.calculate(buildCalculationRequest(adapted, next)); + if (!calculated.ok) return fail('invalid_selection', 'The authenticated nutrition review rejected that source selection.'); + const evidence = calculated.preview.ingredients.find((candidate) => candidate.line_ref === lineRef); + if (!evidence || evidence.fdc_id !== fdcId || evidence.resolved_grams === undefined) { + return fail('invalid_selection', 'The selected USDA source did not produce a verified ingredient amount.'); + } + next = phase4Reducer(next, { + type: 'apply_analysis', + matches: next.matches, + portions: next.portions, + countPortions: next.countPortions, + householdPortions: next.householdPortions, + preview: calculated.preview, + }); + state = next; + const portionResult = session.reviewPortions(fdcId); + const portionCandidate = portionResult.ok + ? portionResult.review.candidates.find((candidate) => candidate.index === portionIndex) + : undefined; + return { + ok: true, + line_ref: lineRef, + fdc_id: fdcId, + description: hit.description, + resolved_grams: evidence.resolved_grams, + ...(portionCandidate ? { portion: portionCandidate.display_label } : {}), + summary: `Verified ${hit.description} for ${lineRef}: ${portionCandidate?.display_label ?? 'authenticated USDA portion'} → ${evidence.resolved_grams} g. The working nutrition review was recalculated; nothing was saved.`, + recalculation: calculated.preview.status === 'complete' ? 'complete' : 'partial', + working_unsaved: true, + }; + }, getState: () => state, getSnapshot, }; diff --git a/src/application/shisoTools.ts b/src/application/shisoTools.ts index 20dc952..3c05dbf 100644 --- a/src/application/shisoTools.ts +++ b/src/application/shisoTools.ts @@ -28,7 +28,9 @@ import { SHISO_LIMITS, type ShisoAnalysisOutcome, type ShisoNutritionCorrectionsOutcome, + type ShisoNutritionSourceSelectionOutcome, type ShisoObservation, + type ShisoObservationFailureCode, type ShisoRecipeEditOutcome, type ShisoRecipeSaveOutcome, type ShisoToolArgs, @@ -109,6 +111,8 @@ export interface ShisoToolContext { } | null; readonly nutrition: { readonly rows: ReadonlyArray; + /** The current Phase 4 review rows, including authenticated review digests. */ + readonly reviewRows?: ReadonlyArray; readonly aiContributions?: ReadonlyArray; readonly summary: string | null; readonly unsaved: boolean; @@ -182,6 +186,10 @@ export interface ShisoToolContext { readonly applyNutritionCorrections?: | ((lineRefs: readonly string[] | undefined) => Promise) | undefined; + /** Promotes one authenticated USDA food + portion through the Phase 4 owner. */ + readonly applyNutritionSourceSelection?: + | ((input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise) + | undefined; /** F3. Applies the application-owned SHISO nutrition review to the unsaved recipe. */ readonly applyNutritionReview?: (() => Promise<{ readonly ok: boolean; @@ -195,6 +203,12 @@ export interface ShisoToolContext { * model is allowed to call this. */ readonly saveWorkingRecipe?: (() => Promise) | undefined; + /** + * Trusted current-user directive for an equal authored alternative. The + * model cannot set this; the conversation surface derives it from the user + * message and the authenticated selected record label. + */ + readonly isTrustedNutritionSourceSelection?: ((lineRef: string, description: string) => boolean) | undefined; } function ok( @@ -2430,6 +2444,72 @@ async function applyNutritionCorrections( }); } +/** + * Promotes one already-investigated USDA record and authenticated portion into + * the live Phase 4 review. This is deliberately separate from the batch + * correction pass: a source selection is a bounded identity decision, while + * correction discovery remains deterministic and conservative. + */ +async function selectUsdaNutritionSource( + ctx: ShisoToolContext, + lineRef: string, + fdcId: number, + portionIndex: number, +): Promise { + const failSelection = (code: ShisoObservationFailureCode, message: string): ShisoObservation => + fail('select_usda_nutrition_source', code, message); + if (!ctx.session || !ctx.recipe || !ctx.nutrition || ctx.applyNutritionSourceSelection === undefined) { + return failSelection('no_nutrition_review', 'The authenticated nutrition review is not available for source selection.'); + } + if (typeof lineRef !== 'string' || lineRef.length === 0 || lineRef.length > SHISO_LIMITS.maxSelectionLineRefChars) { + return failSelection('invalid_request', 'That ingredient line reference is invalid.'); + } + if (!Number.isSafeInteger(fdcId) || fdcId <= 0 || !Number.isSafeInteger(portionIndex) || portionIndex < 0) { + return failSelection('invalid_request', 'The USDA food or portion selection is invalid.'); + } + const row = ctx.nutrition.reviewRows?.find((candidate) => candidate.line_ref === lineRef); + const ingredient = ctx.recipe.ingredients.find((candidate) => candidate.line_ref === lineRef); + if (!row || !ingredient) { + return failSelection('stale_recipe', 'That ingredient line is not part of the current authenticated nutrition review.'); + } + + // Re-authenticate the record and portion here before the owner is asked to + // mutate state. The owner repeats the same checks, so this cannot become a + // trust shortcut if the review changes between these two steps. + const exact = ctx.session.searchFoods(String(fdcId), 5); + if (!exact.ok || !exact.results.some((result) => result.fdc_id === fdcId && result.exact_fdc_id)) { + return failSelection('invalid_selection', 'That USDA record is not present in the authenticated catalog.'); + } + const portionReview = ctx.session.reviewPortions(fdcId); + if (!portionReview.ok || !portionReview.review.candidates.some((candidate) => candidate.index === portionIndex && candidate.kind !== 'unusable' && candidate.effective_amount !== null && candidate.gram_weight > 0)) { + return failSelection('invalid_selection', 'That USDA portion is not available for the authenticated food record.'); + } + + // Equal authored alternatives remain a hard boundary unless the trusted + // current user message explicitly names the selected branch. A model cannot + // manufacture that authorization through tool arguments. + const alternatives = projectIngredientAlternatives(ingredient.text); + const hit = exact.results.find((result) => result.fdc_id === fdcId && result.exact_fdc_id); + if (alternatives?.primary_index === null && + (hit === undefined || ctx.isTrustedNutritionSourceSelection?.(lineRef, hit.description) !== true)) { + return failSelection('explicit_choice_required', 'This ingredient has equal alternatives. Tell me which food was actually used before I select a definitive source.'); + } + + const outcome = await ctx.applyNutritionSourceSelection({ lineRef, fdcId, portionIndex }); + if (!outcome.ok) { + return failSelection('selection_rejected', outcome.summary); + } + return ok('select_usda_nutrition_source', outcome.summary, { + line_ref: outcome.line_ref, + fdc_id: outcome.fdc_id ?? fdcId, + ...(outcome.description ? { description: outcome.description } : {}), + ...(outcome.portion ? { portion: outcome.portion } : {}), + ...(outcome.resolved_grams !== undefined ? { resolved_grams: outcome.resolved_grams } : {}), + recalculation: outcome.recalculation, + working_unsaved: outcome.working_unsaved, + }); +} + /** * F3. Applies the complete general-chat nutrition review through the shell's * existing Phase 5B owner. The capability never persists a Vault write. @@ -2626,6 +2706,8 @@ export function executeShisoTool( return searchUsdaFoods(ctx, args.query, args.limit ?? SHISO_LIMITS.maxSearchResults); case 'inspect_usda_food': return inspectUsdaFood(ctx, args.fdc_id); + case 'select_usda_nutrition_source': + return selectUsdaNutritionSource(ctx, args.line_ref, args.fdc_id, args.portion_index); case 'investigate_ingredient_amount': return investigateIngredientAmount(ctx, args.line_ref); case 'investigate_unresolved_ingredients': diff --git a/src/components/AdvancedNutritionCard.tsx b/src/components/AdvancedNutritionCard.tsx index 343cddc..f7e5fb0 100644 --- a/src/components/AdvancedNutritionCard.tsx +++ b/src/components/AdvancedNutritionCard.tsx @@ -16,6 +16,7 @@ import { basisLabel, buildCalculationRequest, buildReviewRows, + buildPortionChoice, coverageSummary, deriveDisplayNutrients, deriveEnergyDisplay, @@ -83,8 +84,10 @@ import { } from '../core/nutritionV2/brandedFoods'; import { MAX_RESEARCH_TARGETS, type ResearchTarget } from '../core/nutritionV2/aiResearch'; import type { AiEstimateSelectionEvidence } from '../core/nutritionV2/phase4/aiEstimateSelection'; -import { useShiso } from '../application-ui/shisoEntryPoints'; +import { useShiso, type ShisoNutritionReviewApplyResult } from '../application-ui/shisoEntryPoints'; import type { ShisoAnalysisOutcome, ShisoNutritionCorrectionsOutcome } from '../core/shiso/protocol'; +import type { ShisoNutritionSourceSelectionOutcome } from '../core/shiso/protocol'; +import { selectionFromMatchChoice } from '../core/nutritionV2/phase4/rows'; import { buildSupportedNutritionCorrections } from '../core/shiso/nutritionCorrections'; import { deriveNutritionCoverage, nutritionCoverageSummary } from '../core/shiso/nutritionCoverage'; import { @@ -1340,25 +1343,32 @@ onReviewRecipeContextWithAi, state, }; const canRegisterNutritionReviewApplier = - Boolean(onApplyAdvancedNutrition) && Boolean(session) && adaptation.ok && applyEligibility === true && applyMode !== null; + Boolean(onApplyAdvancedNutrition) && Boolean(session) && adaptation.ok && applyMode !== null; useEffect(() => { if (!canRegisterNutritionReviewApplier) { return undefined; } - return shisoRegisterNutritionReviewApplier(async () => { + return shisoRegisterNutritionReviewApplier(async (): Promise => { const current = shisoNutritionReviewApplyRef.current; const { onApplyAdvancedNutrition: apply, session: currentSession, adaptationOk, - applyEligibility: eligible, applyMode: mode, aiReviews: currentAiReviews, recipe: currentRecipe, state: currentState, } = current; - if (!apply || !currentSession || !adaptationOk || eligible !== true || mode === null) { - return { ok: false, applied: false, message: 'The current nutrition review is not eligible to apply.' }; + const currentEligible = currentSession && adaptationOk && currentState.status === 'preview_current' && currentState.preview !== null + ? previewNutritionApplyEligibility({ session: currentSession, recipe: currentRecipe, state: currentState }) + : false; + if (!apply || !currentSession || !adaptationOk || currentEligible !== true || mode === null) { + return { + ok: false, + applied: false, + message: 'The current nutrition review is not eligible to apply.', + code: 'not_eligible', + }; } const reviewReasons: Record = {}; for (const [lineRef, review] of Object.entries(currentAiReviews)) { @@ -1774,6 +1784,106 @@ onReviewRecipeContextWithAi, // eslint-disable-next-line react-hooks/exhaustive-deps }, [session, adaptation, state, adapted, analyzedByRef, evidence, analysis, workingDispatch, shisoRegisterCorrections, workingDirty]); + // SHISO source selection uses the same authenticated Phase 4 match/portion + // builders as the visible review controls. It never accepts model-supplied + // grams or digests and verifies the resulting preview before dispatching. + const shisoRegisterSourceSelection = shiso.registerNutritionSourceSelectionApplier; + useEffect(() => { + return shisoRegisterSourceSelection(async ({ lineRef, fdcId, portionIndex }): Promise => { + const currentState = phase4StateRef.current; + const fail = (code: string, summary: string): ShisoNutritionSourceSelectionOutcome => ({ + ok: false, + line_ref: lineRef, + summary, + recalculation: 'absent', + working_unsaved: workingDirty, + code, + }); + if (!session || !adaptation.ok) return fail('no_nutrition_review', 'Advanced Nutrition is not available for this source selection.'); + const row = currentState.rows.find((candidate) => candidate.line_ref === lineRef); + const entry = adapted.find((candidate) => candidate.line_ref === lineRef); + if (!row || !entry || currentState.recipeKey !== adaptation.recipe.recipe_key || currentState.sessionIdentity === null) { + return fail('stale_recipe', 'That ingredient line is no longer part of the current authenticated review.'); + } + if (!Number.isSafeInteger(fdcId) || fdcId <= 0 || !Number.isSafeInteger(portionIndex) || portionIndex < 0) { + return fail('invalid_request', 'The USDA food or portion selection is invalid.'); + } + const exact = session.searchFoods(String(fdcId), 5); + const hit = exact.ok ? exact.results.find((result) => result.fdc_id === fdcId && result.exact_fdc_id) : undefined; + if (!hit) return fail('invalid_selection', 'That USDA record is not available in the authenticated catalog.'); + const match: MatchChoice = Object.freeze({ + kind: 'manual', + fdc_id: fdcId, + review_digest: row.review_digest ?? '', + record_digest: hit.record_digest, + catalog_digest: session.metadata().catalog_digest, + selectionOrigin: 'shiso_user_directed', + description: hit.description, + }); + const portion = buildPortionChoice(session, { + lineRef, + ingredient: entry.ingredient, + review: row.review, + selection: selectionFromMatchChoice(match, lineRef), + fdcId, + portionIndex, + }); + if (!portion.ok) return fail('invalid_selection', 'That USDA portion could not be authenticated for this ingredient.'); + let next = phase4Reducer(currentState, { type: 'select_match', lineRef, choice: match }); + next = phase4Reducer(next, { type: 'select_portion', lineRef, choice: portion.choice }); + const calculated = session.calculate(buildCalculationRequest(adapted, next)); + if (!calculated.ok) return fail('invalid_selection', 'The authenticated nutrition review rejected that source selection.'); + const selected = calculated.preview.ingredients.find((candidate) => candidate.line_ref === lineRef); + if (!selected || selected.fdc_id !== fdcId || selected.resolved_grams === undefined) { + return fail('invalid_selection', 'The selected USDA source did not produce a verified ingredient amount.'); + } + next = phase4Reducer(next, { + type: 'apply_analysis', + matches: next.matches, + portions: next.portions, + countPortions: next.countPortions, + householdPortions: next.householdPortions, + userMasses: next.userMasses, + aiEstimates: next.aiEstimates, + preview: calculated.preview, + }); + // React dispatch is asynchronous. Publish the exact verified state to + // the synchronous capability owner before dispatching it, so an Apply + // requested by the next tool in this same SHISO turn cannot consume the + // previous reducer snapshot. + phase4StateRef.current = next; + shisoNutritionReviewApplyRef.current = { + ...shisoNutritionReviewApplyRef.current, + state: next, + }; + workingDispatch({ + type: 'apply_analysis', + matches: next.matches, + portions: next.portions, + countPortions: next.countPortions, + householdPortions: next.householdPortions, + userMasses: next.userMasses, + aiEstimates: next.aiEstimates, + preview: calculated.preview, + }); + const portionReview = session.reviewPortions(fdcId); + const portionCandidate = portionReview.ok + ? portionReview.review.candidates.find((candidate) => candidate.index === portionIndex) + : undefined; + return { + ok: true, + line_ref: lineRef, + fdc_id: fdcId, + description: hit.description, + resolved_grams: selected.resolved_grams, + ...(portionCandidate ? { portion: portionCandidate.display_label } : {}), + summary: `Verified ${hit.description}: ${portionCandidate?.display_label ?? 'authenticated USDA portion'} → ${selected.resolved_grams} g. The working nutrition review was recalculated; nothing was saved.`, + recalculation: calculated.preview.status === 'complete' ? 'complete' : 'partial', + working_unsaved: true, + }; + }); + }, [session, adaptation, adapted, workingDispatch, shisoRegisterSourceSelection, workingDirty]); + /** The actionable exception rows derived from the SAME live projection. */ const actionableRows = useMemo( () => diff --git a/src/components/AdvancedNutritionModal.tsx b/src/components/AdvancedNutritionModal.tsx index e77e44e..7b61e8e 100644 --- a/src/components/AdvancedNutritionModal.tsx +++ b/src/components/AdvancedNutritionModal.tsx @@ -2886,6 +2886,8 @@ export const AdvancedNutritionModal: React.FC = ({ ? 'unique-exact food' : live?.food_authority === 'user_confirmed' || entry.user_confirmed ? 'user-confirmed food' + : live?.food_authority === 'assistant_user_directed' + ? 'SHISO-directed food' : undefined; // Mass provenance is INDEPENDENT of food authority. const portionAuthority = diff --git a/src/components/ShisoModal.tsx b/src/components/ShisoModal.tsx index 02badd7..2e10162 100644 --- a/src/components/ShisoModal.tsx +++ b/src/components/ShisoModal.tsx @@ -55,7 +55,7 @@ import { requestUsdaBrandedFoodLookup } from '../application/nutritionBrandedFoo import { requestNutritionWebResearch } from '../application/nutritionWebResearch'; import { useShisoRecipeContext } from '../application-ui/useShisoRecipeContext'; -import { useShiso, type ShisoNutritionAnalysisOutcome, type ShisoNutritionSnapshot } from '../application-ui/shisoEntryPoints'; +import { useShiso, type ShisoNutritionAnalysisOutcome, type ShisoNutritionSnapshot, type ShisoNutritionReviewApplyResult } from '../application-ui/shisoEntryPoints'; import type { ShisoBoundProposal } from '../core/shiso/protocol'; import { buildIdentityDisclosure } from '../core/shiso/disclosure'; import { classifySaveIntent, recipeIdentityOf } from '../core/shiso/saveAuthorization'; @@ -144,6 +144,11 @@ export interface ShisoModalProps { readonly applied: boolean; readonly message: string; }>; + readonly applyIndependentNutritionSourceSelection?: (input: { + readonly lineRef: string; + readonly fdcId: number; + readonly portionIndex: number; + }) => import('../core/shiso/protocol').ShisoNutritionSourceSelectionOutcome; readonly nutritionRows: readonly LiveRowState[]; readonly nutritionAiContributions?: readonly AiNutrientContribution[]; /** The AUTHORITATIVE review rows. Proposals are disclosed from these, never from prose. */ @@ -232,6 +237,7 @@ export function ShisoModal({ getIndependentNutritionSnapshot, acceptIndependentNutrition, applyIndependentNutritionReview, + applyIndependentNutritionSourceSelection, nutritionRows, nutritionAiContributions = [], nutritionReviewRows, @@ -293,6 +299,9 @@ export function ShisoModal({ const entriesRef = useRef(entries); entriesRef.current = entries; const loadedConversationKeyRef = useRef(null); + // Only the current trusted user turn may authorize choosing one branch of an + // equal authored alternative. Model tool arguments never set this value. + const trustedNutritionSelectionMessageRef = useRef(''); // H-2: the LATEST Shiso port surface. The conversation turn can outlive a // render (it awaits tool executions), so tools must never read a stale // closure of the ports — an edit applied mid-turn changes the recipe, and the @@ -504,6 +513,7 @@ export function ShisoModal({ recipeContext, nutritionAvailable, nutritionRows, + nutritionReviewRows, nutritionAiContributions, nutritionSummary, nutritionUnsaved, @@ -524,6 +534,7 @@ export function ShisoModal({ recipeContext, nutritionAvailable, nutritionRows, + nutritionReviewRows, nutritionAiContributions, nutritionSummary, nutritionUnsaved, @@ -582,6 +593,7 @@ export function ShisoModal({ return current.nutritionAvailable ? { rows: current.nutritionRows, + reviewRows: current.nutritionReviewRows, aiContributions: current.nutritionAiContributions, summary: current.nutritionAvailable ? nutritionCoverageSummary(deriveNutritionCoverage(current.nutritionRows, current.nutritionAiContributions)) @@ -706,12 +718,44 @@ export function ShisoModal({ shisoRef.current.applyNutritionCorrections(lineRefs) : undefined; }, + get applyNutritionSourceSelection() { + if (shisoRef.current.canApplyNutritionSourceSelection) { + return (input: Parameters>[0]) => + shisoRef.current.applyNutritionSourceSelection(input); + } + return applyIndependentNutritionSourceSelection + ? async (input) => applyIndependentNutritionSourceSelection(input) + : undefined; + }, + isTrustedNutritionSourceSelection: (lineRef, description) => { + const message = trustedNutritionSelectionMessageRef.current.toLocaleLowerCase(); + if (!/\b(?:pick|choose|select|use)\b/.test(message)) return false; + const terms = description + .toLocaleLowerCase() + .replace(/[^a-z0-9]+/g, ' ') + .split(/\s+/) + .filter((term) => term.length >= 3 && !['food', 'raw', 'fresh', 'with', 'and', 'from'].includes(term)); + return terms.some((term) => message.includes(term)) && lineRef.length > 0; + }, get applyNutritionReview() { - if (!shisoRef.current.canApplyNutritionReview && applyIndependentNutritionReview === undefined) return undefined; - return async () => { - const result = shisoRef.current.canApplyNutritionReview + const cardOwnerAvailable = shisoRef.current.canApplyNutritionReview; + if (!cardOwnerAvailable && applyIndependentNutritionReview === undefined) return undefined; + return async (): Promise => { + let result: ShisoNutritionReviewApplyResult = cardOwnerAvailable ? await shisoRef.current.applyNutritionReview() : await applyIndependentNutritionReview!(); + // The card is mounted for the recipe detail, but its review may not be + // the review that this global-chat turn prepared. A card owner that has + // no current eligible review must not shadow an eligible independent + // owner. Only the explicit ownership signal is retried; a real Apply + // failure (stale/versioned/authorization) is never substituted. + if ( + cardOwnerAvailable && + result.code === 'not_eligible' && + applyIndependentNutritionReview !== undefined + ) { + result = await applyIndependentNutritionReview(); + } if (result.ok && result.applied) { const policy = nutritionSavePolicyRef.current; nutritionSavePolicyRef.current = { ...policy, applied: true }; @@ -748,7 +792,7 @@ export function ShisoModal({ : undefined; }, }), - [acceptIndependentNutrition, applyIndependentNutritionReview, getIndependentNutritionSnapshot, network, onVaultRecipeSelected, runIndependentNutritionAnalysis, vaultCapabilities], + [acceptIndependentNutrition, applyIndependentNutritionReview, applyIndependentNutritionSourceSelection, getIndependentNutritionSnapshot, network, onVaultRecipeSelected, runIndependentNutritionAnalysis, vaultCapabilities], ); // Advanced Nutrition can invoke the very same recipe-bound, validated AI @@ -909,6 +953,7 @@ export function ShisoModal({ // message that does not ask to save, which clears any previous turn's // authorization. The model never sees or influences this decision. const saveIntent = classifySaveIntent(message); + trustedNutritionSelectionMessageRef.current = message; const authorizationRecipe = getSaveAuthorizationRecipe?.() ?? recipe ?? selectedVaultRecipeContext(vaultCapabilities); const authorizationRecipeIdentity = recipeIdentityOf(authorizationRecipe); nutritionSavePolicyRef.current = { diff --git a/src/core/nutritionV2/calculation/calculate.ts b/src/core/nutritionV2/calculation/calculate.ts index 88b0a2b..dcbf8c7 100644 --- a/src/core/nutritionV2/calculation/calculate.ts +++ b/src/core/nutritionV2/calculation/calculate.ts @@ -689,6 +689,7 @@ const MANUAL_SELECTION_KEYS = new Set([ 'line_ref', 'review_digest', 'ai_assisted', + 'selection_origin', ]); interface ManualFoodSelection { @@ -706,6 +707,7 @@ interface ManualFoodSelection { * yields `user_confirmed`. */ readonly aiAssisted: boolean; + readonly selectionOrigin: 'shiso_user_directed' | undefined; } /** @@ -731,6 +733,7 @@ function sanitizeManualSelection(raw: unknown): ManualFoodSelection | undefined if (typeof value.line_ref !== 'string' || value.line_ref.length === 0) return undefined; if (typeof value.review_digest !== 'string' || !SHA256_HEX.test(value.review_digest)) return undefined; if (value.ai_assisted !== undefined && typeof value.ai_assisted !== 'boolean') return undefined; + if (value.selection_origin !== undefined && value.selection_origin !== 'shiso_user_directed') return undefined; return { fdc_id: value.fdc_id, record_digest: value.record_digest, @@ -738,6 +741,7 @@ function sanitizeManualSelection(raw: unknown): ManualFoodSelection | undefined line_ref: value.line_ref, review_digest: value.review_digest, aiAssisted: value.ai_assisted === true, + selectionOrigin: value.selection_origin === 'shiso_user_directed' ? 'shiso_user_directed' : undefined, }; } @@ -797,7 +801,11 @@ function evaluateIngredient( // PROVENANCE: an AI-assisted deterministic acceptance is an AUTOMATIC // match (`auto_confirmed`), never human-reviewed authority. Only an // explicit user selection yields `user_confirmed`. - matchStatus = manual.aiAssisted ? 'auto_confirmed' : 'user_confirmed'; + matchStatus = manual.selectionOrigin === 'shiso_user_directed' + ? 'assistant_user_directed' + : manual.aiAssisted + ? 'auto_confirmed' + : 'user_confirmed'; fdcId = manual.fdc_id; recordDigest = manualRecord.record_digest; confirmationDigest = currentReview.review_digest; @@ -860,7 +868,7 @@ function evaluateIngredient( // path is the existing manual review authority; no new selection mechanism // is introduced here. const equalAlternative = projectIngredientAlternatives(parsed.original_text)?.primary_index === null; - if (equalAlternative && matchStatus !== 'user_confirmed') { + if (equalAlternative && matchStatus !== 'user_confirmed' && matchStatus !== 'assistant_user_directed') { ambiguous = true; } @@ -1397,6 +1405,7 @@ export function runAdvisoryCalculation(inputs: AdvisoryCalculationInputs): Calcu qualitative: entry.qualitative, match_status: entry.matchStatus, user_confirmed: entry.matchStatus === 'user_confirmed', + ...(entry.matchStatus === 'assistant_user_directed' ? { selection_origin: 'shiso_user_directed' as const } : {}), ...(entry.fdcId !== undefined ? { fdc_id: entry.fdcId } : {}), ...(entry.recordDigest !== undefined ? { record_digest: entry.recordDigest } : {}), ...(entry.massSource !== undefined ? { mass_source: entry.massSource } : {}), diff --git a/src/core/nutritionV2/calculation/types.ts b/src/core/nutritionV2/calculation/types.ts index e2e26f3..fdc7b80 100644 --- a/src/core/nutritionV2/calculation/types.ts +++ b/src/core/nutritionV2/calculation/types.ts @@ -163,7 +163,7 @@ export type IngredientOutcome = | 'no_mass' | 'no_nutrition'; -export type MatchStatus = 'unique_exact' | 'user_confirmed' | 'auto_confirmed' | 'none'; +export type MatchStatus = 'unique_exact' | 'user_confirmed' | 'assistant_user_directed' | 'auto_confirmed' | 'none'; /** * A BOUNDED AI MASS ESTIMATE selection supplied to the calculator (AI-3). @@ -217,6 +217,7 @@ export interface IngredientCalculationEvidence { readonly match_status: MatchStatus; /** True ONLY for an explicitly user-confirmed ambiguous match. */ readonly user_confirmed: boolean; + readonly selection_origin?: 'shiso_user_directed'; readonly fdc_id?: number; readonly record_digest?: string; readonly mass_source?: MassSource; diff --git a/src/core/nutritionV2/phase4/hydrate.ts b/src/core/nutritionV2/phase4/hydrate.ts index 31a245b..81bebee 100644 --- a/src/core/nutritionV2/phase4/hydrate.ts +++ b/src/core/nutritionV2/phase4/hydrate.ts @@ -138,6 +138,7 @@ function manualSelectionObject(lineRef: string, match: MatchChoice): unknown { catalog_digest: match.catalog_digest, line_ref: lineRef, review_digest: match.review_digest, + ...(match.selectionOrigin === 'shiso_user_directed' ? { selection_origin: 'shiso_user_directed' } : {}), }; } @@ -207,7 +208,7 @@ export function hydrateWorkingReview( let hydrated = 0; /** Re-derives a reviewed manual match for one line from the pinned catalog. */ - const reviewedMatchFor = (lineRef: string, fdcId: number): MatchChoice | undefined => { + const reviewedMatchFor = (lineRef: string, fdcId: number, selectionOrigin?: 'shiso_user_directed'): MatchChoice | undefined => { const row = rowByRef.get(lineRef); if (!row) return undefined; const search = session.searchFoods(String(fdcId), 1); @@ -220,6 +221,7 @@ export function hydrateWorkingReview( review_digest: row.review_digest ?? '', record_digest: hit.record_digest, catalog_digest: catalogDigest, + ...(selectionOrigin === 'shiso_user_directed' ? { selectionOrigin } : {}), description: hit.description, }); }; @@ -233,7 +235,7 @@ export function hydrateWorkingReview( const fdcId = parseFdcId(evidence.source_food_id); if (fdcId === undefined) continue; - const match = reviewedMatchFor(lineRef, fdcId); + const match = reviewedMatchFor(lineRef, fdcId, evidence.selection_origin); if (!match || evidence.source_release !== session.metadata().bundle_release) continue; matches[lineRef] = match; hydrated += 1; diff --git a/src/core/nutritionV2/phase4/liveRow.ts b/src/core/nutritionV2/phase4/liveRow.ts index 7be6b1e..b66dcf8 100644 --- a/src/core/nutritionV2/phase4/liveRow.ts +++ b/src/core/nutritionV2/phase4/liveRow.ts @@ -67,6 +67,7 @@ export type LiveRowFoodAuthority = | 'automatic' | 'unique_exact' | 'ai_assisted' + | 'assistant_user_directed' | 'user_confirmed' | 'none'; @@ -253,6 +254,8 @@ export function projectLiveRow(input: LiveRowProjectionInput): LiveRowState { ? 'unique_exact' : matchChoice?.aiAccepted === true ? 'ai_assisted' + : matchChoice?.selectionOrigin === 'shiso_user_directed' + ? 'assistant_user_directed' : matchChoice?.automatic === true ? 'automatic' : 'user_confirmed'; diff --git a/src/core/nutritionV2/phase4/rows.ts b/src/core/nutritionV2/phase4/rows.ts index 6153854..fd39b46 100644 --- a/src/core/nutritionV2/phase4/rows.ts +++ b/src/core/nutritionV2/phase4/rows.ts @@ -374,6 +374,7 @@ function selectionFor(choice: MatchChoice, lineRef: string): unknown { // AI-assisted DETERMINISTIC acceptance only. An explicit user choice // (manual search / "Use this match") omits this marker. ...(choice.aiAccepted === true ? { ai_assisted: true } : {}), + ...(choice.selectionOrigin === 'shiso_user_directed' ? { selection_origin: 'shiso_user_directed' } : {}), }; } return { kind: 'none', review_digest: choice.review_digest }; diff --git a/src/core/nutritionV2/phase4/types.ts b/src/core/nutritionV2/phase4/types.ts index 63fb8ae..de9bbff 100644 --- a/src/core/nutritionV2/phase4/types.ts +++ b/src/core/nutritionV2/phase4/types.ts @@ -329,6 +329,12 @@ export interface MatchChoice { * never forge automatic authority. Absent/false means an explicit user choice. */ readonly automatic?: boolean; + /** + * Auditable assistant-directed selection. This is distinct from a human + * `user_confirmed` selection and is only issued after the current user turn + * authorizes SHISO to choose an authenticated source. + */ + readonly selectionOrigin?: 'shiso_user_directed'; /** * Present ONLY for a `kind: 'manual'` selection (explicit user-directed manual * USDA search). The record digest and catalog digest bind the chosen record to diff --git a/src/core/nutritionV2/phase5/authorize.ts b/src/core/nutritionV2/phase5/authorize.ts index 138e9e5..0d68ca9 100644 --- a/src/core/nutritionV2/phase5/authorize.ts +++ b/src/core/nutritionV2/phase5/authorize.ts @@ -450,7 +450,12 @@ function buildPersistenceBlock( source_release: preview.bundle_release, match_status: 'confirmed', resolved: true, - user_confirmed: true, + // Existing Apply semantics treat every verified calculation entry as + // reviewed evidence. SHISO-directed selections are the one explicit + // exception: retain their distinct origin without relabeling them as a + // human click. + user_confirmed: entry.match_status !== 'assistant_user_directed', + ...(entry.selection_origin === 'shiso_user_directed' ? { selection_origin: 'shiso_user_directed' as const } : {}), amount: { value: canonicalGrams, unit: 'g' }, ...(conversion ? { conversion_basis: conversion } : {}), ...(entry.mass_source === 'count_portion' ? { count_portion: { unit: entry.count_unit ?? null, size: entry.count_size ?? null, quantity: entry.count_ingredient_amount, portion_amount: entry.count_portion_amount, gram_weight: entry.count_gram_weight } } : {}), @@ -477,8 +482,8 @@ function buildPersistenceBlock( const evidence = evidenceByRef.get(entry.line_ref); const reviewedFood = evidence !== undefined && - evidence.user_confirmed === true && - evidence.match_status === 'user_confirmed' && + (evidence.user_confirmed === true || evidence.selection_origin === 'shiso_user_directed') && + (evidence.match_status === 'user_confirmed' || evidence.match_status === 'assistant_user_directed') && typeof evidence.fdc_id === 'number' && Number.isSafeInteger(evidence.fdc_id) && evidence.fdc_id > 0; @@ -647,7 +652,7 @@ function authorizeNutritionPersistenceInternal( .map((entry) => entry.line_ref); for (const lineRef of equalAlternativeRefs) { const evidence = trusted.preview.ingredients.find((entry) => entry.line_ref === lineRef); - if (evidence?.match_status !== 'user_confirmed') return fail('explicit_choice_required'); + if (evidence?.match_status !== 'user_confirmed' && evidence?.match_status !== 'assistant_user_directed') return fail('explicit_choice_required'); } if (rawServings.value !== trusted.servings) return fail('stale_preview'); diff --git a/src/core/nutritionV2/schema.ts b/src/core/nutritionV2/schema.ts index c6e7f99..7b38e65 100644 --- a/src/core/nutritionV2/schema.ts +++ b/src/core/nutritionV2/schema.ts @@ -148,6 +148,8 @@ export interface IngredientEvidence { match_status: IngredientMatchStatus; resolved: boolean; user_confirmed: boolean; + /** Distinguishes an authenticated SHISO-directed choice from a human click. */ + selection_origin?: 'shiso_user_directed'; amount?: { value: number; unit: CanonicalUnit }; /** * Schema-v1 conversion bases are CLOSED to direct recipe mass and an diff --git a/src/core/nutritionV2/validate.ts b/src/core/nutritionV2/validate.ts index 7b74553..b86f418 100644 --- a/src/core/nutritionV2/validate.ts +++ b/src/core/nutritionV2/validate.ts @@ -183,6 +183,7 @@ const EVIDENCE_KEYS_V1 = new Set([ 'match_status', 'resolved', 'user_confirmed', + 'selection_origin', 'amount', 'conversion_basis', ]); @@ -621,9 +622,12 @@ function validateInertCodexNutrition( ) { diag.add('invalid_match_status'); } + if (entry.selection_origin !== undefined && entry.selection_origin !== 'shiso_user_directed') { + diag.add('invalid_selection_origin'); + } if (typeof entry.resolved !== 'boolean' || typeof entry.user_confirmed !== 'boolean') { diag.add('invalid_ingredient_flags'); - } else if (entry.resolved !== (matchStatus === 'confirmed' && entry.user_confirmed === true)) { + } else if (entry.resolved !== (matchStatus === 'confirmed' && (entry.user_confirmed === true || entry.selection_origin === 'shiso_user_directed'))) { diag.add('ingredient_resolution_inconsistent'); } let amount: IngredientEvidence['amount']; @@ -878,6 +882,7 @@ function validateInertCodexNutrition( match_status: matchStatus as IngredientEvidence['match_status'], resolved: entry.resolved === true, user_confirmed: entry.user_confirmed === true, + ...(entry.selection_origin === 'shiso_user_directed' ? { selection_origin: 'shiso_user_directed' as const } : {}), ...(amount ? { amount } : {}), ...(conversionBasis ? { conversion_basis: conversionBasis } : {}), ...(householdPortion ? { household_portion: householdPortion } : {}), diff --git a/src/core/shiso/protocol.ts b/src/core/shiso/protocol.ts index ecb6565..d136dfe 100644 --- a/src/core/shiso/protocol.ts +++ b/src/core/shiso/protocol.ts @@ -113,6 +113,8 @@ export const SHISO_LIMITS = Object.freeze({ maxIngredientEditPreparationChars: 160, /** Line refs accepted by ONE `apply_nutrition_corrections` call (H-2). */ maxCorrectionLineRefs: 24, + /** Bound for one authenticated SHISO-directed USDA source selection. */ + maxSelectionLineRefChars: 240, /** Request body ceiling in bytes. */ maxRequestBytes: 64 * 1024, }); @@ -196,6 +198,7 @@ export const SHISO_TOOL_NAMES = Object.freeze([ 'get_branded_evidence', 'search_usda_foods', 'inspect_usda_food', + 'select_usda_nutrition_source', 'investigate_ingredient_amount', 'investigate_unresolved_ingredients', 'run_nutrition_analysis', @@ -238,6 +241,17 @@ export type ShisoToolArgs = | { readonly tool: 'get_branded_evidence' } | { readonly tool: 'search_usda_foods'; readonly query: string; readonly limit?: number } | { readonly tool: 'inspect_usda_food'; readonly fdc_id: number } + | { + /** + * Promotes one authenticated USDA food and portion into the current + * Phase 4 working review. The application re-authenticates both against + * the live recipe/session; the model never supplies grams or evidence. + */ + readonly tool: 'select_usda_nutrition_source'; + readonly line_ref: string; + readonly fdc_id: number; + readonly portion_index: number; + } | { readonly tool: 'investigate_ingredient_amount'; readonly line_ref: string; @@ -456,6 +470,20 @@ export interface ShisoNutritionCorrectionsOutcome { readonly working_unsaved: boolean; } +/** Result of one authenticated USDA source/portion promotion. */ +export interface ShisoNutritionSourceSelectionOutcome { + readonly ok: boolean; + readonly line_ref: string; + readonly fdc_id?: number; + readonly description?: string; + readonly resolved_grams?: number; + readonly portion?: string; + readonly summary: string; + readonly recalculation: 'complete' | 'partial' | 'absent'; + readonly working_unsaved: boolean; + readonly code?: string; +} + // --------------------------------------------------------------------------- // Observations returned to the model. Bounded, verified, and free of authority. // --------------------------------------------------------------------------- @@ -477,6 +505,7 @@ export interface ShisoObservationFail { export type ShisoObservation = ShisoObservationOk | ShisoObservationFail; export type ShisoObservationFailureCode = + | 'invalid_request' | 'invalid_arguments' | 'vault_unavailable' | 'vault_recipe_not_found' @@ -492,6 +521,9 @@ export type ShisoObservationFailureCode = | 'analysis_unavailable' | 'review_not_initialized' | 'stale_recipe' + | 'invalid_selection' + | 'explicit_choice_required' + | 'selection_rejected' // H-2 editing capabilities. `no_edit_owner` / `no_save_owner` mean the // application surface that owns the working state is not mounted, so Shiso // must say so rather than pretend a change happened. diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index 3d0b1a9..c5c8aa7 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -6,18 +6,19 @@ */ import React, { useEffect } from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import App from '../../src/App'; -import { ShisoEntryProvider, useShiso } from '../../src/application-ui/shisoEntryPoints'; +import { ShisoEntryProvider, useShiso, type ShisoEntryPoints } from '../../src/application-ui/shisoEntryPoints'; import type { NetworkAdapter } from '../../src/application/adapters/NetworkAdapter'; import type { SettingsAdapter } from '../../src/application/adapters/SettingsAdapter'; import { createBrowserVaultAdapter } from '../../src/platform/browser'; import { loadVaultContent } from '../../src/application/vaultContent'; import { hydrateAiSelections } from '../../src/application/aiSelection'; import { createAdvancedNutritionSession } from '../../src/core/nutritionV2/phase4/session'; +import { adaptRecipe } from '../../src/core/nutritionV2/phase4'; import type { RuntimeBundleResult } from '../../src/core/nutritionV2/runtime'; import { USDA_ATTRIBUTION } from '../../src/core/nutritionV2/usda/types'; import { NUTRITION_PRODUCT_ACCESS_VERSION } from '../../src/core/nutritionV2/nutritionProductAccess'; @@ -153,6 +154,12 @@ function OpenGlobal() { return null; } +function CaptureShiso({ onReady }: { readonly onReady: (value: ShisoEntryPoints) => void }) { + const shiso = useShiso(); + useEffect(() => onReady(shiso), [onReady, shiso]); + return null; +} + const roots: string[] = []; describe('SHISO agent foundation real App save closure', () => { @@ -320,4 +327,98 @@ describe('SHISO agent foundation real App save closure', () => { await waitFor(() => expect(document.body.textContent).toContain('Nothing was applied or saved')); expect(await readFile(recipePath, 'utf8')).toBe(beforeNoSave); }, 120000); + + it('persists an immediate authenticated Honey selection through the real App without a timing delay', async () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-shiso-execution-app-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', 'Honey Selection Fixture.md'); + await mkdir(dirname(recipePath), { recursive: true }); + const markdown = [ + '---', 'title: "Honey Selection Fixture"', 'tags:', ' - food/recipes', + 'category: Dinner', 'servings: 4', '---', '# Honey Selection Fixture', + '## Ingredients', '- 1/4 cup honey (or brown sugar)', '## Instructions', '1. Stir.', '', + ].join('\n'); + await writeFile(recipePath, markdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable SHISO Execution Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + + const { manifest, records } = buildMatchingBundle([{ + fdcId: 169640, + dataType: 'sr_legacy', + description: 'Honey', + portions: [{ amount: 1, measure: 'cup', gram_weight: 339, 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 network = scriptedNetwork([ + { ok: true, kind: 'reply', text: 'Disposable test transport.', proposals: [] }, + ], { + '/api/nutrition/product-access': { ok: true, version: NUTRITION_PRODUCT_ACCESS_VERSION, tier: 'ai_advanced' }, + '/api/providers': { providers: [] }, + }); + let current: ShisoEntryPoints | null = null; + + render( + + + { current = value; }} /> + , + ); + + 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 SHISO Execution Vault"/); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: 'Honey Selection Fixture' })); + fireEvent.click(await screen.findByRole('button', { name: 'Generate Nutrition' })); + await screen.findByRole('dialog', { name: 'Advanced Nutrition' }); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(1)); + await waitFor(() => { + expect(current?.canApplyNutritionSourceSelection).toBe(true); + expect(current?.canApplyNutritionReview).toBe(true); + expect(current?.snapshot?.reviewRows.length).toBe(1); + }); + + const recipe = (await loadVaultContent(createBrowserVaultAdapter(root))).recipes.find((entry) => entry.title === 'Honey Selection Fixture'); + if (!recipe) throw new Error('disposable recipe was not loaded'); + const adaptation = adaptRecipe(recipe); + if (!adaptation.ok) throw new Error('recipe adaptation failed'); + const lineRef = adaptation.recipe.adapted[0]!.line_ref; + const portions = created.session.reviewPortions(169640); + if (!portions.ok) throw new Error('Honey portions missing'); + const honeyCup = portions.review.candidates.find((candidate) => candidate.gram_weight === 339 && /cup/i.test(candidate.display_label)); + if (!honeyCup) throw new Error('Authenticated Honey cup portion missing'); + + let selected!: Awaited>; + let applied!: Awaited>; + let saved!: Awaited>; + await act(async () => { + selected = await current!.applyNutritionSourceSelection({ lineRef, fdcId: 169640, portionIndex: honeyCup.index }); + applied = await current!.applyNutritionReview(); + saved = await current!.saveWorkingRecipe({ via: 'ui' }); + }); + expect(selected.ok).toBe(true); + expect(selected).toMatchObject({ fdc_id: 169640, resolved_grams: 84.75 }); + expect(applied).toMatchObject({ ok: true, applied: true }); + expect(saved).toMatchObject({ ok: true, saved: true }); + + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + const nutrition = persisted.recipes.find((entry) => entry.title === 'Honey Selection Fixture')?.codexNutrition; + expect(nutrition).toMatchObject({ status: 'complete', sources: ['usda_fdc'] }); + const serialized = JSON.stringify(nutrition); + expect(serialized).toContain('"source_food_id":"169640"'); + expect(serialized).toContain('"value":84.75'); + }, 120000); }); diff --git a/tests/unit/shisoAgentExecution.test.ts b/tests/unit/shisoAgentExecution.test.ts new file mode 100644 index 0000000..f9355d4 --- /dev/null +++ b/tests/unit/shisoAgentExecution.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { USDA_BUNDLE_RELEASE_LOCK } from '../../src/core/nutritionV2/usda/releaseLock'; +import { composeAdvancedNutritionSessionFromBundle } from '../../src/core/nutritionV2/runtime'; +import { createShisoNutritionReviewController } from '../../src/application/shisoNutritionReview'; +import { executeShisoTool, type ShisoToolContext } from '../../src/application/shisoTools'; +import { initialShisoConversation, runShisoConversationTurn } from '../../src/application/shisoConversation'; + +const BUNDLE_DIR = join( + __dirname, + '../../data/advanced-nutrition/usda', + USDA_BUNDLE_RELEASE_LOCK.bundle_release, +); + +async function makeSession() { + const result = await composeAdvancedNutritionSessionFromBundle({ + files: USDA_BUNDLE_RELEASE_LOCK.artifact_filenames.map((name) => ({ + name, + bytes: new Uint8Array(readFileSync(join(BUNDLE_DIR, name))), + })), + } as never); + if (!result.ok) throw new Error('USDA fixture did not load'); + return result.session; +} + +function honeyPortion(session: Awaited>) { + const portions = session.reviewPortions(169640); + if (!portions.ok) throw new Error('Honey portions missing from fixture'); + const portion = portions.review.candidates.find((candidate) => + candidate.kind === 'volume' && /cup/i.test(candidate.display_label) && candidate.gram_weight === 339, + ); + if (!portion) throw new Error('Authenticated 1 cup honey portion missing from fixture'); + return portion; +} + +function recipe(text: string) { + return { + title: 'SHISO agent selection fixture', + servings: 4, + ingredients: [{ text, name: 'honey', amount: 0.25, unit: 'cup', line_ref: '' }], + instructions: [], + }; +} + +describe('SHISO authenticated nutrition source selection', () => { + it('promotes the inspected honey record and authenticated cup portion into the working review', async () => { + const session = await makeSession(); + const sourceRecipe = recipe('1/4 cup honey (or brown sugar)'); + const controllerRecipe = { + title: sourceRecipe.title, + servings: sourceRecipe.servings, + ingredients: [{ original: sourceRecipe.ingredients[0].text, name: 'honey', amount: 0.25, unit: 'cup' }], + instructions: [], + }; + const controller = createShisoNutritionReviewController(controllerRecipe as never, session); + if (!controller) throw new Error('review controller unavailable'); + const lineRef = controller.getSnapshot()!.rows[0]!.line_ref; + const portion = honeyPortion(session); + const ctx: ShisoToolContext = { + session, + recipe: { ...sourceRecipe, ingredients: [{ ...sourceRecipe.ingredients[0], line_ref: lineRef }] }, + nutrition: controller.getSnapshot()!, + applyNutritionSourceSelection: (input) => Promise.resolve(controller.selectUsdaNutritionSource(input)), + }; + + const result = await executeShisoTool({ + tool: 'select_usda_nutrition_source', + line_ref: lineRef, + fdc_id: 169640, + portion_index: portion.index, + }, ctx); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.data['fdc_id']).toBe(169640); + expect(result.data['resolved_grams']).toBeCloseTo(84.75, 8); + expect(String(result.data['description'])).toMatch(/honey/i); + const state = controller.getState(); + const evidence = state.preview?.ingredients.find((entry) => entry.line_ref === lineRef); + expect(evidence?.match_status).toBe('assistant_user_directed'); + expect(evidence?.user_confirmed).toBe(false); + expect(evidence?.selection_origin).toBe('shiso_user_directed'); + expect(evidence?.resolved_grams).toBeCloseTo(84.75, 8); + }, 30000); + + it('refuses equal alternatives until the trusted user message names the selected branch', async () => { + const session = await makeSession(); + const sourceRecipe = recipe('1/4 cup honey or brown sugar'); + const controllerRecipe = { + title: sourceRecipe.title, + servings: sourceRecipe.servings, + ingredients: [{ original: sourceRecipe.ingredients[0].text, name: 'honey', amount: 0.25, unit: 'cup' }], + instructions: [], + }; + const controller = createShisoNutritionReviewController(controllerRecipe as never, session); + if (!controller) throw new Error('review controller unavailable'); + const lineRef = controller.getSnapshot()!.rows[0]!.line_ref; + const portion = honeyPortion(session); + const base: Omit = { + session, + recipe: { ...sourceRecipe, ingredients: [{ ...sourceRecipe.ingredients[0], line_ref: lineRef }] }, + nutrition: controller.getSnapshot()!, + applyNutritionSourceSelection: (input) => Promise.resolve(controller.selectUsdaNutritionSource(input)), + }; + const refused = await executeShisoTool({ + tool: 'select_usda_nutrition_source', line_ref: lineRef, fdc_id: 169640, portion_index: portion.index, + }, base); + expect(refused.ok).toBe(false); + if (refused.ok === false) expect(refused.code).toBe('explicit_choice_required'); + + const trusted = await executeShisoTool({ + tool: 'select_usda_nutrition_source', line_ref: lineRef, fdc_id: 169640, portion_index: portion.index, + }, { ...base, isTrustedNutritionSourceSelection: (_ref, description) => /honey/i.test(description) }); + expect(trusted.ok).toBe(true); + if (trusted.ok) expect(trusted.data['resolved_grams']).toBeCloseTo(84.75, 8); + }, 30000); + + it('executes an explicit branch choice before asking the model for another step', async () => { + const session = await makeSession(); + const sourceRecipe = recipe('1/4 cup honey (or brown sugar)'); + const controller = createShisoNutritionReviewController({ + title: sourceRecipe.title, + servings: sourceRecipe.servings, + ingredients: [{ original: sourceRecipe.ingredients[0].text, name: 'honey', amount: 0.25, unit: 'cup' }], + instructions: [], + } as never, session); + if (!controller) throw new Error('review controller unavailable'); + const lineRef = controller.getSnapshot()!.rows[0]!.line_ref; + const contextRecipe = { + title: sourceRecipe.title, + servings: 4, + ingredients: [{ ...sourceRecipe.ingredients[0], line_ref: lineRef }], + instructions: [], + }; + const toolContext: ShisoToolContext = { + session, + recipe: contextRecipe, + nutrition: controller.getSnapshot()!, + applyNutritionSourceSelection: (input) => Promise.resolve(controller.selectUsdaNutritionSource(input)), + }; + const 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: 'Honey was selected through the authenticated USDA review.', + model_invocations_used: 1, + tool_calls_used: 1, + }, + }), + } as never; + + const outcome = await runShisoConversationTurn( + { + network, + context: { + recipe: { title: sourceRecipe.title, ingredientCount: 1, stepCount: 0, servings: 4 }, + nutrition: { available: true, summary: '1 of 1 unresolved', unresolvedCount: 1, needsAmountCount: 0, needsMatchCount: 1, unsavedWorkingReview: true }, + recipeKey: 'selection-fixture', + sessionIdentity: 'session-fixture', + }, + toolContext, + }, + initialShisoConversation(), + 'pick the honey and fix it', + ); + + expect(outcome.ok).toBe(true); + expect(outcome.toolsUsed).toEqual(['select_usda_nutrition_source']); + expect(outcome.message).toContain('Verified Honey'); + const evidence = controller.getState().preview?.ingredients[0]; + expect(evidence).toMatchObject({ + fdc_id: 169640, + match_status: 'assistant_user_directed', + resolved_grams: 84.75, + }); + }, 30000); +}); diff --git a/tests/unit/shisoAgentExecutionUi.test.tsx b/tests/unit/shisoAgentExecutionUi.test.tsx new file mode 100644 index 0000000..b9808a5 --- /dev/null +++ b/tests/unit/shisoAgentExecutionUi.test.tsx @@ -0,0 +1,113 @@ +// @vitest-environment jsdom + +import { describe, expect, it, beforeAll, afterEach, vi } from 'vitest'; +import { render, waitFor, cleanup, act } from '@testing-library/react'; +import { useEffect, type ComponentProps } from 'react'; + +import { AdvancedNutritionCard } from '../../src/components/AdvancedNutritionCard'; +import { ShisoEntryProvider, useShiso, type ShisoEntryPoints } from '../../src/application-ui/shisoEntryPoints'; +import { adaptRecipe } from '../../src/core/nutritionV2/phase4'; +import { createAdvancedNutritionSession } from '../../src/core/nutritionV2/phase4/session'; +import type { AdvancedNutritionSession } from '../../src/core/nutritionV2/phase4'; +import type { ObsidianRecipe } from '../../src/types'; +import { buildMatchingBundle } from '../fixtures/usdaMatchingFixtures'; + +let session: AdvancedNutritionSession; + +beforeAll(() => { + const { manifest, records } = buildMatchingBundle([{ + fdcId: 169640, + dataType: 'sr_legacy', + description: 'Honey', + portions: [{ amount: 1, measure: 'cup', gram_weight: 339, sequence: 1 }], + }]); + const result = createAdvancedNutritionSession(manifest, records); + if (!result.ok) throw new Error('USDA fixture did not load'); + session = result.session; +}); + +afterEach(() => cleanup()); + +function honeyRecipe(): ObsidianRecipe { + return { + id: 'shiso-execution-honey', + fileName: 'shiso-execution-honey.md', + filePath: 'Recipes/shiso-execution-honey.md', + rawMarkdown: '', + title: 'SHISO Honey Selection', + tags: [], + category: 'Test', + cuisine: 'Test', + difficulty: 'Easy', + rating: 0, + servings: 4, + ingredients: [{ + original: '1/4 cup honey (or brown sugar)', + amount: 0.25, + unit: 'cup', + name: 'honey', + }] as never, + instructions: [], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, + } as ObsidianRecipe; +} + +function PortProbe({ onReady }: { readonly onReady: (value: ShisoEntryPoints) => void }) { + const shiso = useShiso(); + useEffect(() => onReady(shiso), [onReady, shiso]); + return null; +} + +describe('SHISO connected execution ordering', () => { + it('applies the synchronously committed USDA selection without a render delay', async () => { + const recipe = honeyRecipe(); + const adaptation = adaptRecipe(recipe); + if (!adaptation.ok) throw new Error('recipe adaptation failed'); + const lineRef = adaptation.recipe.adapted[0]!.line_ref; + const portions = session.reviewPortions(169640); + if (!portions.ok) throw new Error('Honey portions missing'); + const honeyCup = portions.review.candidates.find((candidate) => candidate.gram_weight === 339 && /cup/i.test(candidate.display_label)); + if (!honeyCup) throw new Error('Authenticated Honey cup portion missing'); + + const apply = vi.fn(async (request: Parameters['onApplyAdvancedNutrition']>>[0]) => { + const evidence = request.state.preview?.ingredients.find((entry) => entry.line_ref === lineRef); + expect(evidence?.fdc_id).toBe(169640); + expect(evidence?.resolved_grams).toBeCloseTo(84.75, 8); + expect(request.state.preview?.status).toBe('complete'); + return { ok: true, mode: request.expectedMode, message: 'Applied the committed review.' }; + }); + + let current: ShisoEntryPoints | null = null; + const onReady = (value: ShisoEntryPoints) => { current = value; }; + render( + + + + , + ); + + await waitFor(() => { + expect(current?.canApplyNutritionSourceSelection).toBe(true); + expect(current?.canApplyNutritionReview).toBe(true); + expect(current?.snapshot?.reviewRows.length).toBe(1); + }); + + // Deliberately do not wait for a React render between these two calls. + let selected!: Awaited>; + let applied!: Awaited>; + await act(async () => { + selected = await current!.applyNutritionSourceSelection({ + lineRef, + fdcId: 169640, + portionIndex: honeyCup.index, + }); + applied = await current!.applyNutritionReview(); + }); + expect(selected.ok).toBe(true); + expect(applied).toMatchObject({ ok: true, applied: true }); + expect(apply).toHaveBeenCalledTimes(1); + }, 30000); +}); diff --git a/tests/unit/useShisoRecipeContext.test.tsx b/tests/unit/useShisoRecipeContext.test.tsx new file mode 100644 index 0000000..b93d361 --- /dev/null +++ b/tests/unit/useShisoRecipeContext.test.tsx @@ -0,0 +1,31 @@ +// @vitest-environment jsdom + +import { describe, expect, it } from 'vitest'; +import { renderHook } from '@testing-library/react'; + +import { useShisoRecipeContext } from '../../src/application-ui/useShisoRecipeContext'; + +describe('production SHISO recipe context projection', () => { + it('retains authored quantity and unit for the deterministic nutrition path', () => { + const { result } = renderHook(() => useShisoRecipeContext({ + title: '15-Minute Strawberry Spinach Salad', + servings: 4, + // This is the shape supplied by the production recipe view: the + // authored line is present even when structured amount/unit fields have + // not been materialized by the upstream parser. + ingredients: [{ + original: '1/4 cup honey (or brown sugar)', + name: 'honey', + }], + instructions: [], + })); + + expect(result.current?.ingredients[0]).toMatchObject({ + text: '1/4 cup honey (or brown sugar)', + name: 'honey', + amount: 0.25, + unit: 'cup', + }); + expect(result.current?.ingredients[0]?.line_ref).toMatch(/^ing:/); + }); +}); From 66f084fa01d2e7895436ff18c272686547986965 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 17:35:31 -0500 Subject: [PATCH 2/4] test(shiso): update closed capability count --- tests/security/shisoAuditRepairs.test.ts | 5 ++++- tests/security/shisoH1Repairs.test.ts | 8 +++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/security/shisoAuditRepairs.test.ts b/tests/security/shisoAuditRepairs.test.ts index 4077ddd..1980b3d 100644 --- a/tests/security/shisoAuditRepairs.test.ts +++ b/tests/security/shisoAuditRepairs.test.ts @@ -239,7 +239,10 @@ describe('F-1 — the advertised capability surface is truthful', () => { // SINC-3 added complete_nutrition: an owner-delegated completion pipeline // that prepares proposals in the unsaved review and never applies or saves. expect(SHISO_TOOL_NAMES).toContain('complete_nutrition'); - expect(SHISO_TOOL_NAMES).toHaveLength(19); + // Agent execution adds authenticated USDA source selection as the final + // owner-delegated capability in this closed vocabulary. + expect(SHISO_TOOL_NAMES).toContain('select_usda_nutrition_source'); + expect(SHISO_TOOL_NAMES).toHaveLength(20); }); }); diff --git a/tests/security/shisoH1Repairs.test.ts b/tests/security/shisoH1Repairs.test.ts index a8fb67d..8a7869a 100644 --- a/tests/security/shisoH1Repairs.test.ts +++ b/tests/security/shisoH1Repairs.test.ts @@ -452,9 +452,11 @@ describe('H-1 Scenario F — unsupported requests are refused truthfully', () => expect(SHISO_TOOL_NAMES as readonly string[]).not.toContain(forbidden); } // Still a small, closed vocabulary (H-2 added the three authorized editing - // capabilities; SINC-3 added complete_nutrition, which prepares proposals - // only and never applies or saves). - expect(SHISO_TOOL_NAMES.length).toBe(19); + // capabilities; SINC-3 added complete_nutrition, and Agent Execution added + // authenticated USDA source selection; neither bypasses the application + // owners or expands access to files, shells, or arbitrary network calls). + expect(SHISO_TOOL_NAMES).toContain('select_usda_nutrition_source'); + expect(SHISO_TOOL_NAMES.length).toBe(20); }); it('the tool dispatcher still cannot reach the filesystem or network', () => { From 6d982d411c9746eb2d4669048c9c8f20e474b7c5 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 17:39:09 -0500 Subject: [PATCH 3/4] test(shiso): align security isolation contracts --- tests/security/shisoH1fRepairs.test.ts | 10 ++++++---- tests/security/usdaMatchingIsolation.test.ts | 9 ++++++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/tests/security/shisoH1fRepairs.test.ts b/tests/security/shisoH1fRepairs.test.ts index ffc2b3d..c13cda6 100644 --- a/tests/security/shisoH1fRepairs.test.ts +++ b/tests/security/shisoH1fRepairs.test.ts @@ -451,16 +451,18 @@ describe('H-1F Test C — timeouts and accounting', () => { }); // =========================================================================== -// 18–19. Security invariants +// 18–20. Security invariants // =========================================================================== describe('H-1F — security invariants', () => { it('the vocabulary stays closed and non-mutating', () => { // H-2 added three AUTHORIZED EDITING capabilities (apply_ingredient_edits, - // apply_nutrition_corrections, save_working_recipe). They still cannot reach - // the filesystem, a shell, or the vault directly — every change is performed + // apply_nutrition_corrections, save_working_recipe). Agent Execution adds + // authenticated USDA source selection. They still cannot reach the + // filesystem, a shell, or the vault directly — every change is performed // by the application owner of that state. - expect(SHISO_TOOL_NAMES.length).toBe(19); + expect(SHISO_TOOL_NAMES).toContain('select_usda_nutrition_source'); + expect(SHISO_TOOL_NAMES.length).toBe(20); for (const forbidden of [ 'generate_image', 'create_image', 'edit_image', 'write_vault', 'save_recipe', 'run_command', 'read_file', 'exec', 'spawn', 'apply_proposal', 'dispatch_action', diff --git a/tests/security/usdaMatchingIsolation.test.ts b/tests/security/usdaMatchingIsolation.test.ts index 0533dba..71c7cb1 100644 --- a/tests/security/usdaMatchingIsolation.test.ts +++ b/tests/security/usdaMatchingIsolation.test.ts @@ -167,7 +167,7 @@ describe('phase 2 matching — isolation and purity', () => { for (const file of MATCHING_FILES) expect(file.endsWith('.ts')).toBe(true); }); - it('is imported ONLY by the explicit Phase 4 review/display boundary', () => { + it('is imported only by audited review/display boundaries and SHISO projections', () => { const productionRoots = [resolve(ROOT, 'src'), resolve(ROOT, 'server')]; const offenders: string[] = []; const importRe = /(?:from|import)\s*(?:\(\s*)?\s*['"]([^'"]+)['"]/g; @@ -179,6 +179,13 @@ describe('phase 2 matching — isolation and purity', () => { // Basic Nutrition uses the same authenticated analyzer, never a second matcher. if (file === resolve(ROOT, 'src/application/catalogBasicNutrition.ts')) continue; if (file.startsWith(PHASE5C_DIR)) continue; // Phase 5C presentation selector (audited) + // SHISO uses only the canonical parser to retain authored quantity/unit + // context for its existing Phase 4 selection authority; it does not + // create a second matcher or access the catalog directly. + if ( + file === resolve(ROOT, 'src/application/shisoConversation.ts') || + file === resolve(ROOT, 'src/application-ui/useShisoRecipeContext.ts') + ) continue; const source = readFileSync(file, 'utf8'); let match: RegExpExecArray | null; importRe.lastIndex = 0; From 56afe796bf128c00cfef5b434d147a641fc333ff Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 17:43:29 -0500 Subject: [PATCH 4/4] test(shiso): assert replay guard response --- tests/unit/shisoH2UiEditing.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/shisoH2UiEditing.test.tsx b/tests/unit/shisoH2UiEditing.test.tsx index 4a05d85..7130a8d 100644 --- a/tests/unit/shisoH2UiEditing.test.tsx +++ b/tests/unit/shisoH2UiEditing.test.tsx @@ -329,7 +329,7 @@ describe('SHISO H-2 — ADVERSARIAL save authorization (existing unsaved working />, ); await send('save my changes'); - await waitFor(() => expect(screen.getByText('Saved once.')).toBeTruthy(), { timeout: 15000 }); + await waitFor(() => expect(screen.getByText(/already verified the same save_working_recipe request/)).toBeTruthy(), { timeout: 15000 }); expect(saves).toBe(1); }, 60000);