From f5b778e8aad3b39320009cec361a7379c33f5703 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 12:23:24 -0500 Subject: [PATCH 1/2] feat(shiso): add autonomous nutrition authority workflow --- src/App.tsx | 176 ++++++++++++++++- src/application-ui/shisoEntryPoints.tsx | 58 +++++- src/application/nutritionChangeHistory.ts | 55 ++++++ src/application/shisoConversation.ts | 71 ++++++- src/application/shisoTools.ts | 162 +++++++++++++++- src/components/AdvancedNutritionCard.tsx | 180 ++++++++++++++++-- src/components/AdvancedNutritionModal.tsx | 36 +++- src/components/RecipeDetailView.tsx | 9 + src/components/RecipeNutritionSection.tsx | 9 + src/components/ShisoModal.tsx | 57 +++++- src/core/nutritionV2/calculation/calculate.ts | 20 +- src/core/nutritionV2/matching/query.ts | 48 +++++ src/core/nutritionV2/phase4/analyzer.ts | 17 ++ src/core/nutritionV2/phase5/authorize.ts | 16 ++ src/core/nutritionV2/phase5/types.ts | 2 + src/core/shiso/nutritionAuthority.ts | 57 ++++++ src/core/shiso/protocol.ts | 1 + src/core/shiso/saveAuthorization.ts | 20 +- .../shisoAgentFoundationAppOnDisk.test.tsx | 92 ++++++++- .../security/shisoH2SaveAuthorization.test.ts | 17 +- .../advancedNutritionAiExceptionsUi.test.tsx | 120 +++++++++++- .../unit/shisoN1IngredientResolution.test.ts | 86 +++++++++ tests/unit/shisoNutritionAuthority.test.ts | 36 ++++ tests/unit/shisoNutritionCompletion.test.ts | 65 +++++++ 24 files changed, 1355 insertions(+), 55 deletions(-) create mode 100644 src/application/nutritionChangeHistory.ts create mode 100644 src/core/shiso/nutritionAuthority.ts create mode 100644 tests/unit/shisoNutritionAuthority.test.ts diff --git a/src/App.tsx b/src/App.tsx index bb35138..e1c96ca 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -186,6 +186,20 @@ import { verifySaveGrant, type ShisoSaveGrant, } from './core/shiso/saveAuthorization'; +import { + SHISO_NUTRITION_AUTHORITY_SETTING, + grantNutritionAuthority, + nutritionAuthorityEnabled, + nutritionAuthorityVaultScope, + parseNutritionAuthorityRecord, + type ShisoNutritionAuthorityRecord, +} from './core/shiso/nutritionAuthority'; +import { + SHISO_NUTRITION_HISTORY_SETTING, + appendNutritionChange, + parseNutritionChangeHistory, + type ShisoNutritionChangeRecord, +} from './application/nutritionChangeHistory'; import type { ShisoAnalysisOutcome, ShisoIngredientEditArgs, @@ -879,6 +893,31 @@ export default function App({ // Theme State (persisted via SettingsAdapter; hydrated on mount) const [theme, setTheme] = useState(DEFAULT_THEME_ID); + const [nutritionAuthorityRecord, setNutritionAuthorityRecord] = useState(null); + const [nutritionChangeHistory, setNutritionChangeHistory] = useState([]); + + const nutritionAuthorityScope = useMemo(() => { + if (!vaultStatus.isConnected || vaultStatus.accessType !== 'filesystem_api') return ''; + const handle = vaultStatus.folderHandle as { root?: unknown; name?: unknown } | undefined; + const locator = typeof handle?.root === 'string' + ? handle.root + : typeof handle?.name === 'string' + ? handle.name + : vaultStatus.vaultPath; + return nutritionAuthorityVaultScope({ kind: 'filesystem', locator }); + }, [vaultStatus.accessType, vaultStatus.folderHandle, vaultStatus.isConnected, vaultStatus.vaultPath]); + const nutritionAuthorityActive = nutritionAuthorityEnabled(nutritionAuthorityRecord, nutritionAuthorityScope); + + const setNutritionAuthority = useCallback(async (enabled: boolean) => { + if (!enabled) { + setNutritionAuthorityRecord(null); + await settingsAdapter.remove(SHISO_NUTRITION_AUTHORITY_SETTING); + return; + } + const record = grantNutritionAuthority(nutritionAuthorityScope); + await settingsAdapter.set(SHISO_NUTRITION_AUTHORITY_SETTING, record); + setNutritionAuthorityRecord(record); + }, [nutritionAuthorityScope, settingsAdapter]); // Navigation & View State (persisted via SettingsAdapter; hydrated on mount) const [activeTab, setActiveTab] = useState<'grid' | 'dataview' | 'mealplan' | 'shopping' | 'themes' | 'providers'>('grid'); @@ -1868,10 +1907,12 @@ export default function App({ let cancelled = false; (async () => { try { - const [savedTheme, savedTab, savedTimers] = await Promise.all([ + const [savedTheme, savedTab, savedTimers, savedNutritionAuthority, savedNutritionHistory] = await Promise.all([ settingsAdapter.get('obsidian_vault_theme'), settingsAdapter.get<'grid' | 'dataview' | 'mealplan' | 'shopping' | 'themes' | 'providers'>('obsidian_active_tab'), settingsAdapter.get('obsidian_active_cooking_timers'), + settingsAdapter.get(SHISO_NUTRITION_AUTHORITY_SETTING), + settingsAdapter.get(SHISO_NUTRITION_HISTORY_SETTING), ]); if (cancelled) return; setTheme((cur) => @@ -1901,6 +1942,8 @@ export default function App({ .map((t) => reconcileTimer(t, now).timer); return mergeHydratedSetting(cur, migrated, (t) => Array.isArray(t) && t.length === 0, (t) => Array.isArray(t)); }); + setNutritionAuthorityRecord(parseNutritionAuthorityRecord(savedNutritionAuthority)); + setNutritionChangeHistory(parseNutritionChangeHistory(savedNutritionHistory)); } catch (err) { console.warn('Failed to hydrate persisted settings:', err); } finally { @@ -2052,6 +2095,11 @@ export default function App({ const handleDirectVaultConnected = async ( folderHandle: any ): Promise<{ recipeCount: number; noteCount: number; accepted: boolean; message?: string }> => { + // An explicit folder selection is a new authority decision. Revoke the + // previous Vault's standing nutrition grant before the new handle can win, + // including the browser edge case where two folders share the same name. + setNutritionAuthorityRecord(null); + await settingsAdapter.remove(SHISO_NUTRITION_AUTHORITY_SETTING).catch(() => undefined); const transition = vaultAuthority.beginTransition('filesystem'); const assetScope = createVaultAssetScope(null, { active: false }); setVaultHydratedState(false); @@ -2150,7 +2198,7 @@ export default function App({ }, []); const commitRecipeWrite = useCallback( - async (savedRecipe: ObsidianRecipe, baseRecipe?: ObsidianRecipe) => { + async (savedRecipe: ObsidianRecipe, baseRecipe?: ObsidianRecipe, options?: { readonly useDesiredRawMarkdown?: boolean }) => { if (isBuiltInRecipe(savedRecipe) || isBuiltInRecipe(baseRecipe)) { throw new Error('Signature Collection originals are read-only. Save this recipe to My Vault first.'); } @@ -2169,7 +2217,10 @@ export default function App({ throw vaultSessionSupersededError(); } const latest = committedRecipesRef.current.find((r) => sameCanonicalRecipeIdentity(r, savedRecipe)); - const toWrite = rebaseRecipeOntoLatest(latest, base, savedRecipe); + const rebased = rebaseRecipeOntoLatest(latest, base, savedRecipe); + const toWrite = options?.useDesiredRawMarkdown === true + ? { ...rebased, rawMarkdown: savedRecipe.rawMarkdown } + : rebased; if (requestedAdapter) { const lease = vaultAuthority.beginWrite(requestedSession); if (!lease) throw vaultSessionSupersededError(); @@ -2607,7 +2658,7 @@ export default function App({ message: 'There is nothing to save — this recipe has no unsaved changes from Shiso.', }; } - const verdict = verifySaveGrant(grant, recipeIdentityOf(current.base)); + const verdict = verifySaveGrant(grant, recipeIdentityOf(current.base), nutritionAuthorityScope); if (verdict.ok !== true) { return { ok: false, @@ -2616,9 +2667,12 @@ export default function App({ message: verdict.reason === 'stale_recipe' ? 'That save was authorized for a different recipe, so nothing was saved. Ask again for this recipe.' + : verdict.reason === 'stale_vault' + ? 'The active Vault changed after nutrition authority was granted. Nothing was saved.' : 'Saving needs your explicit instruction (for example “save my changes”) or the Save button. Nothing was saved.', }; } + const nutritionChanged = JSON.stringify(current.working.codexNutrition ?? null) !== JSON.stringify(current.base.codexNutrition ?? null); try { await commitRecipeWrite(current.working, current.base); } catch (err) { @@ -2628,14 +2682,41 @@ export default function App({ reportVaultError('save', current.working.title || 'recipe', err); return { ok: false, saved: false, reason_code: 'write_failed', message: 'The recipe could not be saved to the vault.' }; } + let historyRecorded = true; + if (nutritionChanged) { + const block = current.working.codexNutrition; + const sources = block && 'sources' in block && Array.isArray(block.sources) + ? block.sources.join(', ') + : 'reviewed nutrition evidence'; + const record: ShisoNutritionChangeRecord = { + id: `${nutritionAuthorityScope}:${recipeIdentityOf(current.base)}:${Date.now()}`, + vault_scope: nutritionAuthorityScope, + recipe_identity: recipeIdentityOf(current.base), + recipe_title: current.working.title, + changed_at: new Date().toISOString(), + reason: grant?.via === 'standing_nutrition' + ? 'SHISO applied and saved a reviewed nutrition update under standing Vault authority.' + : 'A reviewed Advanced Nutrition update was saved.', + evidence: `The saved nutrition block retained its own ingredient provenance and source identifiers (${sources}).`, + previous: current.base.codexNutrition, + next: current.working.codexNutrition, + }; + const nextHistory = appendNutritionChange(nutritionChangeHistory, record); + setNutritionChangeHistory(nextHistory); + try { + await settingsAdapter.set(SHISO_NUTRITION_HISTORY_SETTING, nextHistory); + } catch { + historyRecorded = false; + } + } updateShisoWorkingRecipe(null); return { ok: true, saved: true, - message: `Saved "${current.working.title}" with ${current.changes.length + Number(JSON.stringify(current.working.codexNutrition ?? null) !== JSON.stringify(current.base.codexNutrition ?? null))} recipe change(s).`, + message: `Saved "${current.working.title}" with ${current.changes.length + Number(nutritionChanged)} recipe change(s).${historyRecorded ? '' : ' The recipe was saved, but the local nutrition restore history could not be recorded.'}`, }; }, - [commitRecipeWrite, updateShisoWorkingRecipe], + [commitRecipeWrite, nutritionAuthorityScope, nutritionChangeHistory, settingsAdapter, updateShisoWorkingRecipe], ); // SHISO H-2 — register the recipe-edit/save applier with the ONE Shiso entry @@ -2698,6 +2779,50 @@ export default function App({ const displayRecipe: ObsidianRecipe | null = shisoWorkingForSelected?.working ?? selectedRecipe; + const restorableNutritionChange = useMemo(() => { + if (selectedRecipe === null || nutritionAuthorityScope.length === 0) return null; + const identity = recipeIdentityOf(selectedRecipe); + return [...nutritionChangeHistory].reverse().find((record) => + record.vault_scope === nutritionAuthorityScope && record.recipe_identity === identity, + ) ?? null; + }, [nutritionAuthorityScope, nutritionChangeHistory, selectedRecipe]); + + const restorePreviousNutrition = useCallback(async () => { + const recipe = selectedRecipe; + const record = restorableNutritionChange; + if (recipe === null || record === null) return; + if (JSON.stringify(recipe.codexNutrition ?? null) !== JSON.stringify(record.next ?? null)) { + setVaultNotice({ + tone: 'error', + message: 'Nutrition changed after this history entry was recorded, so Restore stopped without overwriting newer work.', + }); + return; + } + const restoredBase = { ...recipe, codexNutrition: record.previous, rawMarkdown: '' }; + const restored = record.previous === undefined + ? (() => { + const frontmatter = { ...(recipe.frontmatter ?? {}) }; + delete frontmatter.codex_nutrition; + const withoutNutrition = { ...restoredBase, frontmatter }; + return { ...withoutNutrition, rawMarkdown: serializeRecipeToObsidianMarkdown(withoutNutrition) }; + })() + : restoredBase; + try { + await commitRecipeWrite(restored, recipe, { useDesiredRawMarkdown: record.previous === undefined }); + const remaining = nutritionChangeHistory.filter((item) => item.id !== record.id); + setNutritionChangeHistory(remaining); + await settingsAdapter.set(SHISO_NUTRITION_HISTORY_SETTING, remaining); + setVaultNotice({ tone: 'success', message: `Restored the previous nutrition values for "${recipe.title}".` }); + } catch (error) { + setVaultNotice({ + tone: 'error', + message: isVaultSessionSuperseded(error) + ? 'The Vault changed before Restore completed. No nutrition was overwritten.' + : 'The previous nutrition values could not be restored. The current recipe remains unchanged.', + }); + } + }, [commitRecipeWrite, nutritionChangeHistory, restorableNutritionChange, selectedRecipe, settingsAdapter]); + // Create for Me save (generated-save scoped). A same-title file is NEVER // overwritten: on a collision this throws GeneratedRecipePathCollisionError // before any write, so the modal keeps the draft open with a bounded message. @@ -4704,6 +4829,34 @@ export default function App({ )} + {restorableNutritionChange !== null && shisoWorkingForSelected === null && ( +
+
+ + SHISO nutrition change · {new Date(restorableNutritionChange.changed_at).toLocaleString()} + +
+

Reason: {restorableNutritionChange.reason}

+

Evidence: {restorableNutritionChange.evidence}

+

+ Previous:{' '} + {restorableNutritionChange.previous ? `schema ${restorableNutritionChange.previous.schema}, ${'status' in restorableNutritionChange.previous ? restorableNutritionChange.previous.status : 'opaque'}` : 'no Advanced Nutrition block'} + {' → '} + Saved:{' '} + {restorableNutritionChange.next ? `schema ${restorableNutritionChange.next.schema}, ${'status' in restorableNutritionChange.next ? restorableNutritionChange.next.status : 'opaque'}` : 'none'} +

+ +
+
+
+ )} 0, + recipeIdentity: recipeIdentityOf(displayRecipe), + vaultScope: nutritionAuthorityScope, + onChange: setNutritionAuthority, + }} onResolveAdvancedNutritionAi={handleResolveAdvancedNutritionAi} onResolveAdvancedNutritionAiFirst={ AI_FIRST_GENERATE_ENABLED ? handleResolveAdvancedNutritionAiFirst : undefined @@ -5370,6 +5530,10 @@ export default function App({ vaultCapabilities={shisoVaultCapabilityOverride ?? shisoVaultCapabilities} onVaultRecipeSelected={handleShisoVaultRecipeSelected} getSaveAuthorizationRecipe={getShisoSaveAuthorizationRecipe} + nutritionAuthority={{ + enabled: nutritionAuthorityActive, + vaultScope: nutritionAuthorityScope, + }} // General SHISO can select a Vault recipe during the same turn. Keep // that selection inside the capability/review owner without changing // the conversation context key from `global` to `recipe:*` halfway diff --git a/src/application-ui/shisoEntryPoints.tsx b/src/application-ui/shisoEntryPoints.tsx index 855cc14..f487fcd 100644 --- a/src/application-ui/shisoEntryPoints.tsx +++ b/src/application-ui/shisoEntryPoints.tsx @@ -114,7 +114,11 @@ export interface ShisoRecipeEditApplier { * when the CURRENT user turn issued a save authorization at send time. */ export interface ShisoSaveRequest { - readonly via?: 'ui' | 'assistant'; + readonly via?: 'ui' | 'assistant' | 'standing_nutrition'; + readonly recipe_identity?: string; + readonly vault_scope?: string; + readonly turn?: number; + readonly nutrition_applied?: true; } export interface ShisoEntryPoints { @@ -154,6 +158,12 @@ export interface ShisoEntryPoints { readonly runAnalysis: (() => Promise) | null; 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 canApplyNutritionReview: boolean; + readonly registerNutritionReviewApplier: ( + applier: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>, + ) => () => void; // ------------------------------------------------------------------------- // H-2 — authorized editing ports @@ -225,6 +235,9 @@ const INERT: ShisoEntryPoints = { runAnalysis: null, canRunAnalysis: false, registerAnalysisApplier: () => () => {}, + applyNutritionReview: async () => ({ ok: false, applied: false, message: 'No current nutrition review is available to apply.' }), + canApplyNutritionReview: false, + registerNutritionReviewApplier: () => () => {}, applyIngredientEdits: async () => ({ ok: false, applied: [], @@ -275,6 +288,7 @@ 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 [nutritionAnalysisRunner, setNutritionAnalysisRunner] = useState<(() => Promise) | null>(null); const [recipeEditApplier, setRecipeEditApplier] = useState(null); const [correctionsApplier, setCorrectionsApplier] = useState< @@ -324,6 +338,16 @@ 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 }>) => { + setNutritionReviewApplier(() => next); + return () => setNutritionReviewApplier((current) => current === next ? null : current); + }, []); + const applyNutritionReview = useCallback(async () => { + if (nutritionReviewApplier === null) { + return { ok: false, applied: false, message: 'No current nutrition review is available to apply.' }; + } + return nutritionReviewApplier(); + }, [nutritionReviewApplier]); const runNutritionAnalysis = useCallback(async (): Promise => { if (nutritionAnalysisRunner === null) { return { ok: false, contributionCount: 0, message: 'SHISO nutrition analysis is not available right now. You can calculate without AI.' }; @@ -417,6 +441,32 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode turn: 0, }); } + if (via === 'standing_nutrition') { + if ( + typeof request?.recipe_identity !== 'string' || request.recipe_identity.length === 0 || + typeof request.vault_scope !== 'string' || request.vault_scope.length === 0 || + request.nutrition_applied !== true + ) { + return { + ok: false, + saved: false, + reason_code: 'not_authorized', + message: 'Standing nutrition authority was not valid for this recipe and Vault. Nothing was saved.', + }; + } + try { + return await recipeEditApplier.save({ + authorized: true, + via: 'standing_nutrition', + recipe_identity: request.recipe_identity, + vault_scope: request.vault_scope, + turn: request.turn ?? 0, + nutrition_applied: true, + }); + } catch { + return { ok: false, saved: false, reason_code: 'write_failed', message: 'The recipe could not be saved.' }; + } + } // Assistant path: require a CURRENT, unconsumed authorization issued from // THE USER'S OWN MESSAGE of this turn. No authorization means no write. const decision = beginSaveAuthorization(saveAuthorizationRef.current); @@ -501,6 +551,9 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode runAnalysis, canRunAnalysis: analysisApplier !== null, registerAnalysisApplier, + applyNutritionReview, + canApplyNutritionReview: nutritionReviewApplier !== null, + registerNutritionReviewApplier, applyIngredientEdits, canApplyIngredientEdits: recipeEditApplier !== null, registerRecipeEditApplier, @@ -522,7 +575,8 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode open, openForNutritionAnalysis, state.nutritionAnalysisRequest, runNutritionAnalysis, registerNutritionAnalysisRunner, close, state.open, state.source, publishNutrition, snapshot, applyProposal, applier, registerApplier, runAnalysis, analysisApplier, - registerAnalysisApplier, applyIngredientEdits, recipeEditApplier, + registerAnalysisApplier, applyNutritionReview, nutritionReviewApplier, registerNutritionReviewApplier, + applyIngredientEdits, recipeEditApplier, registerRecipeEditApplier, saveWorkingRecipe, issueSaveAuthorizationEntry, clearSaveAuthorizationEntry, discardWorkingRecipe, workingRecipe, publishWorkingRecipe, applyNutritionCorrections, diff --git a/src/application/nutritionChangeHistory.ts b/src/application/nutritionChangeHistory.ts new file mode 100644 index 0000000..09dc514 --- /dev/null +++ b/src/application/nutritionChangeHistory.ts @@ -0,0 +1,55 @@ +import type { ObsidianRecipe } from '../types'; +import { decodeCodexNutrition } from '../core/nutritionV2/validate'; + +export const SHISO_NUTRITION_HISTORY_SETTING = 'shiso_nutrition_change_history_v1'; +export const MAX_SHISO_NUTRITION_HISTORY = 20; + +export interface ShisoNutritionChangeRecord { + readonly id: string; + readonly vault_scope: string; + readonly recipe_identity: string; + readonly recipe_title: string; + readonly changed_at: string; + readonly reason: string; + readonly evidence: string; + readonly previous: ObsidianRecipe['codexNutrition']; + readonly next: ObsidianRecipe['codexNutrition']; +} + +export function parseNutritionChangeHistory(value: unknown): readonly ShisoNutritionChangeRecord[] { + if (!Array.isArray(value)) return []; + return Object.freeze(value.flatMap((item) => { + if (item === null || typeof item !== 'object' || Array.isArray(item)) return []; + const record = item as Record; + if ( + typeof record['id'] !== 'string' || record['id'].length > 160 || + typeof record['vault_scope'] !== 'string' || !/^vault:[0-9a-f]{64}$/.test(record['vault_scope']) || + typeof record['recipe_identity'] !== 'string' || record['recipe_identity'].length === 0 || record['recipe_identity'].length > 500 || + typeof record['recipe_title'] !== 'string' || record['recipe_title'].length > 300 || + typeof record['changed_at'] !== 'string' || Number.isNaN(Date.parse(record['changed_at'])) || + typeof record['reason'] !== 'string' || record['reason'].length > 500 || + typeof record['evidence'] !== 'string' || record['evidence'].length > 1000 + ) return []; + const previousDecoded = decodeCodexNutrition(record['previous']); + const nextDecoded = decodeCodexNutrition(record['next']); + if (previousDecoded.kind === 'malformed' || nextDecoded.kind === 'malformed' || nextDecoded.kind === 'none') return []; + return [{ + id: record['id'], + vault_scope: record['vault_scope'], + recipe_identity: record['recipe_identity'], + recipe_title: record['recipe_title'], + changed_at: record['changed_at'], + reason: record['reason'], + evidence: record['evidence'], + previous: previousDecoded.kind === 'none' ? undefined : previousDecoded.value, + next: nextDecoded.value, + }]; + }).slice(-MAX_SHISO_NUTRITION_HISTORY)); +} + +export function appendNutritionChange( + history: readonly ShisoNutritionChangeRecord[], + record: ShisoNutritionChangeRecord, +): readonly ShisoNutritionChangeRecord[] { + return Object.freeze([...history.filter((item) => item.id !== record.id), record].slice(-MAX_SHISO_NUTRITION_HISTORY)); +} diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index 36e7c35..a6bf382 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -196,6 +196,10 @@ export interface ShisoTurnDeps { readonly retry?: boolean; /** Application-produced note about unsaved working changes. */ readonly workingStateNote?: string; + /** Trusted UI policy; model prose cannot enable or override it. */ + readonly nutritionAuthority?: { + readonly enabled: boolean; + }; /** * C1.7 S5: optional, read-only progress notifications for REAL engine steps. * No token-level or speculative updates; the UI must not imply streaming. @@ -462,6 +466,22 @@ export async function runShisoConversationTurn( const notes = Array.isArray(data['notes']) ? data['notes'].filter((note): note is string => typeof note === 'string').slice(0, 3) : []; + const alternativeSummary = Array.isArray(data['alternative_scenarios']) + ? data['alternative_scenarios'].slice(0, 3).flatMap((scenario) => { + if (scenario === null || typeof scenario !== 'object' || Array.isArray(scenario)) return []; + const branches = (scenario as Record)['branches']; + if (!Array.isArray(branches)) return []; + const labels = branches.slice(0, 4).flatMap((branch) => { + if (branch === null || typeof branch !== 'object' || Array.isArray(branch)) return []; + const value = branch as Record; + if (typeof value['name'] !== 'string') return []; + const grams = typeof value['resolved_grams'] === 'number' ? `, ${value['resolved_grams']} g` : ', unresolved'; + const fdc = typeof value['fdc_id'] === 'number' ? `, FDC ${value['fdc_id']}` : ''; + return [`${value['name']}${fdc}${grams}`]; + }); + return labels.length > 0 ? [`Alternative scenarios (not combined): ${labels.join(' versus ')}.`] : []; + }).join(' ') + : ''; const steps = Array.isArray(data['steps']) ? data['steps'] : []; const aiStep = steps.find((step) => step !== null && typeof step === 'object' && !Array.isArray(step) && (step as Record)['stage'] === 'ai_estimate') as Record | undefined; const aiFailed = aiStep?.['attempted'] === true && (aiStep?.['selected'] ?? 0) === 0; @@ -478,26 +498,67 @@ export async function runShisoConversationTurn( typeof nutrientCoverage === 'object' && !Array.isArray(nutrientCoverage) && typeof (nutrientCoverage as Record)['gap_lines_examined'] === 'number'; + const requiresAlternativeChoice = Array.isArray(data['alternative_scenarios']) && + data['alternative_scenarios'].some((scenario) => + scenario !== null && typeof scenario === 'object' && !Array.isArray(scenario) && + (scenario as Record)['definitive_choice_required'] === true + ); + // `complete_nutrition` is deliberately honest about its own unsaved stage, + // but that sentence must not survive into a final response after a later + // Apply/Save transaction succeeds. The transaction outcome below is the + // sole persistence claim in the delivered message. + const calculatedSummary = summary.replace(/\s*Nothing was applied or saved\.\s*$/i, '').trim(); + let persistenceMessage = requiresAlternativeChoice + ? 'An equal ingredient alternative still needs your choice. Select the branch actually used before Apply or Save. Nothing was applied or saved.' + : 'Calculated only: the prepared contributions remain in the UNSAVED Advanced Nutrition review. Nothing was applied or saved.'; + const shortcutTools = ['complete_nutrition']; + let shortcutState = working; + if (!requiresAlternativeChoice && result.ok && deps.nutritionAuthority?.enabled === true && classifySaveIntent(trimmed).reason !== 'save_negated') { + shortcutTools.push('apply_nutrition_review'); + const applied = await executeShisoTool({ tool: 'apply_nutrition_review' }, deps.toolContext, deps.signal); + const appliedSummary = applied.ok ? applied.summary : (applied as Extract).message; + shortcutState = recordFinding(shortcutState, { + tool: applied.tool, + ok: applied.ok, + summary: appliedSummary, + }); + if (applied.ok) { + shortcutTools.push('save_working_recipe'); + const saved = await executeShisoTool({ tool: 'save_working_recipe' }, deps.toolContext, deps.signal); + const savedSummary = saved.ok ? saved.summary : (saved as Extract).message; + shortcutState = recordFinding(shortcutState, { + tool: saved.tool, + ok: saved.ok, + summary: savedSummary, + }); + persistenceMessage = saved.ok && saved.data['saved'] === true + ? 'Standing nutrition authority applied the reviewed result and the canonical Vault save confirmed persistence.' + : `The review was applied to the working recipe, but Vault persistence was not confirmed: ${savedSummary}`; + } else { + persistenceMessage = `Standing nutrition authority could not apply this review: ${appliedSummary} Nothing was saved.`; + } + } const message = result.ok ? isNutrientGapPass - ? `${summary}${notes.length > 0 ? ` Notes: ${notes.join(' ')}` : ''}` + ? `${calculatedSummary}${notes.length > 0 ? ` Notes: ${notes.join(' ')}` : ''}${alternativeSummary.length > 0 ? ` ${alternativeSummary}` : ''} ${persistenceMessage}` : `I completed a bounded source-first pass: ${resolvedNew} of ${initialUnresolved} previously unresolved line(s) resolved; ` + `${accounted} of ${total} ingredient lines covered (${sourceBreakdown}). ` + `${remaining > 0 ? `${remaining} still need attention. ` : 'Every ingredient line is accounted for. '}` + `${partialKnown > 0 ? `${partialKnown} line(s) retain unknown nutrients. ` : ''}` + `${aiFailed && aiFailureNote ? `No AI nutrition estimate was confirmed. ${aiFailureNote} ` : ''}` + `${notes.length > 0 && !aiFailed ? `Source notes: ${notes.join(' ')} ` : ''}` + - `The prepared contributions are in the UNSAVED Advanced Nutrition review; inspect assumptions and unknown values before Apply. Nothing was applied or saved.` + `${alternativeSummary.length > 0 ? `${alternativeSummary} ` : ''}` + + persistenceMessage : `${summary} No ingredient edits or saves were made.`; const nextState = result.ok - ? recordFinding(appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 }), { tool: result.tool, ok: true, summary: result.summary }) - : appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 }); + ? recordFinding(appendShisoMessage(shortcutState, { role: 'assistant', text: message, proposalCount: 0 }), { tool: result.tool, ok: true, summary: result.summary }) + : appendShisoMessage(shortcutState, { role: 'assistant', text: message, proposalCount: 0 }); return { ok: true, state: nextState, message, status: null, - toolsUsed: Object.freeze(['complete_nutrition']) as readonly string[], + toolsUsed: Object.freeze(shortcutTools) as readonly string[], }; } diff --git a/src/application/shisoTools.ts b/src/application/shisoTools.ts index 78ca5bf..d4cf86e 100644 --- a/src/application/shisoTools.ts +++ b/src/application/shisoTools.ts @@ -35,8 +35,10 @@ import { type ShisoIngredientEditArgs, } from '../core/shiso/protocol'; import { runBatchInvestigation } from '../core/shiso/batchInvestigation'; +import { projectIngredientAlternatives } from '../core/nutritionV2/matching/query'; -import type { AdvancedNutritionSession } from '../core/nutritionV2/phase4'; +import { adaptRecipe, analyzeRecipe, type AdvancedNutritionSession } from '../core/nutritionV2/phase4'; +import { buildPortionChoice } from '../core/nutritionV2/phase4/portion'; import { buildBrandedContribution, type BrandedLookupTarget, @@ -310,6 +312,152 @@ function nutritionMatchesActiveRecipe(ctx: ShisoToolContext): boolean { return recipeSet.size === recipeRefs.length && ctx.nutrition.rows.every((row) => recipeSet.has(row.line_ref)); } +function authenticatedAlternativeScenarios(ctx: ShisoToolContext): readonly Record[] { + if (ctx.session === null || ctx.recipe === null) return []; + const scenarios: Record[] = []; + for (const line of ctx.recipe.ingredients) { + if (typeof line.line_ref !== 'string') continue; + const projected = projectIngredientAlternatives(line.text); + if (projected === null) continue; + const branches = projected.alternatives.slice(0, 4).map((name, index) => { + const branchReview = ctx.session!.reviewIngredient({ name }); + const queryTokens = new Set(name.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).map((token) => token.replace(/s$/, ''))); + const requestedUnit = (line.unit ?? '').toLowerCase().replace(/s$/, ''); + const rankedSearch = ctx.session!.searchFoods(name, 12); + const portionCompatible = (rankedSearch.ok ? rankedSearch.results : branchReview.candidates).find((candidate) => { + const candidateTokens = candidate.description.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).map((token) => token.replace(/s$/, '')); + if (candidateTokens.length > queryTokens.size + 1 || ![...queryTokens].every((token) => candidateTokens.includes(token))) return false; + const portions = ctx.session!.reviewPortions(candidate.fdc_id); + return portions.ok && portions.review.candidates.some((portion) => + portion.kind !== 'unusable' && + portion.gram_weight > 0 && + (requestedUnit.length === 0 || portion.unit?.replace(/s$/, '') === requestedUnit), + ); + }); + // Once the bounded identity + requested-portion policy has selected a + // genuine catalogue candidate, re-enter it through the existing exact + // FDC lookup authority. A `manual` selection would falsely describe an + // autonomous choice as user-confirmed, while `ai_assisted` is reserved + // for the base matcher's own unique deterministic acceptance. + const scenarioQuery = portionCompatible === undefined + ? name + : String(portionCompatible.fdc_id); + const ingredient = { + original: `${line.amount ?? ''} ${line.unit ?? ''} ${name}`.trim(), + amount: line.amount ?? null, + unit: line.unit ?? '', + name, + }; + const review = ctx.session!.reviewIngredient(ingredient); + const scenarioLineRef = `${line.line_ref}:alternative:${index}`; + const exactPortions = portionCompatible === undefined + ? [] + : ctx.session!.reviewPortions(portionCompatible.fdc_id); + const portionIndex = exactPortions && 'ok' in exactPortions && exactPortions.ok + ? exactPortions.review.candidates.find((portion) => + portion.kind !== 'unusable' && + portion.gram_weight > 0 && + (requestedUnit.length === 0 || portion.unit?.replace(/s$/, '') === requestedUnit), + )?.index + : undefined; + const selection = portionCompatible === undefined + ? undefined + : { + kind: 'manual' as const, + fdc_id: portionCompatible.fdc_id, + record_digest: portionCompatible.record_digest, + catalog_digest: ctx.session!.metadata().catalog_digest, + line_ref: scenarioLineRef, + review_digest: review.review_digest, + ai_assisted: true, + }; + const portionChoice = selection !== undefined && portionIndex !== undefined + ? buildPortionChoice(ctx.session!, { + lineRef: scenarioLineRef, + ingredient, + review, + selection, + fdcId: portionCompatible!.fdc_id, + portionIndex, + }) + : null; + const selectedCalculation = portionChoice?.ok + ? ctx.session!.calculate({ + servings: ctx.recipe!.servings ?? 1, + nutrient_scope: Object.keys(NUTRIENT_REGISTRY) as NutrientId[], + ingredients: [{ + line_ref: scenarioLineRef, + ingredient, + selection, + portion_selection: portionChoice.choice.selection, + }], + }) + : null; + const adaptation = selectedCalculation?.ok ? null : adaptRecipe({ + title: `Alternative scenario: ${scenarioQuery}`, + servings: ctx.recipe!.servings ?? 1, + ingredients: [{ ...ingredient, name: scenarioQuery, original: `${line.amount ?? ''} ${line.unit ?? ''} ${scenarioQuery}`.trim() }], + }); + const analysis = adaptation?.ok + ? analyzeRecipe(ctx.session!, adaptation.recipe.adapted, adaptation.recipe.base_servings) + : null; + const preview = selectedCalculation?.ok ? selectedCalculation.preview : analysis?.preview; + if (preview === undefined) { + return { + name, + primary: projected.primary_index === index, + resolved: false, + reason: 'The authenticated calculator could not resolve this branch without an unsupported assumption.', + diagnostic: portionChoice === null + ? 'no_compatible_source_portion' + : 'failure' in portionChoice + ? portionChoice.failure.code + : selectedCalculation !== null && 'failure' in selectedCalculation + ? selectedCalculation.failure.code + : 'analysis_unresolved', + candidates: review.outcome === 'review_required' + ? review.candidates.slice(0, 4).map((candidate) => ({ fdc_id: candidate.fdc_id, description: candidate.description })) + : [], + }; + } + const evidence = preview.ingredients[0]; + const source = portionCompatible ?? (review.outcome === 'matched_exact' + ? review.candidates.find((candidate) => candidate.fdc_id === review.selected_fdc_id) + : undefined); + const resolved = evidence?.outcome === 'calculated' && evidence.fdc_id !== undefined && evidence.resolved_grams !== undefined; + return { + name, + primary: projected.primary_index === index, + resolved, + fdc_id: evidence?.fdc_id ?? null, + source_description: source?.description ?? null, + resolved_grams: evidence?.resolved_grams ?? null, + mass_source: evidence?.mass_source ?? null, + provenance: resolved ? 'authenticated_usda_scenario' : 'unresolved', + totals: Object.fromEntries(Object.entries(preview.totals).map(([nutrient, total]) => [nutrient, total === undefined ? null : { + amount: total.amount, + unit: total.unit, + status: total.status, + coverage: total.coverage, + }])), + reason: resolved ? null : 'This branch remains unresolved; it is not included in a definitive recipe total.', + }; + }); + scenarios.push({ + line_ref: line.line_ref, + ingredient: line.text.slice(0, 200), + mutually_exclusive: true, + primary_index: projected.primary_index, + definitive_choice_required: projected.primary_index === null, + branches, + note: projected.primary_index === null + ? 'These alternatives are equal authored choices. Select one before saving definitive nutrition.' + : 'The first branch is the as-written primary scenario; alternate totals remain separate.', + }); + } + return Object.freeze(scenarios.slice(0, 8)); +} + function getNutritionReview(ctx: ShisoToolContext, includeIngredients: boolean): ShisoObservation { const n = ctx.nutrition; if (n === null) { @@ -346,6 +494,7 @@ function getNutritionReview(ctx: ShisoToolContext, includeIngredients: boolean): review_suggested: coverage.review_suggested, counts_reconcile: coverage.reconciled, coverage_summary: nutritionCoverageSummary(coverage), + alternative_scenarios: authenticatedAlternativeScenarios(ctx), }; if (includeIngredients) { data['ingredients'] = n.rows.slice(0, 60).map((r) => { @@ -2484,7 +2633,16 @@ export function executeShisoTool( case 'run_nutrition_analysis': return runNutritionAnalysis(ctx, signal); case 'complete_nutrition': - return completeNutrition(ctx, signal); + return completeNutrition(ctx, signal).then((completed) => { + if (!completed.ok) return completed; + const alternativeScenarios = authenticatedAlternativeScenarios(ctx); + if (alternativeScenarios.length === 0) return completed; + return ok( + 'complete_nutrition', + `${completed.summary} ${alternativeScenarios.length} mutually exclusive ingredient comparison(s) were calculated separately; alternatives were not combined.`, + { ...completed.data, alternative_scenarios: alternativeScenarios }, + ); + }); case 'get_capability_status': return getCapabilityStatus(ctx); case 'apply_ingredient_edits': diff --git a/src/components/AdvancedNutritionCard.tsx b/src/components/AdvancedNutritionCard.tsx index f1056dc..343cddc 100644 --- a/src/components/AdvancedNutritionCard.tsx +++ b/src/components/AdvancedNutritionCard.tsx @@ -162,6 +162,15 @@ interface AdvancedNutritionCardProps { onLoadBundle?: () => void; /** Explicit Phase 5B Apply handler. Absent when no write path is wired. */ onApplyAdvancedNutrition?: AdvancedNutritionApplyHandler; + /** Vault-scoped, persistent opt-in. It authorizes nutrition Apply+Save only. */ + nutritionAuthority?: { + readonly enabled: boolean; + readonly available: boolean; + /** Exact active recipe/Vault bindings used by the existing standing save grant. */ + readonly recipeIdentity?: string; + readonly vaultScope?: string; + readonly onChange: (enabled: boolean) => Promise | void; + }; /** * The ALREADY-VALIDATED saved Advanced block, supplied by the consolidated * nutrition section. The saved report renders from this alone; no USDA @@ -570,6 +579,7 @@ export const AdvancedNutritionCard: React.FC = ({ bundleStatus, onLoadBundle, onApplyAdvancedNutrition, + nutritionAuthority, savedAdvancedBlock, onResolveWithAi, onResolveWithAiFirst, @@ -582,6 +592,9 @@ onReviewRecipeContextWithAi, }) => { const servingBasisAssumed = !(typeof recipe.servings === 'number' && Number.isFinite(recipe.servings) && recipe.servings > 0); const shiso = useShiso(); + const standingNutritionEnabled = nutritionAuthority?.enabled === true; + const standingNutritionRecipeIdentity = nutritionAuthority?.recipeIdentity ?? ''; + const standingNutritionVaultScope = nutritionAuthority?.vaultScope ?? ''; const nutritionUnsaved = shiso.workingRecipe?.nutrition_unsaved === true; // Product entitlement is independent of provider readiness. `unknown` fails // closed until the server-owned product read completes. @@ -611,6 +624,8 @@ onReviewRecipeContextWithAi, const [appliedNutritionSaved, setAppliedNutritionSaved] = useState(false); const [analysisRuns, setAnalysisRuns] = useState(0); const [shisoNutritionState, setShisoNutritionState] = useState({ kind: 'idle', message: null }); + const [standingTransactionPending, setStandingTransactionPending] = useState(false); + const standingTransactionSeq = useRef(0); const shisoNutritionRunningRef = useRef(false); const [state, dispatch] = useReducer(phase4Reducer, INITIAL_PHASE4_STATE); /** @@ -1300,6 +1315,66 @@ onReviewRecipeContextWithAi, : { kind: 'error', message: result.message }); }; + // The always-mounted card owns the live Phase 4 reducer. Register its exact + // Phase 5 Apply operation so SHISO cannot observe this review and then try to + // apply a separate or absent application-controller snapshot. + const shisoRegisterNutritionReviewApplier = shiso.registerNutritionReviewApplier; + const shisoNutritionReviewApplyRef = useRef({ + onApplyAdvancedNutrition, + session, + adaptationOk: adaptation.ok, + applyEligibility, + applyMode, + aiReviews, + recipe, + state, + }); + shisoNutritionReviewApplyRef.current = { + onApplyAdvancedNutrition, + session, + adaptationOk: adaptation.ok, + applyEligibility, + applyMode, + aiReviews, + recipe, + state, + }; + const canRegisterNutritionReviewApplier = + Boolean(onApplyAdvancedNutrition) && Boolean(session) && adaptation.ok && applyEligibility === true && applyMode !== null; + useEffect(() => { + if (!canRegisterNutritionReviewApplier) { + return undefined; + } + return shisoRegisterNutritionReviewApplier(async () => { + 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 reviewReasons: Record = {}; + for (const [lineRef, review] of Object.entries(currentAiReviews)) { + if (review.decision === 'needs_review') reviewReasons[lineRef] = 'needs_review'; + } + const result = await apply({ + session: currentSession, + recipe: currentRecipe, + state: currentState, + expectedMode: mode, + ...(Object.keys(reviewReasons).length > 0 ? { reviewReasons } : {}), + }); + return { ok: result.ok, applied: result.ok, message: result.message }; + }); + }, [canRegisterNutritionReviewApplier, shisoRegisterNutritionReviewApplier]); + const applyUi: AdvancedNutritionApplyUi | undefined = onApplyAdvancedNutrition ? { eligible: applyEligibility, @@ -1819,14 +1894,14 @@ onReviewRecipeContextWithAi, return map; }, [liveRows]); - const handleAnalyze = () => { - if (!session || !adaptation.ok) return; + const handleAnalyze = (): RecipeAnalysis | null => { + if (!session || !adaptation.ok) return null; // Always execute a fresh analysis on click. Fall back to an on-demand // computation if the memoized analysis is unavailable, so the control can // never become a dead button after a saved-state reopen. const current = analysis ?? analyzeRecipeFromRows(session, adapted, rows, adaptation.recipe.base_servings); - if (!current) return; + if (!current) return null; // REVIEWED-DECISION PRESERVATION. Re-analysis is a gap-filling pass, never a // destructive reset: every explicit user choice (a manual/USDA-search @@ -1932,6 +2007,7 @@ onReviewRecipeContextWithAi, setAiEstimateEvidence({}); setGenerateAiFeedback(null); setAiMessage(null); + return current; }; const compact = display @@ -2500,28 +2576,28 @@ onReviewRecipeContextWithAi, }); return; } - if (onResolveWithAiFirst === undefined) { - setGenerateAiFeedback({ - kind: 'unavailable', - message: 'SHISO whole-recipe analysis is unavailable in this build. Deterministic review remains available.', - }); - return; - } - if (!aiAvailabilityAvailable) { - setGenerateAiFeedback({ - kind: 'unavailable', - message: - aiAvailabilityReason ?? - 'AI Advanced Nutrition is unavailable. Deterministic analysis is ready without AI.', - }); + if (onResolveWithAiFirst === undefined || !aiAvailabilityAvailable) { + if (shisoNutritionRunningRef.current) return; + shisoNutritionRunningRef.current = true; + setShisoNutritionState({ kind: 'running', message: 'SHISO is running the authenticated USDA-only review…' }); + const local = handleAnalyze(); + const limitation = aiAvailabilityReason ?? (onResolveWithAiFirst === undefined + ? 'AI whole-recipe interpretation is not available in this build.' + : 'The selected AI connection is unavailable.'); + const message = local + ? `${limitation} SHISO completed the authenticated USDA-only analysis instead. Review the source matches and unresolved lines below; nothing was applied or saved.` + : `${limitation} The USDA-only analysis could not initialize. Load the authenticated USDA catalog and retry.`; + setGenerateAiFeedback({ kind: local ? 'partial' : 'error', message }); + setShisoNutritionState({ kind: local ? 'success' : 'error', message }); + if (local && standingNutritionEnabled) setStandingTransactionPending(true); + shisoNutritionRunningRef.current = false; return; } if (shisoNutritionRunningRef.current) return; if (actionableRows.length === 0) { - setGenerateAiFeedback({ - kind: 'success', - message: 'The deterministic review resolved every ingredient. No AI interpretation was needed.', - }); + const message = 'The deterministic review resolved every ingredient. No AI interpretation was needed.'; + setGenerateAiFeedback({ kind: 'success', message }); + if (standingNutritionEnabled) setStandingTransactionPending(true); return; } shisoNutritionRunningRef.current = true; @@ -2559,6 +2635,7 @@ onReviewRecipeContextWithAi, ? { kind: 'success', message: `${outcome.message} Review before Apply. Nothing was saved.` } : { kind: 'error', message: outcome.message } ); + if (outcome.ok && standingNutritionEnabled) setStandingTransactionPending(true); } catch { if (identityRef.current.recipeKey === recipeKey && isOpenRef.current) { setGenerateAiFeedback({ @@ -2583,8 +2660,68 @@ onReviewRecipeContextWithAi, aiAvailabilityReason, actionableRows.length, handleResolveWithAi, + handleAnalyze, + standingNutritionEnabled, ]); + // With standing nutrition authority enabled, the Analyze button owns the + // complete authorized transaction. This effect waits for the same reducer + // state and Phase 5 Apply owner used by the visible Apply control to publish + // after analysis has committed. Equal authored alternatives leave + // applyEligibility false and stop here, asking for the real user choice. + useEffect(() => { + if (!standingTransactionPending || !standingNutritionEnabled) return undefined; + if (!session || !adaptation.ok || applyEligibility === null) return undefined; + if (applyEligibility !== true) { + setStandingTransactionPending(false); + const message = 'Standing nutrition authority is enabled, but an equal ingredient alternative still needs your choice. Nothing was applied or saved.'; + setShisoNutritionState({ kind: 'error', message }); + setGenerateAiFeedback({ kind: 'partial', message }); + return undefined; + } + if (!shiso.canApplyNutritionReview) return undefined; + const seq = standingTransactionSeq.current + 1; + standingTransactionSeq.current = seq; + setStandingTransactionPending(false); + void (async () => { + setShisoNutritionState({ kind: 'running', message: 'SHISO is applying the verified review and saving it to the active Vault…' }); + const applied = await shiso.applyNutritionReview(); + if (standingTransactionSeq.current !== seq) return; + if (!applied.ok || !applied.applied) { + const message = `Standing nutrition authority could not Apply this review: ${applied.message} Nothing was saved.`; + setShisoNutritionState({ kind: 'error', message }); + setGenerateAiFeedback({ kind: 'error', message }); + return; + } + const recipeIdentity = standingNutritionRecipeIdentity; + const vaultScope = standingNutritionVaultScope; + if (recipeIdentity.length === 0 || vaultScope.length === 0) { + const message = 'The review was applied, but the exact recipe/Vault save binding was unavailable. Nothing was saved.'; + setShisoNutritionState({ kind: 'error', message }); + setGenerateAiFeedback({ kind: 'error', message }); + return; + } + const saved = await shiso.saveWorkingRecipe({ + via: 'standing_nutrition', + recipe_identity: recipeIdentity, + vault_scope: vaultScope, + nutrition_applied: true, + }); + if (standingTransactionSeq.current !== seq) return; + const message = saved.ok && saved.saved + ? `SHISO applied the verified nutrition review and saved it to the active Vault. ${saved.message}` + : `SHISO applied the verified nutrition review, but it was not saved: ${saved.message}`; + setShisoNutritionState({ kind: saved.ok && saved.saved ? 'success' : 'error', message }); + setGenerateAiFeedback({ kind: saved.ok && saved.saved ? 'success' : 'error', message }); + })().catch(() => { + if (standingTransactionSeq.current !== seq) return; + const message = 'SHISO applied no persistent nutrition change because the authorized save failed. Nothing was saved.'; + setShisoNutritionState({ kind: 'error', message }); + setGenerateAiFeedback({ kind: 'error', message }); + }); + return undefined; + }, [adaptation, applyEligibility, session, shiso, standingNutritionEnabled, standingNutritionRecipeIdentity, standingNutritionVaultScope, standingTransactionPending]); + /** * AN-WEB-1 — explicit external research for locally unresolved, non-ambiguous * lines. Research never decides a salted/unsalted/brand ambiguity: only @@ -3783,6 +3920,7 @@ onReviewRecipeContextWithAi, analysis={analysis} onAnalyze={handleAnalyze} onAnalyzeRecipe={() => { void handleAnalyzeNutritionWithShiso(); }} + nutritionAuthority={nutritionAuthority} shisoAnalysisState={shisoNutritionState} analysisRuns={analysisRuns} apply={applyUi} diff --git a/src/components/AdvancedNutritionModal.tsx b/src/components/AdvancedNutritionModal.tsx index bba1f9d..e77e44e 100644 --- a/src/components/AdvancedNutritionModal.tsx +++ b/src/components/AdvancedNutritionModal.tsx @@ -315,6 +315,11 @@ interface AdvancedNutritionModalProps { /** Runs the registered, recipe-bound SHISO structured nutrition request. */ onAnalyzeRecipe?: () => void; shisoAnalysisState?: { readonly kind: 'idle' | 'running' | 'success' | 'error'; readonly message: string | null }; + nutritionAuthority?: { + readonly enabled: boolean; + readonly available: boolean; + readonly onChange: (enabled: boolean) => Promise | void; + }; /** Number of analyzer runs in this modal session (visible feedback). */ analysisRuns?: number; /** True when the working review diverges from the saved Advanced result. */ @@ -1136,6 +1141,7 @@ export const AdvancedNutritionModal: React.FC = ({ onAnalyze, onAnalyzeRecipe = () => {}, shisoAnalysisState = { kind: 'idle', message: null }, + nutritionAuthority, analysisRuns = 0, workingDirty = false, hydratedFromSaved = false, @@ -2158,7 +2164,9 @@ export const AdvancedNutritionModal: React.FC = ({

Intelligent completion

Analyze with SHISO

- Runs the genuine whole-recipe AI-first workflow only when you explicitly choose it. SHISO proposes; the local USDA catalog and calculator verify; nothing is saved until Apply. + {nutritionAuthority?.enabled + ? 'Runs the verified whole-recipe workflow and saves through the active Vault authority after analysis. Equal ingredient choices still require your selection.' + : 'Runs the genuine whole-recipe AI-first workflow only when you explicitly choose it. SHISO proposes; the local USDA catalog and calculator verify; nothing is saved until Apply.'}

@@ -2166,7 +2174,7 @@ export const AdvancedNutritionModal: React.FC = ({ type="button" data-testid="advanced-nutrition-analyze-with-shiso" onClick={onAnalyzeRecipe} - disabled={shisoAnalysisState.kind === 'running' || (ai !== undefined && ai.available === false)} + disabled={shisoAnalysisState.kind === 'running'} aria-describedby="advanced-nutrition-shiso-status" className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg bg-amber-500 px-4 text-[14px] font-semibold text-black transition-colors hover:bg-amber-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring,#F59E0B)] disabled:cursor-not-allowed disabled:opacity-50" > @@ -2190,8 +2198,30 @@ export const AdvancedNutritionModal: React.FC = ({ aria-live="polite" className={`text-[14px] ${shisoAnalysisState.kind === 'error' ? 'text-[var(--text-primary,#F3F4F6)]' : shisoAnalysisState.kind === 'success' ? 'text-[var(--text-primary,#F3F4F6)]' : 'text-[var(--text-secondary,#9CA3AF)]'}`} > - {shisoAnalysisState.message ?? (shisoAnalysisState.kind === 'idle' ? 'Analysis creates a review only. Apply and Vault saving are separate steps.' : '')} + {shisoAnalysisState.message ?? (shisoAnalysisState.kind === 'idle' + ? nutritionAuthority?.enabled + ? 'SHISO will automatically apply and save eligible nutrition results. Unresolved ingredient choices or failed verification will prevent saving.' + : 'Analysis creates a working review only. Apply and Vault saving are separate steps.' + : '')}

+ {nutritionAuthority && ( + + )}
{analysis && ( diff --git a/src/components/RecipeDetailView.tsx b/src/components/RecipeDetailView.tsx index b715ff3..32d57c1 100644 --- a/src/components/RecipeDetailView.tsx +++ b/src/components/RecipeDetailView.tsx @@ -117,6 +117,13 @@ interface RecipeDetailViewProps { advancedNutritionAiAvailability?: AdvancedNutritionAiAvailability; /** Explicit Phase 5B Apply handler (browser shell only). */ onApplyAdvancedNutrition?: AdvancedNutritionApplyHandler; + nutritionAuthority?: { + readonly enabled: boolean; + readonly available: boolean; + readonly recipeIdentity?: string; + readonly vaultScope?: string; + readonly onChange: (enabled: boolean) => Promise | void; + }; /** Optional AI-assisted USDA resolution port (browser shell only). */ onResolveAdvancedNutritionAi?: AdvancedNutritionAiResolveHandler; /** Optional AI-FIRST Generate resolution port (browser shell only). */ @@ -159,6 +166,7 @@ export function RecipeDetailView({ onLoadAdvancedNutritionBundle, advancedNutritionAiAvailability, onApplyAdvancedNutrition, + nutritionAuthority, onResolveAdvancedNutritionAi, onResolveAdvancedNutritionAiFirst, onResearchAdvancedNutritionAi, @@ -1100,6 +1108,7 @@ export function RecipeDetailView({ advancedNutritionBundleStatus={advancedNutritionBundleStatus} onLoadAdvancedNutritionBundle={onLoadAdvancedNutritionBundle} onApplyAdvancedNutrition={onApplyAdvancedNutrition} + nutritionAuthority={nutritionAuthority} onResolveAdvancedNutritionAi={onResolveAdvancedNutritionAi} onResolveAdvancedNutritionAiFirst={onResolveAdvancedNutritionAiFirst} onResearchAdvancedNutritionAi={onResearchAdvancedNutritionAi} diff --git a/src/components/RecipeNutritionSection.tsx b/src/components/RecipeNutritionSection.tsx index 4067436..e9e3d73 100644 --- a/src/components/RecipeNutritionSection.tsx +++ b/src/components/RecipeNutritionSection.tsx @@ -32,6 +32,13 @@ interface RecipeNutritionSectionProps { /** AI-5C bounded AI presentation state; passed straight through to the card. */ advancedNutritionAiAvailability?: AdvancedNutritionAiAvailability; onApplyAdvancedNutrition?: AdvancedNutritionApplyHandler; + nutritionAuthority?: { + readonly enabled: boolean; + readonly available: boolean; + readonly recipeIdentity?: string; + readonly vaultScope?: string; + readonly onChange: (enabled: boolean) => Promise | void; + }; /** Optional AI-assisted USDA resolution port (injected by the shell). */ onResolveAdvancedNutritionAi?: AdvancedNutritionAiResolveHandler; /** Optional AI-FIRST Generate resolution port (injected by the shell). */ @@ -80,6 +87,7 @@ export const RecipeNutritionSection: React.FC = ({ onLoadAdvancedNutritionBundle, advancedNutritionAiAvailability, onApplyAdvancedNutrition, + nutritionAuthority, onResolveAdvancedNutritionAi, onResolveAdvancedNutritionAiFirst, onResearchAdvancedNutritionAi, @@ -249,6 +257,7 @@ export const RecipeNutritionSection: React.FC = ({ onLoadBundle={onLoadAdvancedNutritionBundle} advancedNutritionAiAvailability={advancedNutritionAiAvailability} onApplyAdvancedNutrition={onApplyAdvancedNutrition} + nutritionAuthority={nutritionAuthority} savedAdvancedBlock={presentation.advanced} onResolveWithAi={onResolveAdvancedNutritionAi} onResolveWithAiFirst={onResolveAdvancedNutritionAiFirst} diff --git a/src/components/ShisoModal.tsx b/src/components/ShisoModal.tsx index 5ff58e7..02badd7 100644 --- a/src/components/ShisoModal.tsx +++ b/src/components/ShisoModal.tsx @@ -110,6 +110,11 @@ export interface ShisoModalProps { readonly fileName?: unknown; readonly title?: unknown; } | null; + /** Persistent, user-controlled nutrition-only authority for the active Vault. */ + readonly nutritionAuthority?: { + readonly enabled: boolean; + readonly vaultScope: string; + }; readonly nutritionSession: AdvancedNutritionSession | null; readonly nutritionBundleStatus?: 'idle' | 'loading' | 'ready' | 'failed' | 'unsupported'; /** @@ -219,6 +224,7 @@ export function ShisoModal({ onVaultRecipeSelected, recipe, getSaveAuthorizationRecipe, + nutritionAuthority = { enabled: false, vaultScope: '' }, nutritionSession, nutritionBundleStatus, loadNutritionBundle, @@ -274,6 +280,13 @@ export function ShisoModal({ const shiso = useShiso(); const creationMode = shiso.source === 'create'; const seqRef = useRef(0); + const nutritionSavePolicyRef = useRef({ + turn: 0, + allowed: false, + applied: false, + recipeIdentity: '', + vaultScope: '', + }); const activeTurnControllerRef = useRef(null); const conversationRef = useRef(conversation); conversationRef.current = conversation; @@ -694,12 +707,33 @@ export function ShisoModal({ : undefined; }, get applyNutritionReview() { - return applyIndependentNutritionReview; + if (!shisoRef.current.canApplyNutritionReview && applyIndependentNutritionReview === undefined) return undefined; + return async () => { + const result = shisoRef.current.canApplyNutritionReview + ? await shisoRef.current.applyNutritionReview() + : await applyIndependentNutritionReview!(); + if (result.ok && result.applied) { + const policy = nutritionSavePolicyRef.current; + nutritionSavePolicyRef.current = { ...policy, applied: true }; + } + return result; + }; }, get saveWorkingRecipe() { - return shisoRef.current.canSaveWorkingRecipe - ? () => shisoRef.current.saveWorkingRecipe({ via: 'assistant' }) - : undefined; + if (!shisoRef.current.canSaveWorkingRecipe) return undefined; + return () => { + const policy = nutritionSavePolicyRef.current; + if (policy.allowed && policy.applied) { + return shisoRef.current.saveWorkingRecipe({ + via: 'standing_nutrition', + recipe_identity: policy.recipeIdentity, + vault_scope: policy.vaultScope, + turn: policy.turn, + nutrition_applied: true, + }); + } + return shisoRef.current.saveWorkingRecipe({ via: 'assistant' }); + }; }, // Lets Shiso clear the one genuine prerequisite itself, using the same // controller the user's own Load USDA data button calls. @@ -876,9 +910,20 @@ export function ShisoModal({ // authorization. The model never sees or influences this decision. const saveIntent = classifySaveIntent(message); const authorizationRecipe = getSaveAuthorizationRecipe?.() ?? recipe ?? selectedVaultRecipeContext(vaultCapabilities); + const authorizationRecipeIdentity = recipeIdentityOf(authorizationRecipe); + nutritionSavePolicyRef.current = { + turn: seq, + allowed: + nutritionAuthority.enabled && + nutritionAuthority.vaultScope.length > 0 && + saveIntent.reason !== 'save_negated', + applied: false, + recipeIdentity: authorizationRecipeIdentity, + vaultScope: nutritionAuthority.vaultScope, + }; shisoRef.current.issueSaveAuthorization({ authorized: saveIntent.authorized, - recipe_identity: recipeIdentityOf(authorizationRecipe), + recipe_identity: authorizationRecipeIdentity, turn: seq, }); @@ -910,6 +955,7 @@ export function ShisoModal({ signal: controller.signal, retry, ...(workingStateNote.length > 0 ? { workingStateNote } : {}), + nutritionAuthority: { enabled: nutritionAuthority.enabled }, // Read-only, real-step notifications. A superseded turn's steps are // ignored so a late callback cannot paint over the active turn. onProgress: (progress) => { @@ -976,6 +1022,7 @@ export function ShisoModal({ editableCreatedDraft, saveCreatedDraftNow, nutritionCoverage, effectiveNutritionSummary, workingStateNote, conversationLoading, getSaveAuthorizationRecipe, + nutritionAuthority.enabled, nutritionAuthority.vaultScope, ]); /** diff --git a/src/core/nutritionV2/calculation/calculate.ts b/src/core/nutritionV2/calculation/calculate.ts index d26475b..3c49a8a 100644 --- a/src/core/nutritionV2/calculation/calculate.ts +++ b/src/core/nutritionV2/calculation/calculate.ts @@ -24,7 +24,7 @@ import { isNutrientId, NUTRIENT_IDS, NUTRIENT_REGISTRY, type NutrientId } from ' import { isValidNutrientAmount, MAX_NUTRIENT_AMOUNT, type CanonicalUnit } from '../units'; import { normalizeQuery } from '../matching/normalize'; import { parseIngredient } from '../matching/parse'; -import { projectQueryText } from '../matching/query'; +import { projectIngredientAlternatives, projectQueryText } from '../matching/query'; import { confirmIngredientReview, reviewIngredient } from '../matching/review'; import { isDeterministicAutomaticSelection } from '../matching/confidence'; import type { ConfirmationResult, ReviewCatalog } from '../matching/types'; @@ -852,6 +852,24 @@ function evaluateIngredient( } } + // Authored equal alternatives are not a deterministic food choice. A + // matcher-selected candidate (including an automatic-selection claim) may + // be useful for investigation, but it must never enter definitive totals or + // Phase 5 until the user explicitly confirms one branch. The explicit + // `user_confirmed` 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') { + matched = false; + ambiguous = true; + fdcId = undefined; + recordDigest = undefined; + confirmationDigest = undefined; + manualRecordId = undefined; + manualRecordDigest = undefined; + matchStatus = 'none'; + } + // Resolve the current canonical record for a matched identity. let record: CanonicalUsdaFoodRecord | undefined; if (matched && fdcId !== undefined) { diff --git a/src/core/nutritionV2/matching/query.ts b/src/core/nutritionV2/matching/query.ts index ce6ca4a..f873bc4 100644 --- a/src/core/nutritionV2/matching/query.ts +++ b/src/core/nutritionV2/matching/query.ts @@ -2167,6 +2167,54 @@ export function queryParentheticalIdentityTokens(text: string): ReadonlyArray; + /** Index of the as-written primary branch; null means the author gave equal choices. */ + readonly primary_index: number | null; +} + +/** + * Projects an explicitly authored mutually-exclusive food choice without + * choosing it. `honey (or brown sugar)` has an as-written primary; `honey or + * brown sugar` is an equal choice. Quantities and preparation remain outside + * the branch identity and are supplied separately to the calculator. + */ +export function projectIngredientAlternatives(text: string): IngredientAlternativeProjection | null { + const bounded = String(text).normalize('NFKC').slice(0, 500); + const parenthetical = /\(\s*or\s+([^()]{1,160})\)/i.exec(bounded); + if (parenthetical) { + const primaryText = bounded.replace(parenthetical[0], ' '); + const primary = projectQueryText(primaryText).food_identity.trim(); + const alternate = projectQueryText(parenthetical[1] ?? '').food_identity.trim(); + if (primary.length > 0 && alternate.length > 0 && primary !== alternate) { + return Object.freeze({ alternatives: Object.freeze([primary, alternate]), primary_index: 0 }); + } + return null; + } + const directParts = bounded.split(/\s+or\s+/i); + if (directParts.length >= 2 && directParts.length <= 4) { + const stripLeadingMeasure = (value: string): string => value + .replace(/^\s*(?:\d+(?:\.\d+)?|\d+\s*\/\s*\d+|\d+\s+\d+\s*\/\s*\d+)\s*/, '') + .replace(/^\s*(?:cups?|tablespoons?|tbsp|teaspoons?|tsp|ounces?|oz|pounds?|lbs?|grams?|g|kilograms?|kg|milliliters?|ml|liters?|l)\b\s*/i, '') + .trim(); + const alternatives = directParts + .map((part, index) => projectQueryText(index === 0 ? stripLeadingMeasure(part) : part).food_identity.trim()) + .filter((branch, index, all) => branch.length > 0 && all.indexOf(branch) === index); + if (alternatives.length >= 2) { + return Object.freeze({ alternatives: Object.freeze(alternatives), primary_index: null }); + } + } + const projection = projectQueryText(bounded); + if (projection.alternative_groups.length < 2) return null; + const alternatives = projection.alternative_groups + .map((branch) => branch.join(' ').trim()) + .filter((branch, index, all) => branch.length > 0 && all.indexOf(branch) === index) + .slice(0, 4); + return alternatives.length >= 2 + ? Object.freeze({ alternatives: Object.freeze(alternatives), primary_index: null }) + : null; +} + /** True when the query itself explicitly requests a negation/variant qualifier. */ export function queryRequestsNegation(projection: IngredientQueryProjection): boolean { return projection.food_tokens.some((token) => NEGATION_TOKENS.has(token)); diff --git a/src/core/nutritionV2/phase4/analyzer.ts b/src/core/nutritionV2/phase4/analyzer.ts index 99bc9ef..084a6cd 100644 --- a/src/core/nutritionV2/phase4/analyzer.ts +++ b/src/core/nutritionV2/phase4/analyzer.ts @@ -17,6 +17,7 @@ */ import { parseIngredient } from '../matching/parse'; +import { projectIngredientAlternatives } from '../matching/query'; import { bestEffortPortionTieCandidates, classifyReviewConfidence, @@ -291,6 +292,8 @@ export function analyzeRecipeFromRows( const measurementKind = parsed && parsed.ok ? parsed.parsed.measurement_kind : 'unknown'; const originalText = row.original_text || row.query; const hasMassRange = hasExplicitMassRange(originalText); + const requiresExplicitAlternativeChoice = + projectIngredientAlternatives(originalText)?.primary_index === null; const base = { line_ref: row.line_ref, @@ -329,6 +332,20 @@ export function analyzeRecipeFromRows( continue; } + if (requiresExplicitAlternativeChoice) { + analyzed.push({ + ...base, + status: 'needs_match', + confidence: 'unresolved', + selected_fdc_id: undefined, + selected_description: undefined, + match_class: undefined, + auto_portion: false, + reason: 'explicit_alternative_choice_required', + }); + continue; + } + const confidence = classifyReviewConfidence(review); const automatic = selectBestEffortMatch(review); diff --git a/src/core/nutritionV2/phase5/authorize.ts b/src/core/nutritionV2/phase5/authorize.ts index 57aaf33..eeb1742 100644 --- a/src/core/nutritionV2/phase5/authorize.ts +++ b/src/core/nutritionV2/phase5/authorize.ts @@ -78,6 +78,7 @@ import type { AdvisoryNutritionPreview } from '../calculation/types'; import { recomputeReviewedNutrition } from '../phase4/session'; import { adaptRecipe } from '../phase4/adapt'; import { ingredientMeasurement } from '../phase4/rows'; +import { projectIngredientAlternatives } from '../matching/query'; import { hasDangerousOwnKey, hasSymbolKeys, materializeNarrow, readOwnDataField } from '../phase4/materialize'; import { PHASE5_AUTHORIZATION_VERSION, @@ -634,6 +635,21 @@ function authorizeNutritionPersistenceInternal( } const trusted = recompute.result; + // Equal authored alternatives are a hard Apply boundary. The Phase 3 + // calculator may expose both branches for investigation, but only an + // explicit user-confirmed review selection can authorize a definitive + // persisted result. This is intentionally general and does not identify + // individual foods or weights. + const adaptedForAlternativeCheck = adaptRecipe(recipeField.value); + if (!adaptedForAlternativeCheck.ok) return fail('invalid_request'); + const equalAlternativeRefs = adaptedForAlternativeCheck.recipe.adapted + .filter((entry) => projectIngredientAlternatives(entry.ingredient.original)?.primary_index === null) + .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 (rawServings.value !== trusted.servings) return fail('stale_preview'); let persistencePreview = trusted.preview; const aiNutritionField = ownField(state, 'aiNutrition'); diff --git a/src/core/nutritionV2/phase5/types.ts b/src/core/nutritionV2/phase5/types.ts index a20fcbf..3edf3ba 100644 --- a/src/core/nutritionV2/phase5/types.ts +++ b/src/core/nutritionV2/phase5/types.ts @@ -35,6 +35,7 @@ export type Phase5AuthorizationFailureCode = | 'unresolved_authority' | 'schema_invalid' | 'calculation_mismatch' + | 'explicit_choice_required' | 'applied_line_unresolved' | 'unknown_future_schema' | 'unsafe_request' @@ -48,6 +49,7 @@ export const PHASE5_FAILURE_MESSAGE: Readonly; + if ( + record['version'] !== 1 || + record['enabled'] !== true || + typeof record['vault_scope'] !== 'string' || + !/^vault:[0-9a-f]{64}$/.test(record['vault_scope']) || + typeof record['granted_at'] !== 'string' || + Number.isNaN(Date.parse(record['granted_at'])) + ) return null; + return { + version: 1, + enabled: true, + vault_scope: record['vault_scope'], + granted_at: record['granted_at'], + }; +} + +export function nutritionAuthorityEnabled( + record: ShisoNutritionAuthorityRecord | null, + currentVaultScope: string, +): boolean { + return currentVaultScope.length > 0 && record?.enabled === true && record.vault_scope === currentVaultScope; +} + +export function grantNutritionAuthority(vaultScope: string, now = new Date()): ShisoNutritionAuthorityRecord { + if (!/^vault:[0-9a-f]{64}$/.test(vaultScope)) throw new Error('A writable Vault must be connected first.'); + return { + version: 1, + enabled: true, + vault_scope: vaultScope, + granted_at: now.toISOString(), + }; +} diff --git a/src/core/shiso/protocol.ts b/src/core/shiso/protocol.ts index eae7158..ecb6565 100644 --- a/src/core/shiso/protocol.ts +++ b/src/core/shiso/protocol.ts @@ -399,6 +399,7 @@ export interface ShisoRecipeSaveOutcome { readonly reason_code?: | 'not_authorized' | 'stale_recipe' + | 'stale_vault' | 'nothing_unsaved' | 'no_owner' | 'write_failed'; diff --git a/src/core/shiso/saveAuthorization.ts b/src/core/shiso/saveAuthorization.ts index 8ef0c49..edb8f05 100644 --- a/src/core/shiso/saveAuthorization.ts +++ b/src/core/shiso/saveAuthorization.ts @@ -148,15 +148,19 @@ export function recipeIdentityOf( */ export interface ShisoSaveGrant { readonly authorized: true; - /** 'ui' = a genuine Save control; 'assistant' = a natural-language command. */ - readonly via: 'ui' | 'assistant'; + /** Standing authority is restricted to a nutrition Apply in the same turn. */ + readonly via: 'ui' | 'assistant' | 'standing_nutrition'; /** Bound at issuance; the recipe being saved must match for 'assistant'. */ readonly recipe_identity: string; /** The user turn that issued the authorization (0 for a UI action). */ readonly turn: number; + /** Required only for standing nutrition authority; never a raw Vault path. */ + readonly vault_scope?: string; + /** Defense in depth: the trusted surface confirms nutrition Apply succeeded first. */ + readonly nutrition_applied?: true; } -export type ShisoSaveGrantRejection = 'not_authorized' | 'stale_recipe'; +export type ShisoSaveGrantRejection = 'not_authorized' | 'stale_recipe' | 'stale_vault'; /** * INDEPENDENT re-verification at the persistence owner. A grant that is absent, @@ -167,18 +171,26 @@ export type ShisoSaveGrantRejection = 'not_authorized' | 'stale_recipe'; export function verifySaveGrant( grant: unknown, currentRecipeIdentity: string, + currentVaultScope = '', ): { readonly ok: true } | { readonly ok: false; readonly reason: ShisoSaveGrantRejection } { if (grant === null || typeof grant !== 'object') return { ok: false, reason: 'not_authorized' }; const record = grant as Record; if (record['authorized'] !== true) return { ok: false, reason: 'not_authorized' }; const via = record['via']; - if (via !== 'ui' && via !== 'assistant') return { ok: false, reason: 'not_authorized' }; + if (via !== 'ui' && via !== 'assistant' && via !== 'standing_nutrition') return { ok: false, reason: 'not_authorized' }; if (via === 'ui') return { ok: true }; const boundIdentity = record['recipe_identity']; if (typeof boundIdentity !== 'string' || boundIdentity.length === 0) { return { ok: false, reason: 'not_authorized' }; } if (boundIdentity !== currentRecipeIdentity) return { ok: false, reason: 'stale_recipe' }; + if (via === 'standing_nutrition') { + if (record['nutrition_applied'] !== true) return { ok: false, reason: 'not_authorized' }; + const vaultScope = record['vault_scope']; + if (typeof vaultScope !== 'string' || vaultScope.length === 0 || vaultScope !== currentVaultScope) { + return { ok: false, reason: 'stale_vault' }; + } + } return { ok: true }; } diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index 7b0958a..3d0b1a9 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -13,6 +13,7 @@ import { dirname, join } from 'node:path'; import App from '../../src/App'; import { ShisoEntryProvider, useShiso } 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'; @@ -37,10 +38,11 @@ servings: 2 1. Mix and cook. `; -const settings = { - get: async () => null, - set: async () => {}, - remove: async () => {}, +const settingsValues = new Map(); +const settings: SettingsAdapter = { + get: async (key: string) => settingsValues.get(key) as T | undefined, + set: async (key: string, value: T) => { settingsValues.set(key, value); }, + remove: async (key: string) => { settingsValues.delete(key); }, }; class DiskFileHandle { @@ -157,6 +159,7 @@ describe('SHISO agent foundation real App save closure', () => { afterEach(async () => { cleanup(); vi.restoreAllMocks(); + settingsValues.clear(); delete (window as unknown as { showDirectoryPicker?: unknown }).showDirectoryPicker; while (roots.length > 0) await rm(roots.pop()!, { recursive: true, force: true }); }); @@ -236,4 +239,85 @@ describe('SHISO agent foundation real App save closure', () => { expect(saved?.codexNutrition).toMatchObject({ status: 'complete', sources: ['usda_fdc'] }); expect((saved?.codexNutrition as { readonly ingredients?: readonly unknown[] } | undefined)?.ingredients).toHaveLength(2); }, 90000); + + it('persists standing-authority nutrition through the real App, honors do-not-save, and restores the prior value', async () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-shiso-authority-app-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', 'Nutrition Fixture.md'); + await mkdir(dirname(recipePath), { recursive: true }); + await writeFile(recipePath, nutritionRecipeMarkdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable SHISO Authority Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + + const { manifest, records } = buildMatchingBundle([ + { fdcId: 7001, dataType: 'foundation', description: 'Butter, unsalted' }, + { fdcId: 7002, dataType: 'foundation', description: 'Salt, table' }, + ]); + 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: 'No provider step was required.', proposals: [] }, + ], { + '/api/nutrition/product-access': { ok: true, version: NUTRITION_PRODUCT_ACCESS_VERSION, tier: 'ai_advanced' }, + '/api/providers': { providers: [] }, + }); + + render( + + + , + ); + + fireEvent.click(await screen.findByRole('button', { name: 'Connect Vault' })); + fireEvent.click(await screen.findByRole('tab', { name: 'Live Directory Sync' })); + fireEvent.click(await screen.findByRole('button', { name: 'Choose Local Obsidian Vault Folder' })); + await screen.findByText(/Connected live to vault "Disposable SHISO Authority Vault"/); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: 'Nutrition Fixture' })); + + fireEvent.click(await screen.findByRole('button', { name: 'Generate Nutrition' })); + await screen.findByRole('dialog', { name: 'Advanced Nutrition' }); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(1)); + const authorityToggle = await screen.findByTestId('shiso-nutrition-authority-toggle') as HTMLInputElement; + expect(authorityToggle.checked).toBe(false); + fireEvent.click(authorityToggle); + await waitFor(() => expect(authorityToggle.checked).toBe(true)); + fireEvent.click(screen.getByRole('button', { name: 'Close Advanced Nutrition' })); + + fireEvent.click(await screen.findByTestId('recipe-shiso-entry')); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'Fix the missing ingredients in this nutrition review.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Standing nutrition authority applied the reviewed result')); + + let persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((recipe) => recipe.title === 'Nutrition Fixture')?.codexNutrition) + .toMatchObject({ status: 'complete', sources: ['usda_fdc'] }); + + fireEvent.click(screen.getByRole('button', { name: 'Close Shiso' })); + const restore = await screen.findByRole('button', { name: 'Restore previous nutrition' }); + fireEvent.click(restore); + await screen.findByText(/Restored the previous nutrition values/); + persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((recipe) => recipe.title === 'Nutrition Fixture')?.codexNutrition).toBeUndefined(); + + fireEvent.click(await screen.findByTestId('recipe-shiso-entry')); + const noSaveComposer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + const beforeNoSave = await readFile(recipePath, 'utf8'); + fireEvent.change(noSaveComposer, { target: { value: 'Complete the nutrition, but do not save.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Nothing was applied or saved')); + expect(await readFile(recipePath, 'utf8')).toBe(beforeNoSave); + }, 120000); }); diff --git a/tests/security/shisoH2SaveAuthorization.test.ts b/tests/security/shisoH2SaveAuthorization.test.ts index f56cd6a..0dcfb27 100644 --- a/tests/security/shisoH2SaveAuthorization.test.ts +++ b/tests/security/shisoH2SaveAuthorization.test.ts @@ -253,6 +253,21 @@ describe('H-2 save authorization — grant verification at the save owner', () = expect(verdict.ok).toBe(true); }); + it('accepts standing nutrition authority only after nutrition Apply and for the exact Vault', () => { + const grant = { + authorized: true, + via: 'standing_nutrition', + recipe_identity: 'Recipes/Chicken.md', + vault_scope: `vault:${'a'.repeat(64)}`, + turn: 9, + nutrition_applied: true, + } as const; + expect(verifySaveGrant(grant, 'Recipes/Chicken.md', `vault:${'a'.repeat(64)}`)).toEqual({ ok: true }); + expect(verifySaveGrant({ ...grant, nutrition_applied: undefined }, 'Recipes/Chicken.md', grant.vault_scope)).toMatchObject({ ok: false, reason: 'not_authorized' }); + expect(verifySaveGrant(grant, 'Recipes/Other.md', grant.vault_scope)).toMatchObject({ ok: false, reason: 'stale_recipe' }); + expect(verifySaveGrant(grant, 'Recipes/Chicken.md', `vault:${'b'.repeat(64)}`)).toMatchObject({ ok: false, reason: 'stale_vault' }); + }); + it('accepts a UI grant (the genuine Save control is its own authorization)', () => { const verdict = verifySaveGrant( { authorized: true, via: 'ui', recipe_identity: '', turn: 0 }, @@ -364,7 +379,7 @@ describe('H-2 save authorization — structural pins', () => { it('the persistence owner re-verifies the grant against the recipe being saved', () => { const app = read('src/App.tsx'); - expect(app).toContain('verifySaveGrant(grant, recipeIdentityOf(current.base))'); + expect(app).toContain('verifySaveGrant(grant, recipeIdentityOf(current.base), nutritionAuthorityScope)'); // The refusal is before the canonical write on the refuse path. const verifyAt = app.indexOf('verifySaveGrant'); const writeAt = app.indexOf('await commitRecipeWrite(current.working'); diff --git a/tests/unit/advancedNutritionAiExceptionsUi.test.tsx b/tests/unit/advancedNutritionAiExceptionsUi.test.tsx index 5de25c4..e6b9f73 100644 --- a/tests/unit/advancedNutritionAiExceptionsUi.test.tsx +++ b/tests/unit/advancedNutritionAiExceptionsUi.test.tsx @@ -15,9 +15,10 @@ import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react'; -import { useState, type ComponentProps } from 'react'; +import { useEffect, useState, type ComponentProps } from 'react'; import { AdvancedNutritionCard } from '../../src/components/AdvancedNutritionCard'; +import { ShisoEntryProvider, useShiso } from '../../src/application-ui/shisoEntryPoints'; import { createAdvancedNutritionSession } from '../../src/core/nutritionV2/phase4/session'; import { parseIngredient } from '../../src/core/nutritionV2/matching/parse'; import { resolveAmountsFromAiSuggestions } from '../../src/core/nutritionV2/phase4/aiAmountResolve'; @@ -151,6 +152,52 @@ async function analyzeWithShiso(): Promise { fireEvent.click(button); } +function StandingAuthorityHarness({ + target, + apply, + save, +}: { + readonly target: ObsidianRecipe; + readonly apply: ComponentProps['onApplyAdvancedNutrition']; + readonly save: (grant: unknown) => Promise<{ ok: boolean; saved: boolean; message: string }>; +}) { + const shiso = useShiso(); + const registerRecipeEditApplier = shiso.registerRecipeEditApplier; + useEffect(() => registerRecipeEditApplier({ + applyEdits: async () => ({ + ok: false, + applied: [], + refused: [], + summary: 'No recipe edit was requested.', + working_unsaved: false, + note: '', + }), + save: async (grant) => save(grant), + discard: () => {}, + }), [registerRecipeEditApplier, save]); + return ( + {}, + }} + advancedNutritionAiAvailability={{ + available: false, + reason: 'The selected AI connection is unavailable.', + refreshing: false, + canRetry: false, + advancedEditingAccess: 'entitled', + }} + /> + ); +} + function summaryText(): string { return screen.getByTestId('advanced-nutrition-live-summary').textContent ?? ''; } @@ -941,6 +988,77 @@ describe('Generate — deterministic first, AI only on explicit SHISO action', ( expect(args.orchestration).toBe('generate'); }); + it('runs an observable authenticated USDA-only fallback when AI is unavailable', async () => { + const aiFirst = vi.fn(); + render( + + ); + await openAndAnalyze(); + const button = await screen.findByTestId('advanced-nutrition-analyze-with-shiso') as HTMLButtonElement; + expect(button.disabled).toBe(false); + fireEvent.click(button); + await waitFor(() => expect(screen.getByTestId('advanced-nutrition-shiso-status').textContent).toMatch(/completed the authenticated USDA-only analysis/i)); + expect(aiFirst).not.toHaveBeenCalled(); + expect(screen.getByTestId('advanced-nutrition-live-summary')).toBeTruthy(); + }); + + it('runs the authenticated USDA-only fallback through Apply and Save when standing authority is enabled', async () => { + const apply = vi.fn(async () => ({ ok: true, mode: 'create' as const, message: 'Applied through the canonical review owner.' })); + const save = vi.fn(async (_grant: unknown) => ({ ok: true, saved: true, message: 'Saved through the canonical Vault owner.' })); + render( + + + + ); + await openAndAnalyze(); + fireEvent.click(await screen.findByTestId('advanced-nutrition-analyze-with-shiso')); + await waitFor(() => expect(screen.getByTestId('advanced-nutrition-shiso-status').textContent).toMatch(/saved it to the active Vault/i)); + expect(apply).toHaveBeenCalledTimes(1); + expect(save).toHaveBeenCalledTimes(1); + expect(save.mock.calls[0]?.[0]).toMatchObject({ + authorized: true, + via: 'standing_nutrition', + recipe_identity: 'Recipes/authority.md', + vault_scope: 'disposable-vault', + nutrition_applied: true, + }); + expect(screen.getByTestId('advanced-nutrition-shiso-status').textContent).not.toMatch(/nothing was applied or saved/i); + }); + + it('announces the correct idle Analyze with SHISO policy for both authority states', async () => { + const authority = (enabled: boolean) => ({ + enabled, + available: true, + recipeIdentity: 'Recipes/idle-wording.md', + vaultScope: 'disposable-vault', + onChange: () => {}, + }); + + render(); + await openAndAnalyze(); + expect(screen.getByTestId('advanced-nutrition-shiso-status').textContent).toContain( + 'Analysis creates a working review only. Apply and Vault saving are separate steps.' + ); + + cleanup(); + render(); + await openAndAnalyze(); + expect(screen.getByTestId('advanced-nutrition-shiso-status').textContent).toContain( + 'SHISO will automatically apply and save eligible nutrition results. Unresolved ingredient choices or failed verification will prevent saving.' + ); + }); + it('does not ask AI when the deterministic baseline already resolved every line', async () => { const handler = vi.fn(async () => ({ ok: true, diff --git a/tests/unit/shisoN1IngredientResolution.test.ts b/tests/unit/shisoN1IngredientResolution.test.ts index e8b1192..df7bf45 100644 --- a/tests/unit/shisoN1IngredientResolution.test.ts +++ b/tests/unit/shisoN1IngredientResolution.test.ts @@ -16,6 +16,7 @@ import { createShisoNutritionReviewController } from '../../src/application/shis import { parseIngredient } from '../../src/core/nutritionV2/matching/parse'; import { adaptRecipe } from '../../src/core/nutritionV2/phase4/adapt'; import { analyzeRecipe } from '../../src/core/nutritionV2/phase4/analyzer'; +import { previewNutritionApplyEligibility } from '../../src/core/nutritionV2/phase5/authorize'; import { composeAdvancedNutritionSessionFromBundle } from '../../src/core/nutritionV2/runtime'; import { USDA_BUNDLE_RELEASE_LOCK } from '../../src/core/nutritionV2/usda/releaseLock'; import type { AdvancedNutritionSession } from '../../src/core/nutritionV2/phase4'; @@ -53,6 +54,91 @@ function structuredIngredient(original: string): Record { } describe('N-1 ordinary ingredient resolution', () => { + it('withholds equal authored alternatives from definitive Apply/Save until a user chooses', () => { + const recipe = { + id: 'equal-alternative', + fileName: 'Equal Alternative.md', + filePath: 'Recipes/Equal Alternative.md', + rawMarkdown: '', + title: 'Equal Alternative', + tags: ['food/recipes'], + category: 'Test', + cuisine: 'Test', + difficulty: 'Easy', + rating: 0, + servings: 1, + ingredients: [structuredIngredient('1/4 cup honey or brown sugar')], + instructions: [], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, + } as unknown as ObsidianRecipe; + const controller = createShisoNutritionReviewController(recipe, session); + expect(controller).not.toBeNull(); + if (controller === null) return; + const state = controller.getState(); + const snapshot = controller.getSnapshot(); + expect(snapshot?.rows[0]?.status).toBe('needs_match'); + expect(state.preview?.ingredients[0]?.outcome).not.toBe('calculated'); + expect(previewNutritionApplyEligibility({ session, recipe, state })).toBe(false); + }); + + it('calculates authenticated mutually exclusive sweetener scenarios without combining them', async () => { + const recipe = { + id: 'alternative-sweetener', + fileName: 'Alternative Sweetener.md', + filePath: 'Recipes/Alternative Sweetener.md', + rawMarkdown: '', + title: 'Alternative Sweetener', + tags: ['food/recipes'], + category: 'Test', + cuisine: 'Test', + difficulty: 'Easy', + rating: 0, + servings: 1, + ingredients: [structuredIngredient('1/4 cup honey (or brown sugar)')], + instructions: [], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, + } as unknown as ObsidianRecipe; + const controller = createShisoNutritionReviewController(recipe, session); + if (controller === null) throw new Error('controller failed'); + const snapshot = controller.getSnapshot(); + const lineRef = snapshot.rows[0]?.line_ref; + if (lineRef === undefined) throw new Error('line ref missing'); + const ctx: ShisoToolContext = { + session, + recipe: { + title: recipe.title, + servings: 1, + ingredients: [{ + text: '1/4 cup honey (or brown sugar)', + name: 'honey', + amount: 0.25, + unit: 'cup', + line_ref: lineRef, + }], + instructions: [], + }, + nutrition: snapshot, + }; + const review = await executeShisoTool({ tool: 'get_nutrition_review', include_ingredients: true }, ctx); + expect(review.ok).toBe(true); + if (!review.ok) return; + const scenarios = review.data['alternative_scenarios'] as Array>; + expect(scenarios).toHaveLength(1); + expect(scenarios[0]).toMatchObject({ mutually_exclusive: true, primary_index: 0, definitive_choice_required: false }); + const branches = scenarios[0].branches as Array>; + expect(branches).toHaveLength(2); + expect(branches[0]).toMatchObject({ name: 'honey', fdc_id: 169640, resolved: true, provenance: 'authenticated_usda_scenario' }); + expect(branches[0].resolved_grams).toBeCloseTo(84.75, 4); + expect(branches[1]).toMatchObject({ name: 'brown sugar', fdc_id: 168833, resolved: true, provenance: 'authenticated_usda_scenario' }); + expect(branches[1].resolved_grams).toBeCloseTo(55, 4); + }); + it('uses food identity rather than preparation wording for SHISO USDA discovery', async () => { const ctx = { session, recipe: null, nutrition: null } as unknown as ShisoToolContext; diff --git a/tests/unit/shisoNutritionAuthority.test.ts b/tests/unit/shisoNutritionAuthority.test.ts new file mode 100644 index 0000000..0464252 --- /dev/null +++ b/tests/unit/shisoNutritionAuthority.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; + +import { + grantNutritionAuthority, + nutritionAuthorityEnabled, + nutritionAuthorityVaultScope, + parseNutritionAuthorityRecord, +} from '../../src/core/shiso/nutritionAuthority'; +import { projectIngredientAlternatives } from '../../src/core/nutritionV2/matching/query'; + +describe('SHISO standing nutrition authority', () => { + it('is opt-in and bound to an opaque exact Vault scope', () => { + const a = nutritionAuthorityVaultScope({ kind: 'filesystem', locator: '/vault/a' }); + const b = nutritionAuthorityVaultScope({ kind: 'filesystem', locator: '/vault/b' }); + expect(a).toMatch(/^vault:[0-9a-f]{64}$/); + expect(a).not.toBe(b); + expect(nutritionAuthorityEnabled(null, a)).toBe(false); + const grant = grantNutritionAuthority(a, new Date('2026-11-27T12:00:00.000Z')); + expect(nutritionAuthorityEnabled(grant, a)).toBe(true); + expect(nutritionAuthorityEnabled(grant, b)).toBe(false); + expect(parseNutritionAuthorityRecord(grant)).toEqual(grant); + expect(parseNutritionAuthorityRecord({ ...grant, vault_scope: '/personal/path' })).toBeNull(); + }); + + it('projects parenthetical primary alternatives separately from equal choices', () => { + expect(projectIngredientAlternatives('1/4 cup honey (or brown sugar)')).toEqual({ + alternatives: ['honey', 'brown sugar'], + primary_index: 0, + }); + expect(projectIngredientAlternatives('1/4 cup honey or brown sugar')).toEqual({ + alternatives: ['honey', 'brown sugar'], + primary_index: null, + }); + expect(projectIngredientAlternatives('1 cup strawberries (cleaned and hulled, sliced)')).toBeNull(); + }); +}); diff --git a/tests/unit/shisoNutritionCompletion.test.ts b/tests/unit/shisoNutritionCompletion.test.ts index 0021ad1..c50fad1 100644 --- a/tests/unit/shisoNutritionCompletion.test.ts +++ b/tests/unit/shisoNutritionCompletion.test.ts @@ -543,6 +543,71 @@ describe('SINC-3 end-to-end conversational command', () => { expect(network.post).not.toHaveBeenCalled(); }); + it('reports the canonical persistence outcome without retaining the unsaved claim', async () => { + const applyNutritionReview = vi.fn(async () => ({ + ok: true, + applied: true, + message: 'The verified review is in the working recipe.', + })); + const saveWorkingRecipe = vi.fn(async () => ({ + ok: true, + saved: true, + message: 'The canonical Vault write completed.', + })); + const fixture = ownerFixture({ applyNutritionReview, saveWorkingRecipe }); + const outcome = await runShisoConversationTurn({ + network: noProviderNetwork(), + toolContext: fixture.ctx, + nutritionAuthority: { enabled: true }, + context: { + recipe: { title: 'Gochujang Chicken Rice Bowls', servings: 4, ingredientCount: 18, stepCount: 6 }, + nutrition: { available: true, summary: null, unresolvedCount: 2, needsAmountCount: 0, needsMatchCount: 2, unsavedWorkingReview: true }, + recipeKey: 'gochujang-bowls', + sessionIdentity: 'session-sinc3', + }, + }, initialShisoConversation(), 'Complete nutrition.'); + + expect(outcome.ok).toBe(true); + expect(outcome.toolsUsed).toEqual(['complete_nutrition', 'apply_nutrition_review', 'save_working_recipe']); + expect(applyNutritionReview).toHaveBeenCalledTimes(1); + expect(saveWorkingRecipe).toHaveBeenCalledTimes(1); + expect(outcome.message).toContain('canonical Vault save confirmed persistence'); + expect(outcome.message).not.toContain('Nothing was applied or saved'); + expect(outcome.message).not.toMatch(/unsaved.*saved/i); + }); + + it('reports an Apply failure as unsaved and never claims persistence', async () => { + const applyNutritionReview = vi.fn(async () => ({ + ok: false, + applied: false, + message: 'The authoritative review was stale.', + })); + const saveWorkingRecipe = vi.fn(async () => ({ + ok: true, + saved: true, + message: 'Unexpected save.', + })); + const fixture = ownerFixture({ applyNutritionReview, saveWorkingRecipe }); + const outcome = await runShisoConversationTurn({ + network: noProviderNetwork(), + toolContext: fixture.ctx, + nutritionAuthority: { enabled: true }, + context: { + recipe: { title: 'Gochujang Chicken Rice Bowls', servings: 4, ingredientCount: 18, stepCount: 6 }, + nutrition: { available: true, summary: null, unresolvedCount: 2, needsAmountCount: 0, needsMatchCount: 2, unsavedWorkingReview: true }, + recipeKey: 'gochujang-bowls', + sessionIdentity: 'session-sinc3', + }, + }, initialShisoConversation(), 'Complete nutrition.'); + + expect(outcome.ok).toBe(true); + expect(applyNutritionReview).toHaveBeenCalledTimes(1); + expect(saveWorkingRecipe).not.toHaveBeenCalled(); + expect(outcome.message).toContain('could not apply this review'); + expect(outcome.message).toContain('Nothing was saved'); + expect(outcome.message).not.toContain('canonical Vault save confirmed persistence'); + }); + it('executes a model-requested complete_nutrition tool call', async () => { const fixture = ownerFixture(); const replies = [ From 9bf04c05ded746cc11ad40713cd1e7fe6c063246 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Nov 2026 12:53:39 -0500 Subject: [PATCH 2/2] fix(shiso): preserve safe alternative evidence boundary --- src/application/shisoNutritionReview.ts | 18 +++++++++++++- src/application/shisoTools.ts | 8 +++++-- src/core/nutritionV2/calculation/calculate.ts | 24 +++++++++---------- src/core/nutritionV2/phase4/analyzer.ts | 18 -------------- src/core/nutritionV2/phase4/index.ts | 5 ++++ src/core/nutritionV2/phase5/authorize.ts | 2 +- tests/security/usdaPhase1Isolation.test.ts | 5 ++++ 7 files changed, 45 insertions(+), 35 deletions(-) diff --git a/src/application/shisoNutritionReview.ts b/src/application/shisoNutritionReview.ts index f812c45..6f8e003 100644 --- a/src/application/shisoNutritionReview.ts +++ b/src/application/shisoNutritionReview.ts @@ -120,7 +120,7 @@ export function createShisoNutritionReviewController( const getLiveRows = (): readonly LiveRowState[] => { const analyzedByRef = new Map(analysis.rows.map((row) => [row.line_ref, row])); - return projectLiveRows( + const rows = projectLiveRows( state, analyzedByRef, adapted, @@ -129,6 +129,22 @@ export function createShisoNutritionReviewController( analysis.portions, analysis.countPortions, ); + // The core calculator preserves an automatically discovered equal- + // alternative as raw diagnostic evidence, but SHISO's working review must + // present that line as unresolved until the user chooses a branch. This is + // a presentation-level projection only; Phase 5 independently enforces the + // same boundary before Apply/Save. + return rows.map((row) => { + const evidence = state.preview?.ingredients.find((entry) => entry.line_ref === row.line_ref); + if (evidence?.outcome !== 'ambiguous' || evidence.match_status === 'user_confirmed') return row; + return { + ...row, + status: 'needs_match' as const, + resolved_grams: undefined, + mass_source: undefined, + portion_index: undefined, + }; + }); }; const getSnapshot = (): ShisoNutritionSnapshot => { diff --git a/src/application/shisoTools.ts b/src/application/shisoTools.ts index d4cf86e..20dc952 100644 --- a/src/application/shisoTools.ts +++ b/src/application/shisoTools.ts @@ -35,9 +35,13 @@ import { type ShisoIngredientEditArgs, } from '../core/shiso/protocol'; import { runBatchInvestigation } from '../core/shiso/batchInvestigation'; -import { projectIngredientAlternatives } from '../core/nutritionV2/matching/query'; -import { adaptRecipe, analyzeRecipe, type AdvancedNutritionSession } from '../core/nutritionV2/phase4'; +import { + adaptRecipe, + analyzeRecipe, + projectIngredientAlternatives, + type AdvancedNutritionSession, +} from '../core/nutritionV2/phase4'; import { buildPortionChoice } from '../core/nutritionV2/phase4/portion'; import { buildBrandedContribution, diff --git a/src/core/nutritionV2/calculation/calculate.ts b/src/core/nutritionV2/calculation/calculate.ts index 3c49a8a..88b0a2b 100644 --- a/src/core/nutritionV2/calculation/calculate.ts +++ b/src/core/nutritionV2/calculation/calculate.ts @@ -852,22 +852,16 @@ function evaluateIngredient( } } - // Authored equal alternatives are not a deterministic food choice. A - // matcher-selected candidate (including an automatic-selection claim) may - // be useful for investigation, but it must never enter definitive totals or - // Phase 5 until the user explicitly confirms one branch. The explicit - // `user_confirmed` path is the existing manual review authority; no new - // selection mechanism is introduced here. + // Authored equal alternatives are not a deterministic food choice. Preserve + // the matcher-selected identity and mass as diagnostic evidence so the + // established raw-production benchmark remains truthful, but mark the line + // ambiguous so it cannot contribute to definitive totals or Phase 5 until + // the user explicitly confirms one branch. The explicit `user_confirmed` + // 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') { - matched = false; ambiguous = true; - fdcId = undefined; - recordDigest = undefined; - confirmationDigest = undefined; - manualRecordId = undefined; - manualRecordDigest = undefined; - matchStatus = 'none'; } // Resolve the current canonical record for a matched identity. @@ -1348,6 +1342,10 @@ export function runAdvisoryCalculation(inputs: AdvisoryCalculationInputs): Calcu let covered = 0; for (const entry of ordered) { if (entry.qualitative) continue; + // Keep ambiguous equal-alternative evidence visible on the line, but + // exclude it from any definitive recipe total until a user confirms + // the authored choice. + if (entry.ambiguous) continue; const value = entry.contributions[nutrient]; if (value === undefined) continue; covered += 1; diff --git a/src/core/nutritionV2/phase4/analyzer.ts b/src/core/nutritionV2/phase4/analyzer.ts index 084a6cd..d35b4af 100644 --- a/src/core/nutritionV2/phase4/analyzer.ts +++ b/src/core/nutritionV2/phase4/analyzer.ts @@ -17,7 +17,6 @@ */ import { parseIngredient } from '../matching/parse'; -import { projectIngredientAlternatives } from '../matching/query'; import { bestEffortPortionTieCandidates, classifyReviewConfidence, @@ -292,9 +291,6 @@ export function analyzeRecipeFromRows( const measurementKind = parsed && parsed.ok ? parsed.parsed.measurement_kind : 'unknown'; const originalText = row.original_text || row.query; const hasMassRange = hasExplicitMassRange(originalText); - const requiresExplicitAlternativeChoice = - projectIngredientAlternatives(originalText)?.primary_index === null; - const base = { line_ref: row.line_ref, original_text: row.original_text, @@ -332,20 +328,6 @@ export function analyzeRecipeFromRows( continue; } - if (requiresExplicitAlternativeChoice) { - analyzed.push({ - ...base, - status: 'needs_match', - confidence: 'unresolved', - selected_fdc_id: undefined, - selected_description: undefined, - match_class: undefined, - auto_portion: false, - reason: 'explicit_alternative_choice_required', - }); - continue; - } - const confidence = classifyReviewConfidence(review); const automatic = selectBestEffortMatch(review); diff --git a/src/core/nutritionV2/phase4/index.ts b/src/core/nutritionV2/phase4/index.ts index fc2160e..3552d23 100644 --- a/src/core/nutritionV2/phase4/index.ts +++ b/src/core/nutritionV2/phase4/index.ts @@ -30,4 +30,9 @@ export * from './aiAmountResolve'; export * from './aiHouseholdResolve'; export * from './deterministicAcceptanceView'; export * from './aiPlanReconcile'; +// Phase 4 is the explicit application review boundary for the pure matching +// projection. SHISO orchestration and Phase 5 authorization consume this +// reviewed projection through the boundary rather than reaching into the +// isolated matching namespace directly. +export { projectIngredientAlternatives } from '../matching/query'; export type { AiResolutionIssueKind } from '../aiResolution'; diff --git a/src/core/nutritionV2/phase5/authorize.ts b/src/core/nutritionV2/phase5/authorize.ts index eeb1742..138e9e5 100644 --- a/src/core/nutritionV2/phase5/authorize.ts +++ b/src/core/nutritionV2/phase5/authorize.ts @@ -78,7 +78,7 @@ import type { AdvisoryNutritionPreview } from '../calculation/types'; import { recomputeReviewedNutrition } from '../phase4/session'; import { adaptRecipe } from '../phase4/adapt'; import { ingredientMeasurement } from '../phase4/rows'; -import { projectIngredientAlternatives } from '../matching/query'; +import { projectIngredientAlternatives } from '../phase4'; import { hasDangerousOwnKey, hasSymbolKeys, materializeNarrow, readOwnDataField } from '../phase4/materialize'; import { PHASE5_AUTHORIZATION_VERSION, diff --git a/tests/security/usdaPhase1Isolation.test.ts b/tests/security/usdaPhase1Isolation.test.ts index a5e97b3..1d0ee3d 100644 --- a/tests/security/usdaPhase1Isolation.test.ts +++ b/tests/security/usdaPhase1Isolation.test.ts @@ -32,6 +32,8 @@ const ADVANCED_NAMESPACE = resolve(ROOT, 'src/core/nutritionV2'); const PHASE45B_BROWSER_LOADER = resolve(ROOT, 'src/browser/advancedNutritionBundle.ts'); /** The audited Phase 5B application write coordinator (reuses the canonical digest). */ const PHASE5B_APPLY_MODULE = resolve(ROOT, 'src/application/advancedNutritionApply.ts'); +/** SHISO's Vault-scoped authority binds only an opaque scope through the pure digest helper. */ +const SHISO_AUTHORITY_MODULE = resolve(ROOT, 'src/core/shiso/nutritionAuthority.ts'); function stripComments(source: string): string { return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/[^\n]*/g, '$1'); @@ -143,6 +145,7 @@ describe('usda phase 1 — no network, no keys, no persistence', () => { if (file.startsWith(ADVANCED_NAMESPACE)) continue; // Phases 1–4 are internal if (file === PHASE45B_BROWSER_LOADER) continue; // Phase 4.5B runtime loader (audited) if (file === PHASE5B_APPLY_MODULE) continue; // Phase 5B Apply coordinator (audited) + if (file === SHISO_AUTHORITY_MODULE) continue; // SHISO authority uses digest only const source = readFileSync(file, 'utf8'); let match: RegExpExecArray | null; importRe.lastIndex = 0; @@ -180,6 +183,8 @@ describe('usda phase 1 — no network, no keys, no persistence', () => { // canonical Phase 1 digest (never a private USDA record/store surface). expect(readFileSync(PHASE5B_APPLY_MODULE, 'utf8')).toMatch(/nutritionV2\/usda\/digest/); expect(readFileSync(PHASE5B_APPLY_MODULE, 'utf8')).not.toMatch(/nutritionV2\/usda\/(store|adapter|record|raw)/); + expect(readFileSync(SHISO_AUTHORITY_MODULE, 'utf8')).toMatch(/nutritionV2\/usda\/digest/); + expect(readFileSync(SHISO_AUTHORITY_MODULE, 'utf8')).not.toMatch(/nutritionV2\/usda\/(store|adapter|record|raw)/); }); it('is not re-exported from the Phase 0 / core barrels', () => {