Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions server/shiso/conversationTurn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ const SYSTEM_PROMPT = [
" when applied_count is 0, and never claim an ingredient was fixed unless it is in",
" `applied`. Never invent authenticated matches or portions — the application decides what",
" is supported and reports what is not.",
"- select_usda_nutrition_source: after search_usda_foods/inspect_usda_food identifies",
" an authenticated record and portion for an unresolved line, use this capability to",
" place that exact food and portion into the live review. Send the exact line_ref,",
" fdc_id and portion_index returned by tools; the application re-authenticates them",
" and calculates grams. This is a SHISO-directed working-review change, not a human",
" confirmation, and it is never a reason to invent a value or save without authorization.",
"- apply_nutrition_review: apply the complete application-owned Phase 4 review through",
" the same trusted Apply authority used by Advanced Nutrition. It changes only the",
" UNSAVED working recipe; it never saves to the Vault. Treat its observation as the",
Expand Down Expand Up @@ -246,6 +252,7 @@ const SYSTEM_PROMPT = [
"get_branded_evidence read accepted USDA Branded product evidence in the working review",
"search_usda_foods search the authenticated pinned USDA catalogue",
"inspect_usda_food read one authenticated record and its portions",
"select_usda_nutrition_source place one authenticated food + portion into the working review",
"investigate_ingredient_amount diagnose ONE unresolved ingredient line",
"investigate_unresolved_ingredients diagnose EVERY unresolved line in one step (use this for 'all'/'investigate these')",
"run_nutrition_analysis prepare source-backed and validated AI-estimated nutrition in the unsaved review",
Expand All @@ -264,6 +271,7 @@ const SYSTEM_PROMPT = [
"- {\"tool\":\"investigate_ingredient_amount\",\"line_ref\":\"<from get_current_recipe>\"}",
"- {\"tool\":\"search_usda_foods\",\"query\":\"...\"}",
"- {\"tool\":\"inspect_usda_food\",\"fdc_id\":123}",
"- {\"tool\":\"select_usda_nutrition_source\",\"line_ref\":\"<ref>\",\"fdc_id\":123,\"portion_index\":0}",
"- {\"tool\":\"search_vault_recipes\",\"query\":\"chicken\",\"field\":\"ingredient\"}",
"- {\"tool\":\"get_vault_recipe\",\"recipe_id\":\"<id from search_vault_recipes>\"}",
"- {\"tool\":\"select_vault_recipe\",\"recipe_id\":\"<id from search_vault_recipes>\"}",
Expand Down Expand Up @@ -439,6 +447,8 @@ function salvageToolArgs(tool: ShisoToolName): ShisoToolArgs {
return { tool, query: '', limit: 1 };
case 'inspect_usda_food':
return { tool, fdc_id: 0 };
case 'select_usda_nutrition_source':
return { tool, line_ref: '', fdc_id: 0, portion_index: -1 };
case 'investigate_ingredient_amount':
return { tool, line_ref: '' };
case 'investigate_unresolved_ingredients':
Expand Down Expand Up @@ -550,6 +560,15 @@ function readToolArgs(tool: ShisoToolName, raw: unknown): ShisoToolArgs | null {
if (fdcId <= 0) return null;
return { tool, fdc_id: fdcId };
}
case 'select_usda_nutrition_source': {
const lineRef = rec['line_ref'];
const fdcId = rec['fdc_id'];
const portionIndex = rec['portion_index'];
if (typeof lineRef !== 'string' || lineRef.trim().length === 0 || lineRef.trim().length > SHISO_LIMITS.maxSelectionLineRefChars) return null;
if (typeof fdcId !== 'number' || !Number.isSafeInteger(fdcId) || fdcId <= 0) return null;
if (typeof portionIndex !== 'number' || !Number.isSafeInteger(portionIndex) || portionIndex < 0) return null;
return { tool, line_ref: lineRef.trim(), fdc_id: fdcId, portion_index: portionIndex };
}
case 'investigate_ingredient_amount': {
const lineRef = rec['line_ref'];
if (typeof lineRef !== 'string') return null;
Expand Down
22 changes: 22 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ import {
import type {
ShisoAnalysisOutcome,
ShisoIngredientEditArgs,
ShisoNutritionSourceSelectionOutcome,
ShisoRecipeEditOutcome,
ShisoRecipeSaveOutcome,
} from './core/shiso/protocol';
Expand Down Expand Up @@ -3039,6 +3040,26 @@ export default function App({
: null;
}, []);

const applyIndependentShisoNutritionSourceSelection = useCallback((input: {
readonly lineRef: string;
readonly fdcId: number;
readonly portionIndex: number;
}): ShisoNutritionSourceSelectionOutcome => {
const controller = shisoNutritionReviewRef.current;
const currentRecipe = shisoSelectedRecipeForReviewRef.current;
if (controller === null || currentRecipe === null || !sameCanonicalRecipeIdentity(controller.recipe, currentRecipe)) {
return {
ok: false,
line_ref: input.lineRef,
summary: 'No current SHISO nutrition review is available for that source selection.',
recalculation: 'absent',
working_unsaved: false,
code: 'no_active_review',
};
}
return controller.selectUsdaNutritionSource(input);
}, []);

const acceptIndependentShisoNutrition = useCallback((
contributions: readonly import('./core/nutritionV2/aiContribution').AiNutrientContribution[],
supplements?: readonly import('./core/nutritionV2/aiContribution').AiNutrientSupplement[],
Expand Down Expand Up @@ -5552,6 +5573,7 @@ export default function App({
getIndependentNutritionSnapshot={getIndependentShisoNutritionSnapshot}
acceptIndependentNutrition={acceptIndependentShisoNutrition}
applyIndependentNutritionReview={applyIndependentShisoNutritionReview}
applyIndependentNutritionSourceSelection={applyIndependentShisoNutritionSourceSelection}
nutritionRows={shiso.snapshot?.rows ?? []}
nutritionAiContributions={shiso.snapshot?.aiContributions ?? []}
nutritionReviewRows={shiso.snapshot?.reviewRows ?? []}
Expand Down
73 changes: 69 additions & 4 deletions src/application-ui/shisoEntryPoints.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import type {
ShisoBoundProposal,
ShisoIngredientEditArgs,
ShisoNutritionCorrectionsOutcome,
ShisoNutritionSourceSelectionOutcome,
ShisoRecipeEditOutcome,
ShisoRecipeSaveOutcome,
} from '../core/shiso/protocol';
Expand All @@ -44,6 +45,21 @@ export interface ShisoNutritionAnalysisOutcome {
readonly message: string;
}

/**
* Result of an Apply through a nutrition-review owner.
*
* `not_eligible` is an ownership signal, not a successful Apply: the card owner
* has no current eligible review, so SHISO may use the independent review owner
* instead. Real Apply failures (stale review, authorization, persistence) do not
* carry this code and must not be retried against another review.
*/
export interface ShisoNutritionReviewApplyResult {
readonly ok: boolean;
readonly applied: boolean;
readonly message: string;
readonly code?: 'not_eligible';
}

export type ShisoEntrySource = 'global' | 'recipe' | 'nutrition' | 'create';

export interface ShisoNutritionSnapshot {
Expand Down Expand Up @@ -159,10 +175,10 @@ export interface ShisoEntryPoints {
readonly canRunAnalysis: boolean;
readonly registerAnalysisApplier: (applier: () => Promise<ShisoAnalysisOutcome>) => () => void;
/** Applies the currently displayed authoritative review through Phase 5. */
readonly applyNutritionReview: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>;
readonly applyNutritionReview: () => Promise<ShisoNutritionReviewApplyResult>;
readonly canApplyNutritionReview: boolean;
readonly registerNutritionReviewApplier: (
applier: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>,
applier: () => Promise<ShisoNutritionReviewApplyResult>,
) => () => void;

// -------------------------------------------------------------------------
Expand Down Expand Up @@ -213,6 +229,15 @@ export interface ShisoEntryPoints {
readonly registerCorrectionsApplier: (
applier: (lineRefs?: readonly string[]) => Promise<ShisoNutritionCorrectionsOutcome>,
) => () => void;
readonly applyNutritionSourceSelection: (input: {
readonly lineRef: string;
readonly fdcId: number;
readonly portionIndex: number;
}) => Promise<ShisoNutritionSourceSelectionOutcome>;
readonly canApplyNutritionSourceSelection: boolean;
readonly registerNutritionSourceSelectionApplier: (
applier: (input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise<ShisoNutritionSourceSelectionOutcome>,
) => () => void;
readonly acceptAiNutrition: (contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean;
readonly canAcceptAiNutrition: boolean;
readonly registerAiNutritionApplier: (applier: (contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean) => () => void;
Expand Down Expand Up @@ -272,6 +297,16 @@ const INERT: ShisoEntryPoints = {
}),
canApplyNutritionCorrections: false,
registerCorrectionsApplier: () => () => {},
applyNutritionSourceSelection: async () => ({
ok: false,
line_ref: '',
summary: 'The nutrition review owner is not available.',
recalculation: 'absent',
working_unsaved: false,
code: 'no_active_review',
}),
canApplyNutritionSourceSelection: false,
registerNutritionSourceSelectionApplier: () => () => {},
acceptAiNutrition: () => false,
canAcceptAiNutrition: false,
registerAiNutritionApplier: () => () => {},
Expand All @@ -288,12 +323,15 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
const [snapshot, setSnapshot] = useState<ShisoNutritionSnapshot | null>(null);
const [applier, setApplier] = useState<((b: ShisoBoundProposal) => Promise<ShisoApplyResult>) | null>(null);
const [analysisApplier, setAnalysisApplier] = useState<(() => Promise<ShisoAnalysisOutcome>) | null>(null);
const [nutritionReviewApplier, setNutritionReviewApplier] = useState<(() => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>) | null>(null);
const [nutritionReviewApplier, setNutritionReviewApplier] = useState<(() => Promise<ShisoNutritionReviewApplyResult>) | null>(null);
const [nutritionAnalysisRunner, setNutritionAnalysisRunner] = useState<(() => Promise<ShisoNutritionAnalysisOutcome>) | null>(null);
const [recipeEditApplier, setRecipeEditApplier] = useState<ShisoRecipeEditApplier | null>(null);
const [correctionsApplier, setCorrectionsApplier] = useState<
((lineRefs?: readonly string[]) => Promise<ShisoNutritionCorrectionsOutcome>) | null
>(null);
const [nutritionSourceSelectionApplier, setNutritionSourceSelectionApplier] = useState<
((input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise<ShisoNutritionSourceSelectionOutcome>) | null
>(null);
const [aiNutritionApplier, setAiNutritionApplier] = useState<((contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean) | null>(null);
const [workingRecipe, setWorkingRecipe] = useState<ShisoWorkingRecipeSummary | null>(null);
/**
Expand Down Expand Up @@ -338,7 +376,7 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
setNutritionAnalysisRunner(() => next);
return () => setNutritionAnalysisRunner((current) => current === next ? null : current);
}, []);
const registerNutritionReviewApplier = useCallback((next: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>) => {
const registerNutritionReviewApplier = useCallback((next: () => Promise<ShisoNutritionReviewApplyResult>) => {
setNutritionReviewApplier(() => next);
return () => setNutritionReviewApplier((current) => current === next ? null : current);
}, []);
Expand All @@ -365,6 +403,13 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
},
[],
);
const registerNutritionSourceSelectionApplier = useCallback(
(next: (input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => Promise<ShisoNutritionSourceSelectionOutcome>) => {
setNutritionSourceSelectionApplier(() => next);
return () => setNutritionSourceSelectionApplier((current) => current === next ? null : current);
},
[],
);
const registerAiNutritionApplier = useCallback((next: (contributions: readonly AiNutrientContribution[], supplements?: readonly AiNutrientSupplement[]) => boolean) => {
setAiNutritionApplier(() => next);
return () => setAiNutritionApplier(null);
Expand Down Expand Up @@ -532,6 +577,22 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
},
[correctionsApplier],
);
const applyNutritionSourceSelection = useCallback(
async (input: { readonly lineRef: string; readonly fdcId: number; readonly portionIndex: number }) => {
if (nutritionSourceSelectionApplier === null) {
return {
ok: false,
line_ref: input.lineRef,
summary: 'The nutrition review is not open for this recipe.',
recalculation: 'absent',
working_unsaved: false,
code: 'no_active_review',
} as ShisoNutritionSourceSelectionOutcome;
}
return nutritionSourceSelectionApplier(input);
},
[nutritionSourceSelectionApplier],
);

const value = useMemo<ShisoEntryPoints>(
() => ({
Expand Down Expand Up @@ -567,6 +628,9 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
applyNutritionCorrections,
canApplyNutritionCorrections: correctionsApplier !== null,
registerCorrectionsApplier,
applyNutritionSourceSelection,
canApplyNutritionSourceSelection: nutritionSourceSelectionApplier !== null,
registerNutritionSourceSelectionApplier,
acceptAiNutrition,
canAcceptAiNutrition: aiNutritionApplier !== null,
registerAiNutritionApplier,
Expand All @@ -581,6 +645,7 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
clearSaveAuthorizationEntry, discardWorkingRecipe,
workingRecipe, publishWorkingRecipe, applyNutritionCorrections,
correctionsApplier, registerCorrectionsApplier,
applyNutritionSourceSelection, nutritionSourceSelectionApplier, registerNutritionSourceSelectionApplier,
acceptAiNutrition, aiNutritionApplier, registerAiNutritionApplier,
],
);
Expand Down
38 changes: 36 additions & 2 deletions src/application-ui/useShisoRecipeContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,18 @@

import { useMemo } from 'react';
import { adaptRecipe } from '../core/nutritionV2/phase4';
import { parseIngredient } from '../core/nutritionV2/matching/parse';

export interface ShisoRecipeView {
readonly title: string;
readonly servings: number | null;
readonly ingredients: ReadonlyArray<{
readonly text: string;
readonly name: string;
/** Canonical authored quantity, retained for nutrition actions. */
readonly amount?: number;
/** Canonical authored unit, retained for nutrition actions. */
readonly unit?: string;
/** H-2 stable edit handle; null when the recipe cannot be adapted. */
readonly line_ref?: string | null;
}>;
Expand Down Expand Up @@ -70,14 +75,43 @@ export function toShisoRecipeView(recipe: ShisoRecipeLike | null): ShisoRecipeVi
const ingredients = rawIngredients.slice(0, 80).map((i, index) => {
const name = typeof i.name === 'string' ? i.name.slice(0, 160) : '';
const authored = typeof i.original === 'string' ? i.original.trim() : '';
const structuredAmount =
typeof i.amount === 'number' && Number.isFinite(i.amount)
? i.amount
: typeof i.quantity === 'number' && Number.isFinite(i.quantity)
? i.quantity
: undefined;
const parsedStructured = parseIngredient({
...(authored.length > 0 ? { original: authored } : {}),
...(structuredAmount !== undefined ? { amount: structuredAmount } : {}),
...(typeof i.unit === 'string' && i.unit.length > 0 ? { unit: i.unit } : {}),
...(name.length > 0 ? { name } : {}),
});
const parsedAuthored = authored.length > 0 ? parseIngredient(authored) : null;
const amount = structuredAmount ?? (
parsedAuthored?.ok === true && parsedAuthored.parsed.amount !== null
? parsedAuthored.parsed.amount
: parsedStructured.ok && parsedStructured.parsed.amount !== null
? parsedStructured.parsed.amount
: undefined
);
const unit = typeof i.unit === 'string' && i.unit.length > 0
? i.unit
: parsedAuthored?.ok === true
? parsedAuthored.parsed.raw_unit
: parsedStructured.ok
? parsedStructured.parsed.raw_unit
: i.unit;
const parts: string[] = [];
if (typeof i.quantity === 'number' && Number.isFinite(i.quantity)) parts.push(String(i.quantity));
if (typeof i.unit === 'string' && i.unit.length > 0) parts.push(i.unit);
if (amount !== undefined) parts.push(String(amount));
if (typeof unit === 'string' && unit.length > 0) parts.push(unit);
parts.push(name);
const text = (authored.length > 0 ? authored : parts.join(' ').trim()).slice(0, 200);
return {
text,
name,
...(amount !== undefined ? { amount } : {}),
...(typeof unit === 'string' && unit.length > 0 ? { unit } : {}),
line_ref: typeof lineRefs[index] === 'string' ? lineRefs[index] : null,
};
});
Expand Down
Loading