From 3f010a032476eb33a598cc275cbeb3920d6bc7fc Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 28 Nov 2026 11:13:02 -0500 Subject: [PATCH 1/2] fix(shiso): preserve nutrition state and continue trusted choices --- src/application/shisoChoiceContinuation.ts | 408 ++++++++++++++++++ src/application/shisoConversation.ts | 142 ++++-- src/application/shisoNutritionReview.ts | 45 +- src/components/ShisoModal.tsx | 60 ++- .../shisoAgentFoundationAppOnDisk.test.tsx | 142 ++++++ tests/unit/shisoLiveAcceptance.test.ts | 166 ++++--- 6 files changed, 847 insertions(+), 116 deletions(-) create mode 100644 src/application/shisoChoiceContinuation.ts diff --git a/src/application/shisoChoiceContinuation.ts b/src/application/shisoChoiceContinuation.ts new file mode 100644 index 0000000..8c8c446 --- /dev/null +++ b/src/application/shisoChoiceContinuation.ts @@ -0,0 +1,408 @@ +/** + * SHISO — trusted continuation choices. + * + * The initial culinary investigation asks one consolidated question. This module + * turns the user's ANSWER to that question into bounded, authenticated work + * through the SAME Phase 4 review and USDA selection authority. It is not a + * second nutrition engine and it never guesses an FDC record, a portion, a mass + * or a mixture. + * + * Supported choice dimensions are the ones the application can authenticate: + * - volume with a compatible authenticated volume portion; + * - mass with a compatible authenticated mass portion; + * - count with an authenticated count portion naming the authored item. + * + * A named type without a measurement (pinch of salt, one tortilla) remains a + * specific measurement blocker. A multi-ingredient vegetable mixture remains a + * composition blocker because this recipe line cannot truthfully become one + * USDA vegetable. + */ + +import { + candidateIdentityVerdict, + projectCulinaryIngredient, + projectIngredientAlternatives, + selectDeterministicVolumePortionIndex, + type AdvancedNutritionSession, +} from '../core/nutritionV2/phase4'; +import type { ShisoObservation } from '../core/shiso/protocol'; +import { executeShisoTool, type ShisoToolContext } from './shisoTools'; + +export interface ShisoChoiceOutcome { + readonly line_ref: string; + readonly label: string; + readonly answer: string; + readonly selected: boolean; + readonly reason: string | null; + readonly observation: ShisoObservation | null; +} + +export interface ShisoChoiceContinuationResult { + readonly message: string; + readonly toolsUsed: readonly string[]; + readonly observations: readonly ShisoObservation[]; + readonly outcomes: readonly ShisoChoiceOutcome[]; +} + +function normalizedTokens(text: string): ReadonlySet { + return new Set( + text + .toLowerCase() + .replace(/[^a-z0-9]+/g, ' ') + .split(/\s+/) + .filter(Boolean) + .map((token) => token.length > 3 && token.endsWith('s') ? token.slice(0, -1) : token), + ); +} + +function userNamedBranch(message: string, branch: string): boolean { + const messageTokens = normalizedTokens(message); + return [...normalizedTokens(branch)].every((token) => messageTokens.has(token)); +} + +/** + * Finds the answer sentence that belongs to this authored ingredient line. + * Labels such as "Sausage: breakfast sausage" are matched by the line's food + * identity; an alternative name can also stand alone in prose. + */ +function choiceAnswerForLine(message: string, lineText: string, lineName: string | undefined): string | null { + const projection = projectCulinaryIngredient(lineText); + const alternatives = projectIngredientAlternatives(lineText)?.alternatives ?? []; + const lineTokens = new Set([ + ...normalizedTokens(projection.identity), + ...(lineName ? normalizedTokens(lineName) : []), + ]); + const sentences = message + .split(/\n+|(?<=[.!?])\s+/) + .map((sentence) => sentence.trim()) + .filter(Boolean); + + for (const sentence of sentences) { + const colon = sentence.indexOf(':'); + if (colon > 0) { + const labelTokens = normalizedTokens(sentence.slice(0, colon)); + const labelMatches = [...lineTokens].some((token) => labelTokens.has(token)); + if (labelMatches) return sentence.slice(colon + 1).trim(); + } + if (alternatives.some((alternative) => userNamedBranch(sentence, alternative))) { + return sentence; + } + } + return null; +} + +function cleanChoiceQuery(answer: string): string { + return answer + .toLowerCase() + .replace(/\([^)]*\)/g, ' ') + .replace(/\b(?:only|just|regular|standard|about|roughly|approximately|estimate|estimated|defensible|chopped|diced|minced|sliced|shredded|fresh|large|medium|small|whole)\b/g, ' ') + .replace(/\b\d+(?:\s*\/\s*\d+)?\b/g, ' ') + .replace(/\b(?:cups?|tablespoons?|teaspoons?|tbsp|tsp|pounds?|lbs?|ounces?|oz|pinches?|grams?|g|kilograms?|kg|milliliters?|ml|liters?|l)\b/g, ' ') + .replace(/\b(?:and|or)\b/g, ' ') + .replace(/[^a-z0-9\s-]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); +} + +function answerNamesMultipleComponents(answer: string): boolean { + return answer + .split(/\band\b|,|&|\//i) + .map((part) => part.trim()) + .filter((part) => cleanChoiceQuery(part).length > 0) + .length > 1; +} + +interface PortionResolution { + readonly index: number; + readonly label: string; +} + +function resolveCompatiblePortion( + session: AdvancedNutritionSession, + projection: ReturnType, + fdcId: number, +): PortionResolution | string { + const reviewed = session.reviewPortions(fdcId); + if (!reviewed.ok) return 'The authenticated catalogue could not provide portions for that record.'; + const usable = reviewed.review.candidates.filter( + (candidate) => candidate.kind !== 'unusable' && candidate.gram_weight > 0 && candidate.gram_weight < 100000, + ); + + if (projection.measurement_kind === 'volume' && projection.milliliters !== null) { + const index = selectDeterministicVolumePortionIndex( + session, + fdcId, + projection.milliliters, + projection.normalized_unit ?? projection.unit ?? undefined, + projection.identity, + ); + if (index === undefined) { + return 'The matching record has no authenticated volume portion compatible with the authored measurement; I did not substitute a slice or count.'; + } + const portion = usable.find((candidate) => candidate.index === index); + return portion === undefined + ? 'The authenticated volume portion could not be re-read.' + : { index: portion.index, label: portion.display_label }; + } + + if (projection.measurement_kind === 'mass' && projection.grams !== null) { + const portion = usable.find((candidate) => candidate.kind === 'mass'); + return portion === undefined + ? 'The matching record has no authenticated mass portion; a mass portion or a measured weight is required.' + : { index: portion.index, label: portion.display_label }; + } + + // Count-like lines include lines whose authored unit did not parse (for + // example "8 burrito-size tortillas"). The portion must name the same item. + const requested = normalizedTokens(projection.unit ?? projection.count_noun ?? projection.identity); + const matchingCounts = usable.filter((candidate) => { + if (candidate.kind !== 'count') return false; + const measureTokens = normalizedTokens(candidate.measure); + return [...requested].some((token) => measureTokens.has(token)); + }); + // A record whose identity is the authored item and whose only count measure is + // a generic piece/each/serving is still exactly one item. Package, slice and + // other materially different measures never qualify. + const genericCounts = matchingCounts.length > 0 + ? [] + : usable.filter((candidate) => + candidate.kind === 'count' && /\b(?:piece|each|item|unit|serving)\b/i.test(candidate.measure)); + const counts = matchingCounts.length > 0 ? matchingCounts : genericCounts; + if (counts.length > 0) { + const signatures = new Set(counts.map((candidate) => `${candidate.effective_amount}:${candidate.gram_weight}`)); + if (signatures.size > 1) { + return `Multiple authenticated count portions match (${counts.slice(0, 4).map((candidate) => candidate.display_label).join('; ')}); specify which one was used.`; + } + return { index: counts[0].index, label: counts[0].display_label }; + } + return 'The matching record has no authenticated per-item count portion; a measured weight is required.'; +} + +/** + * Observes the answered lines and executes only authenticated selections. + * Returns null when the message contains no answer for any current line. + */ +export async function tryCulinaryChoiceContinuation( + ctx: ShisoToolContext, + message: string, + signal?: AbortSignal, +): Promise { + if (signal?.aborted) return null; + if (ctx.session === null || ctx.nutrition === null || ctx.recipe === null) return null; + if (ctx.applyNutritionSourceSelection === undefined) return null; + + const answered: Array<{ + readonly line: NonNullable['ingredients'][number]; + readonly answer: string; + }> = []; + for (const line of ctx.recipe.ingredients) { + if (typeof line.line_ref !== 'string' || line.line_ref.length === 0) continue; + const answer = choiceAnswerForLine(message, line.text, line.name); + if (answer !== null) answered.push({ line, answer }); + } + if (answered.length === 0) return null; + + const observations: ShisoObservation[] = []; + const outcomes: ShisoChoiceOutcome[] = []; + const toolsUsed: string[] = []; + + for (const { line, answer } of answered) { + if (signal?.aborted) return null; + const projection = projectCulinaryIngredient(line.text); + const row = ctx.nutrition.rows.find((candidate) => candidate.line_ref === line.line_ref); + const label = line.text.slice(0, 160); + const blocker = (reason: string): void => { + const retained = row?.status === 'matched' && row.selected_description + ? ` The existing ${row.selected_description} selection remains.` + : ''; + outcomes.push({ + line_ref: line.line_ref!, + label, + answer, + selected: false, + reason: `${reason}${retained}`, + observation: null, + }); + }; + + if (projection.flexible_mixture && answerNamesMultipleComponents(answer)) { + blocker('You specified a multi-ingredient mixture. This recipe has one ingredient line, so selecting a single USDA vegetable would misrepresent the composition. The mixture remains unresolved until the recipe has separate component lines or an authenticated combined source.'); + continue; + } + if (projection.measurement_note !== null) { + blocker(`You named a food, but “${projection.unit ?? 'this measure'}” has no documented exact mass. A measured amount is still required; I did not invent one.`); + continue; + } + + const alternatives = projectIngredientAlternatives(line.text); + const branch = alternatives?.alternatives.find((candidate) => userNamedBranch(answer, candidate)) ?? null; + if (alternatives?.primary_index === null && branch === null) { + blocker(`The authored line is an equal choice between ${alternatives.alternatives.join(' and ')}. Name one of those alternatives before I select a definitive source.`); + continue; + } + + const query = branch ?? cleanChoiceQuery(answer); + if (query.length === 0) { + blocker('The answer did not contain a searchable food name. I did not guess one.'); + continue; + } + + let search = ctx.session.searchFoods(query, 12); + let usedQuery = query; + let candidates = search.ok ? [...search.results] : []; + if (candidates.length === 0 && projection.fallback_identities.length > 0) { + for (const fallback of projection.fallback_identities) { + const fallbackSearch = ctx.session.searchFoods(fallback, 12); + if (fallbackSearch.ok && fallbackSearch.results.length > 0) { + search = fallbackSearch; + usedQuery = fallback; + candidates = [...fallbackSearch.results]; + break; + } + } + } + if (!search.ok || candidates.length === 0) { + blocker(`No identity-compatible authenticated record was found for “${query}”. I did not substitute an unrelated food.`); + continue; + } + + const compatible = candidates.filter((candidate) => { + const verdict = candidateIdentityVerdict(usedQuery, candidate.description); + const named = branch === null || userNamedBranch(candidate.description, branch); + if (!verdict.compatible) return false; + if (branch !== null && !named) return false; + return true; + }); + if (compatible.length === 0) { + blocker(`No identity-compatible authenticated record was found for “${query}”. I did not substitute an unrelated food.`); + continue; + } + + const withPortion: Array<{ candidate: (typeof compatible)[number]; portion: PortionResolution }> = []; + let portionReason: string | null = null; + for (const candidate of compatible) { + const portion = resolveCompatiblePortion(ctx.session, projection, candidate.fdc_id); + if (typeof portion === 'string') { + portionReason ??= portion; + continue; + } + withPortion.push({ candidate, portion }); + } + if (withPortion.length === 0) { + const directMassNote = row?.mass_source === 'direct_mass' && typeof row.resolved_grams === 'number' + ? ` The authored mass (${Math.round(row.resolved_grams * 100) / 100} g) is already authoritative, so the review refuses a conflicting source portion; the food identity remains unconfirmed.` + : ''; + blocker(`${portionReason ?? 'No authenticated portion could represent the authored measurement.'}${directMassNote}`); + continue; + } + const distinct = new Set(withPortion.map(({ candidate }) => candidate.description.trim().toLowerCase())); + if (distinct.size > 1) { + blocker(`Multiple authenticated variants match “${query}”: ${withPortion.slice(0, 4).map(({ candidate }) => candidate.description).join('; ')}. Specify which one was used; I did not choose silently.`); + continue; + } + + const chosen = withPortion[0]; + const trustedContext: ShisoToolContext = { + ...ctx, + isTrustedNutritionSourceSelection: (lineRef, description) => + ctx.isTrustedNutritionSourceSelection?.(lineRef, description) === true || + (lineRef === line.line_ref && + (userNamedBranch(answer, description) || (branch !== null && userNamedBranch(answer, branch)))), + }; + const result = await executeShisoTool( + { + tool: 'select_usda_nutrition_source', + line_ref: line.line_ref!, + fdc_id: chosen.candidate.fdc_id, + portion_index: chosen.portion.index, + }, + trustedContext, + signal, + ); + toolsUsed.push('select_usda_nutrition_source'); + observations.push(result); + if (result.ok) { + outcomes.push({ + line_ref: line.line_ref!, + label, + answer, + selected: true, + reason: null, + observation: result, + }); + } else { + const failure = (result as Extract).message; + const directMassNote = row?.mass_source === 'direct_mass' && typeof row.resolved_grams === 'number' + ? ` The authored mass (${Math.round(row.resolved_grams * 100) / 100} g) is already authoritative, so the review refuses a conflicting source portion; the food identity remains unconfirmed.` + : ''; + blocker(`${failure}${directMassNote}`); + } + } + + if (outcomes.length === 0) return null; + + const review = await executeShisoTool({ tool: 'get_nutrition_review', include_ingredients: true }, ctx, signal); + toolsUsed.push('get_nutrition_review'); + observations.push(review); + const data = review.ok ? review.data : {}; + const ingredients = Array.isArray(data['ingredients']) + ? data['ingredients'].filter((entry): entry is Record => + entry !== null && typeof entry === 'object' && !Array.isArray(entry)) + : []; + const retained = ingredients + .filter((entry) => entry['status'] === 'source_backed') + .slice(0, 6) + .map((entry) => { + const label = typeof entry['label'] === 'string' ? entry['label'].slice(0, 70) : 'an ingredient'; + const food = typeof entry['food'] === 'string' ? entry['food'] : 'authenticated source'; + const grams = typeof entry['resolved_grams'] === 'number' ? ` · ${Math.round(entry['resolved_grams'] * 100) / 100} g` : ''; + return `${label} — ${food}${grams}`; + }); + const selected = outcomes.filter((outcome) => outcome.selected); + const blocked = outcomes.filter((outcome) => !outcome.selected); + const answerLines = outcomes.map((outcome) => { + const answerNote = outcome.answer.length > 0 ? ` Your answer: “${outcome.answer.slice(0, 160)}”.` : ''; + return outcome.selected + ? `✓ ${outcome.label} — ${outcome.observation?.ok ? outcome.observation.summary : 'authenticated source selected'}` + : `• ${outcome.label} — ${outcome.reason ?? 'remains unresolved.'}${answerNote}`; + }); + const answeredRefs = new Set(outcomes.map((outcome) => outcome.line_ref)); + const remaining = ingredients + .filter((entry) => entry['status'] !== 'source_backed' && typeof entry['line_ref'] === 'string' && !answeredRefs.has(entry['line_ref'] as string)) + .slice(0, 8) + .map((entry) => { + const label = typeof entry['label'] === 'string' ? entry['label'].slice(0, 120) : 'an ingredient'; + const status = typeof entry['status'] === 'string' ? entry['status'].replace(/_/g, ' ') : 'unresolved'; + return `• ${label} — remains ${status}.`; + }); + const resolved = typeof data['source_backed'] === 'number' ? data['source_backed'] : null; + const total = typeof data['total_ingredient_lines'] === 'number' ? data['total_ingredient_lines'] : null; + + const messageParts = [ + 'I processed your answers against the authenticated review.', + selected.length > 0 + ? `Executed ${selected.length} supported selection${selected.length === 1 ? '' : 's'}.` + : 'No new authenticated source could be selected without guessing.', + answerLines.join('\n'), + ]; + if (retained.length > 0) { + messageParts.push(`Previously verified selections remain attached: ${retained.join('; ')}.`); + } + if (remaining.length > 0) { + messageParts.push(`Still unresolved after your answers:\n${remaining.join('\n')}`); + } + if (resolved !== null && total !== null) { + messageParts.push(`${resolved} of ${total} ingredient lines are source-backed.`); + } + if (blocked.length > 0) { + messageParts.push(`${blocked.length} answer${blocked.length === 1 ? '' : 's'} need a specific food, composition, or measurement before they can become authenticated nutrition.`); + } + messageParts.push('Nothing was applied or saved.'); + + return Object.freeze({ + message: messageParts.join('\n'), + toolsUsed: Object.freeze(toolsUsed), + observations: Object.freeze(observations), + outcomes: Object.freeze(outcomes), + }); +} diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index 16e79a0..6e3e5fe 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -41,6 +41,7 @@ import { import type { NetworkAdapter, NetworkResponse } from './adapters/NetworkAdapter'; import { buildAiSelectionRequestOptions } from './aiSelection'; import { executeShisoTool, type ShisoToolContext } from './shisoTools'; +import { tryCulinaryChoiceContinuation } from './shisoChoiceContinuation'; import { planDeterministicIngredientEdit } from '../core/shiso/deterministicEdit'; import { classifySaveIntent } from '../core/shiso/saveAuthorization'; import { @@ -220,6 +221,17 @@ async function tryDeterministicNutritionSourceSelection( return null; } +function requestsAffirmativeNutritionApply(message: string): boolean { + const text = message.toLowerCase().replace(/[’']/g, ''); + if (/\b(?:do not|don't|dont|without)\s+(?:apply|save)\b/.test(text)) return false; + return /\bapply\b/.test(text) && /\b(?:nutrition|review|changes?|it)\b/.test(text); +} + +function conversationAwaitsNutritionChoices(state: ShisoConversationState): boolean { + const lastAssistant = [...state.messages].reverse().find((message) => message.role === 'assistant')?.text ?? ''; + return /consolidated choice|which did you actually use|what measured amount|still unresolved/i.test(lastAssistant); +} + function requestsVaultCount(message: string): boolean { const text = message.toLowerCase().replace(/[’']/g, ''); return ( @@ -362,9 +374,6 @@ async function tryCulinaryIdentityProgress( const roundedGrams = grams === null ? null : Math.round(grams * 100) / 100; if (description !== null) selectedSources.push(`${description}${roundedGrams !== null ? ` (${roundedGrams} g)` : ''}`); selectedLineRefs.push(lineRef); - // The owning review dispatches asynchronously; let it commit before the - // next selection/completion reads the same live owner. - await new Promise((resolve) => setTimeout(resolve, 0)); } } const pending = Array.isArray(data['pending_user_choices']) @@ -650,6 +659,30 @@ export async function runShisoConversationTurn( const collected: ShisoCollectedFinding[] = []; /** tool signature -> observation already obtained this turn. */ const cache = new Map(); + /** Cached successful reads served without a new tool execution. */ + const cachedRepeatServes = new Map(); + const EVIDENCE_READ_TOOLS: ReadonlySet = new Set([ + 'get_current_recipe', + 'get_nutrition_review', + 'get_branded_evidence', + 'search_usda_foods', + 'inspect_usda_food', + 'investigate_ingredient_amount', + 'investigate_unresolved_ingredients', + 'get_vault_status', + 'get_vault_recipe', + 'select_vault_recipe', + 'get_capability_status', + 'load_usda_catalog', + ]); + const STATE_CHANGING_TOOLS: ReadonlySet = new Set([ + 'apply_ingredient_edits', + 'apply_nutrition_corrections', + 'select_usda_nutrition_source', + 'run_nutrition_analysis', + 'apply_nutrition_review', + 'save_working_recipe', + ]); /** H-2S: tool signature -> how many times an EQUIVALENT failure occurred. */ const failureCounts = new Map(); let modelInvocations = 0; @@ -659,6 +692,40 @@ export async function runShisoConversationTurn( /** Set the moment a capability reports a missing prerequisite. */ let block: ShisoBlock | null = null; + // A direct answer to the consolidated culinary question is a deterministic + // continuation, not a new open-ended chat turn. Process the supported + // selections through the SAME authenticated review first, then report the + // specific blockers. This keeps the verified review intact even when the + // model would otherwise spend its turn re-reading it. + if (!classifySaveIntent(trimmed).authorized && !requestsAffirmativeNutritionApply(trimmed) && conversationAwaitsNutritionChoices(state)) { + if (deps.signal?.aborted) return cancelled(working, toolsUsed); + const continuation = await tryCulinaryChoiceContinuation(deps.toolContext, trimmed, deps.signal); + if (deps.signal?.aborted) return cancelled(working, toolsUsed); + if (continuation !== null) { + let next = working; + for (const observation of continuation.observations) { + if (!observation.ok) continue; + next = recordFinding(next, { + tool: observation.tool, + ok: true, + summary: observation.summary, + }); + } + next = appendShisoMessage(next, { + role: 'assistant', + text: continuation.message, + proposalCount: 0, + }); + return { + ok: true, + state: next, + message: continuation.message, + status: null, + toolsUsed: Object.freeze([...continuation.toolsUsed]) as readonly string[], + }; + } + } + // A Vault count is a deterministic read of the active application snapshot. // It does not need a provider call and therefore cannot be confused with a // stale screen count or a provider entitlement failure. @@ -972,12 +1039,6 @@ export async function runShisoConversationTurn( tool: deterministicSelection.tool, ok: deterministicSelection.ok, }); - // A mounted React review owner may commit its dispatch on the next event - // loop turn. The following model/tool step reads the same live owner, not a - // stale render snapshot. - if (deterministicSelection.ok) { - await new Promise((resolve) => setTimeout(resolve, 0)); - } } /** @@ -1047,28 +1108,6 @@ export async function runShisoConversationTurn( 'apply_nutrition_review', 'save_working_recipe', ]); - const NON_PROGRESS_REPEAT_TOOLS: ReadonlySet = new Set([ - 'get_vault_status', - 'search_vault_recipes', - 'get_vault_recipe', - 'select_vault_recipe', - 'load_usda_catalog', - 'get_current_recipe', - 'get_nutrition_review', - 'get_branded_evidence', - 'search_usda_foods', - 'inspect_usda_food', - 'investigate_ingredient_amount', - 'investigate_unresolved_ingredients', - 'get_capability_status', - 'select_usda_nutrition_source', - 'run_nutrition_analysis', - 'complete_nutrition', - 'apply_nutrition_corrections', - 'apply_nutrition_review', - 'save_working_recipe', - ]); - /** * Deterministic delivery of everything already known, with NO provider call. * @@ -1285,16 +1324,27 @@ export async function runShisoConversationTurn( toolsUsed, }; } - if (cached.ok && NON_PROGRESS_REPEAT_TOOLS.has(turn.tool)) { - return { - ok: true, - state: working, - message: deterministicReport( - `I already verified the same ${turn.tool} request in this message, so I stopped instead of repeating it.`, - ), - status: null, - toolsUsed, - }; + if (cached.ok) { + // A repeated SUCCESSFUL read is evidence, not a terminal event. Serve + // the cached observation without charging the tool budget, and let the + // model continue with the same verified facts. Only a genuinely + // repeated no-progress read (bounded below) may stop the turn. + const repeats = (cachedRepeatServes.get(signature) ?? 0) + 1; + if (repeats > 2) { + return { + ok: true, + state: working, + message: deterministicReport( + `I stopped because the same ${turn.tool} read produced no new progress after ${repeats} repeats. ` + + 'The verified evidence below remains available; no edit or save occurred.', + ), + status: null, + toolsUsed, + }; + } + cachedRepeatServes.set(signature, repeats); + observation = cached; + continue; } const terminal = noteFailure(signature, cached); if (terminal !== null) return terminal; @@ -1318,6 +1368,16 @@ export async function runShisoConversationTurn( // result as the current turn or begin another provider/tool iteration. if (deps.signal?.aborted) return cancelled(working, toolsUsed); cache.set(signature, executed); + if (executed.ok && STATE_CHANGING_TOOLS.has(turn.tool)) { + // A mutation invalidates prior read evidence. Re-serving a pre-change + // review after a successful selection is exactly how coverage appeared + // to regress. Keep the mutation's own cache entry, but force later + // reads to execute against the new authoritative state. + for (const [key, value] of cache) { + if (key !== signature && EVIDENCE_READ_TOOLS.has(value.tool)) cache.delete(key); + } + cachedRepeatServes.clear(); + } detectBlock(executed); // H-2S: a repeated EQUIVALENT failure ends the turn with a truthful // account instead of consuming the rest of the budget. diff --git a/src/application/shisoNutritionReview.ts b/src/application/shisoNutritionReview.ts index d450421..eb24ac4 100644 --- a/src/application/shisoNutritionReview.ts +++ b/src/application/shisoNutritionReview.ts @@ -29,6 +29,7 @@ import { buildShisoNutrientCoverage, deriveNutritionCoverage, nutritionCoverageS import type { ShisoNutritionSnapshot } from '../application-ui/shisoEntryPoints'; import type { ShisoAnalysisOutcome, ShisoNutritionSourceSelectionOutcome } from '../core/shiso/protocol'; import { buildPortionChoice } from '../core/nutritionV2/phase4/portion'; +import { buildCountPortionChoice } from '../core/nutritionV2/phase4/countPortion'; import { selectionFromMatchChoice } from '../core/nutritionV2/phase4/rows'; export interface ShisoNutritionReviewController { @@ -231,17 +232,41 @@ export function createShisoNutritionReviewController( description: hit.description, }); const selection = selectionFromMatchChoice(match, lineRef); - const portion = buildPortionChoice(session, { - lineRef, - ingredient: entry.ingredient, - review: row.review, - selection, - fdcId, - portionIndex, - }); - if (!portion.ok) return fail('invalid_selection', 'That USDA portion could not be authenticated for this ingredient.'); + const portionReview = session.reviewPortions(fdcId); + const candidate = portionReview.ok + ? portionReview.review.candidates.find((entry) => entry.index === portionIndex) + : undefined; + if (candidate === undefined) { + return fail('invalid_selection', 'That USDA portion is not available for the authenticated food record.'); + } let next = phase4Reducer(state, { type: 'select_match', lineRef, choice: match }); - next = phase4Reducer(next, { type: 'select_portion', lineRef, choice: portion.choice }); + if (candidate.kind === 'count') { + // Count portions use the SAME count builder/action as Advanced Nutrition; + // selecting one through the source-portion action would lose the count + // requirement and fail closed for an otherwise valid authored count. + const count = buildCountPortionChoice(session, { + lineRef, + ingredient: entry.ingredient, + review: row.review, + selection, + fdcId, + portionIndex: candidate.index, + countRequirementHint: { unit: candidate.measure ?? null, size: null }, + }); + if (!count.ok) return fail('invalid_selection', 'That authenticated count portion could not be applied to this ingredient.'); + next = phase4Reducer(next, { type: 'select_count_portion', lineRef, choice: count.choice }); + } else { + const portion = buildPortionChoice(session, { + lineRef, + ingredient: entry.ingredient, + review: row.review, + selection, + fdcId, + portionIndex, + }); + if (!portion.ok) return fail('invalid_selection', 'That USDA portion could not be authenticated for this ingredient.'); + next = phase4Reducer(next, { type: 'select_portion', lineRef, choice: portion.choice }); + } const calculated = session.calculate(buildCalculationRequest(adapted, next)); if (!calculated.ok) return fail('invalid_selection', 'The authenticated nutrition review rejected that source selection.'); const evidence = calculated.preview.ingredients.find((candidate) => candidate.line_ref === lineRef); diff --git a/src/components/ShisoModal.tsx b/src/components/ShisoModal.tsx index 585db51..ab7a66b 100644 --- a/src/components/ShisoModal.tsx +++ b/src/components/ShisoModal.tsx @@ -484,11 +484,31 @@ export function ShisoModal({ // every committed render still replaces it with the application state. const liveNutritionSessionRef = useRef(nutritionSession); liveNutritionSessionRef.current = nutritionSession; + // The same-turn bundle handoff intentionally initializes the independent + // Chat review before React commits the card's session prop. That review is + // the authoritative Chat review for this recipe until the card itself runs + // an analysis. Keeping the owner explicit prevents a later card snapshot from + // silently replacing the review that already holds the verified selections. + const independentReviewActiveRef = useRef(false); + const [independentReviewActive, setIndependentReviewActive] = useState(false); + const activateIndependentReview = useCallback((active: boolean) => { + independentReviewActiveRef.current = active; + setIndependentReviewActive(active); + }, []); + useEffect(() => { + activateIndependentReview(false); + }, [activateIndependentReview, recipe?.id]); + const independentSnapshot = independentReviewActive ? getIndependentNutritionSnapshot?.() ?? null : null; + const effectiveNutritionRows = independentSnapshot?.rows ?? nutritionRows; + const effectiveNutritionContributions = independentSnapshot?.aiContributions ?? nutritionAiContributions; + const effectiveNutritionAvailable = independentSnapshot !== null || nutritionAvailable; const nutritionCoverage = useMemo( - () => nutritionAvailable ? deriveNutritionCoverage(nutritionRows, nutritionAiContributions) : deriveNutritionCoverage([]), - [nutritionAvailable, nutritionRows, nutritionAiContributions] + () => effectiveNutritionAvailable + ? deriveNutritionCoverage(effectiveNutritionRows, effectiveNutritionContributions) + : deriveNutritionCoverage([]), + [effectiveNutritionAvailable, effectiveNutritionRows, effectiveNutritionContributions] ); - const effectiveNutritionSummary = nutritionAvailable ? nutritionCoverageSummary(nutritionCoverage) : null; + const effectiveNutritionSummary = effectiveNutritionAvailable ? nutritionCoverageSummary(nutritionCoverage) : null; const workingStateNote = useMemo(() => { const parts: string[] = []; if (shiso.workingRecipe !== null && shiso.workingRecipe.unsaved) { @@ -589,6 +609,7 @@ export function ShisoModal({ get nutrition() { const current = latest.current; const independent = getIndependentNutritionSnapshot?.(); + if (independentReviewActiveRef.current && independent !== null && independent !== undefined) return independent; if (!current.nutritionAvailable && independent !== null && independent !== undefined) return independent; return current.nutritionAvailable ? { @@ -612,15 +633,20 @@ export function ShisoModal({ // analyzer/calculator through a read-only handoff instead of requiring a // manual modal open. runAnalysis: async (signal) => { - if (shisoRef.current.canRunAnalysis && nutritionSession !== null) return shisoRef.current.runAnalysis(); + if (shisoRef.current.canRunAnalysis && nutritionSession !== null) { + activateIndependentReview(false); + return shisoRef.current.runAnalysis(); + } const currentRecipe = currentToolRecipe(); if ( runIndependentNutritionAnalysis !== undefined && currentRecipe !== null && liveNutritionSessionRef.current !== null ) { + activateIndependentReview(true); return runIndependentNutritionAnalysis(currentRecipe, liveNutritionSessionRef.current, signal); } + activateIndependentReview(false); return shisoRef.current.runAnalysis(); }, runAiNutrition: async (signal, options) => { @@ -720,9 +746,31 @@ export function ShisoModal({ }, get applyNutritionSourceSelection() { const cardOwnerAvailable = shisoRef.current.canApplyNutritionSourceSelection; - if (!cardOwnerAvailable && applyIndependentNutritionSourceSelection === undefined) return undefined; + const independent = getIndependentNutritionSnapshot?.() ?? null; + // A recipe card can register its selection capability before its own + // review exists. The published `nutritionAvailable` snapshot is the + // authority that says the card review is the active one. When the review + // was initialized through the independent Chat owner, that owner must + // also receive every selection; otherwise the next turn reads a review + // that never saw them and coverage silently regresses. + const preferIndependent = independentReviewActiveRef.current && independent !== null; + if (!cardOwnerAvailable && !preferIndependent && applyIndependentNutritionSourceSelection === undefined) return undefined; return async (input: Parameters>[0]) => { - let result = cardOwnerAvailable + let result; + if (preferIndependent && applyIndependentNutritionSourceSelection !== undefined) { + result = await applyIndependentNutritionSourceSelection(input); + // A real independent rejection is authoritative. Only an ownership + // failure may fall back to the card owner. + if ( + !result.ok && + cardOwnerAvailable && + (result.code === 'no_active_review' || result.code === 'no_nutrition_review' || result.code === 'stale_recipe') + ) { + result = await shisoRef.current.applyNutritionSourceSelection(input); + } + return result; + } + result = cardOwnerAvailable ? await shisoRef.current.applyNutritionSourceSelection(input) : await applyIndependentNutritionSourceSelection!(input); // A mounted recipe card can be registered while its own review has diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index 6ff69f1..3998e08 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -735,4 +735,146 @@ describe('SHISO agent foundation real App save closure', () => { expect(persisted.recipes.find((entry) => entry.title === 'Live Acceptance Breakfast')?.codexNutrition).toBeUndefined(); }, 120000); + const BREAKFAST_LINES = [ + '2 cups chopped vegetables (such as red onion, bell pepper, mushrooms or broccoli)', + '1 pound breakfast sausage or Italian sausage', + '2 pinches salt', + '2 teaspoons unsalted butter', + '8 burrito-size tortillas', + '2 cups shredded cheddar cheese (or Monterey Jack)', + '8 large eggs', + '1 cup milk', + ]; + const BREAKFAST_INITIAL = "SHISO, investigate the unresolved nutrition for this recipe. Use authenticated USDA sources to resolve everything you confidently can. Ask one consolidated question about anything requiring my choice. Do not Apply or Save."; + const BREAKFAST_ANSWERS = "Vegetables: 1 cup chopped red onion and 1 cup chopped bell pepper. Sausage: breakfast sausage. Cheese: sharp cheddar only. Salt: regular table salt. Tortillas: standard burrito-size flour tortillas. Estimate salt and tortilla weights only when defensible. Do not Apply or Save."; + const BASE_BREAKFAST_RECORDS = [ + { fdcId: 51, dataType: 'sr_legacy', description: 'Butter, without salt', portions: [{ amount: 1, measure: 'tbsp', gram_weight: 14.2, sequence: 1 }, { amount: 1, measure: 'cup', gram_weight: 227, sequence: 2 }] }, + { fdcId: 52, dataType: 'sr_legacy', description: 'Cheese, cheddar', portions: [{ amount: 1, measure: 'slice', gram_weight: 17, sequence: 1 }, { amount: 1, measure: 'cup', gram_weight: 105, sequence: 2 }] }, + { fdcId: 53, dataType: 'sr_legacy', description: 'Egg, whole, raw', portions: [{ amount: 1, measure: 'egg', gram_weight: 50, sequence: 1 }] }, + { fdcId: 54, dataType: 'sr_legacy', description: 'Milk, whole', portions: [{ amount: 1, measure: 'cup', gram_weight: 244, sequence: 1 }] }, + { fdcId: 55, dataType: 'sr_legacy', description: 'Tortilla, flour', portions: [{ amount: 1, measure: 'package', gram_weight: 407, sequence: 1 }] }, + { fdcId: 56, dataType: 'sr_legacy', description: 'Sausage, turkey, breakfast links, mild, raw', portions: [{ amount: 1, measure: 'link', gram_weight: 28, sequence: 1 }] }, + { fdcId: 57, dataType: 'sr_legacy', description: 'Salt, table', portions: [{ amount: 1, measure: 'tsp', gram_weight: 6, sequence: 1 }] }, + { fdcId: 58, dataType: 'sr_legacy', description: 'Raw vegetable, NFS', portions: [{ amount: 1, measure: 'cup', gram_weight: 120, sequence: 1 }] }, + ]; + + async function setupBreakfastApp( + title: string, + recordSpecs: ReadonlyArray, + script: ReadonlyArray, + ) { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-continuation-')); + roots.push(rootPath); + const recipePath = join(rootPath, 'Recipes', 'Dinner', `${title}.md`); + await mkdir(dirname(recipePath), { recursive: true }); + await writeFile(recipePath, [ + '---', `title: "${title}"`, 'tags:', ' - food/recipes', + 'category: Breakfast', 'servings: 4', '---', `# ${title}`, + '## Ingredients', + ...BREAKFAST_LINES.map((line) => `- ${line}`), + '## Instructions', '1. Cook the filling.', '2. Fill and roll.', '', + ].join('\n'), 'utf8'); + const root = new DiskDirectoryHandle(`Disposable ${title} Vault`, rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + const { manifest, records } = buildMatchingBundle(recordSpecs as never); + const created = createAdvancedNutritionSession(manifest, records); + if (!created.ok) throw new Error('fixture USDA session failed'); + const loader = vi.fn(async (): Promise => ({ + ok: true, session: created.session, metadata: created.session.metadata(), attribution: USDA_ATTRIBUTION, + })); + const captured = capturingNetwork(script, { + '/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(new RegExp(`Connected live to vault "Disposable ${title} Vault"`)); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: title })); + fireEvent.click(await screen.findByTestId('recipe-shiso-entry')); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: BREAKFAST_INITIAL } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toMatch(/authenticated source.*\(.*g\)/i), { timeout: 25000 }); + return { composer, captured, root }; + } + + it('AUDIT continuation preserves four verified selections and processes the exact owner answers into concrete blockers', async () => { + const title = 'Continuation Integrity Breakfast'; + const { composer, captured, root } = await setupBreakfastApp(title, BASE_BREAKFAST_RECORDS, [ + { ok: true, kind: 'reply', text: 'unused deterministic reply', proposals: [] }, + ]); + const before = captured.turns.length; + fireEvent.change(composer, { target: { value: BREAKFAST_ANSWERS } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('I processed your answers'), { timeout: 20000 }); + const body = document.body.textContent ?? ''; + expect(captured.turns.length).toBe(before); + expect(body).toMatch(/Previously verified selections remain attached/i); + expect(body).toMatch(/Butter, without salt/); + expect(body).toMatch(/Cheese, cheddar/); + expect(body).toMatch(/4 of 8 ingredient lines are source-backed/i); + expect(body).toMatch(/multi-ingredient mixture/i); + expect(body).toMatch(/no authenticated mass portion/i); + expect(body).toMatch(/pinches/i); + expect(body).toMatch(/per-item count portion/i); + expect(body).toMatch(/sharp cheddar only/i); + expect(body).toMatch(/Nothing was applied or saved/i); + expect(body).not.toMatch(/Open Advanced Nutrition/i); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((entry) => entry.title === title)?.codexNutrition).toBeUndefined(); + }, 120000); + + it('AUDIT continuation executes supported volume and count selections without Apply or Save', async () => { + const title = 'Continuation Supported Breakfast'; + const { composer, captured, root } = await setupBreakfastApp(title, [ + ...BASE_BREAKFAST_RECORDS.filter((record) => record.fdcId !== 55), + { fdcId: 55, dataType: 'sr_legacy', description: 'Tortilla, flour, burrito-size', portions: [{ amount: 1, measure: 'piece', modifier: 'tortilla', gram_weight: 45, sequence: 1 }] }, + { fdcId: 59, dataType: 'sr_legacy', description: 'Cheese, cheddar, sharp', portions: [{ amount: 1, measure: 'cup', gram_weight: 113, sequence: 1 }] }, + ], [ + { ok: true, kind: 'reply', text: 'unused deterministic reply', proposals: [] }, + ]); + const before = captured.turns.length; + fireEvent.change(composer, { target: { value: BREAKFAST_ANSWERS } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Executed 2 supported selections'), { timeout: 20000 }); + const body = document.body.textContent ?? ''; + expect(captured.turns.length).toBe(before); + expect(body).toMatch(/8 burrito-size tortillas.*360 g/i); + expect(body).toMatch(/2 cups shredded cheddar cheese.*226 g/i); + expect(body).toMatch(/5 of 8 ingredient lines are source-backed/i); + expect(body).toMatch(/Previously verified selections remain attached/i); + expect(body).toMatch(/Nothing was applied or saved/i); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((entry) => entry.title === title)?.codexNutrition).toBeUndefined(); + }, 120000); + + it('AUDIT a repeated successful review read is served from cache and does not end the task', async () => { + const title = 'Continuation Cache Breakfast'; + const { composer, captured } = await setupBreakfastApp(title, BASE_BREAKFAST_RECORDS, [ + { ok: true, kind: 'tool_request', tool: 'get_nutrition_review', args: { tool: 'get_nutrition_review', include_ingredients: true } }, + { ok: true, kind: 'tool_request', tool: 'get_nutrition_review', args: { tool: 'get_nutrition_review', include_ingredients: true } }, + { ok: true, kind: 'reply', text: 'Cache continuation completed.', proposals: [] }, + ]); + const before = captured.turns.length; + fireEvent.change(composer, { target: { value: 'Please continue the review.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Cache continuation completed.'), { timeout: 20000 }); + expect(captured.turns.length).toBe(before + 3); + const second = captured.turns[before + 1]?.['observation'] as any; + const third = captured.turns[before + 2]?.['observation'] as any; + expect(second?.data?.resolved).toBe(4); + expect(third?.data?.resolved).toBe(4); + expect(JSON.stringify(third)).toContain('Butter, without salt'); + expect(JSON.stringify(third)).toContain('Cheese, cheddar'); + expect(document.body.textContent).not.toMatch(/already verified the same get_nutrition_review request/i); + }, 120000); + }); diff --git a/tests/unit/shisoLiveAcceptance.test.ts b/tests/unit/shisoLiveAcceptance.test.ts index 9216b4d..3cad344 100644 --- a/tests/unit/shisoLiveAcceptance.test.ts +++ b/tests/unit/shisoLiveAcceptance.test.ts @@ -23,6 +23,8 @@ const LINES = [ '8 large eggs', '1 cup milk', ]; +const OWNER_ANSWERS = "Vegetables: 1 cup chopped red onion and 1 cup chopped bell pepper. Sausage: breakfast sausage. Cheese: sharp cheddar only. Salt: regular table salt. Tortillas: standard burrito-size flour tortillas. Estimate salt and tortilla weights only when defensible. Do not Apply or Save."; +const INITIAL_REQUEST = "SHISO, investigate the unresolved nutrition for my Breakfast Burritos recipe. Use your available tools to identify the correct ingredients, find authenticated USDA sources, and resolve everything you can confidently resolve. Reject inappropriate food matches. Don't guess which ingredient alternatives I used. If you need information from me, ask one consolidated question covering all outstanding choices. Show me exactly what you've accomplished and what remains unresolved. Do not Apply or Save anything yet."; let session: AdvancedNutritionSession; @@ -37,67 +39,74 @@ beforeAll(async () => { session = composed.session; }, 180000); +function liveRecipe(): ObsidianRecipe { + return { + id: 'breakfast-live', + fileName: 'Breakfast Burritos.md', + filePath: 'Recipes/Breakfast Burritos.md', + rawMarkdown: '', + title: 'Breakfast Burritos', + tags: ['food/recipes'], + category: 'Breakfast', + cuisine: 'Mexican', + difficulty: 'Easy', + rating: 0, + servings: 4, + ingredients: LINES.map((original) => { + const parsed = parseIngredient(original); + return { + original, + name: parsed.ok ? parsed.parsed.query : original, + ...(parsed.ok && parsed.parsed.amount !== null ? { amount: parsed.parsed.amount } : {}), + ...(parsed.ok && parsed.parsed.raw_unit !== undefined ? { unit: parsed.parsed.raw_unit } : {}), + }; + }), + instructions: [{ text: 'Cook the filling and fill the tortillas.' }], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, + } as unknown as ObsidianRecipe; +} + +function liveToolContext(recipe: ObsidianRecipe) { + const view = toShisoRecipeView(recipe); + if (view === null) throw new Error('recipe view failed'); + const controller = createShisoNutritionReviewController(recipe, session); + if (controller === null) throw new Error('review controller failed'); + let analyzed = false; + const toolContext = { + session, + recipe: view, + get nutrition() { return analyzed ? controller.getSnapshot() : null; }, + runAnalysis: () => { + analyzed = true; + return controller.analyze(); + }, + acceptNutritionContributions: () => true, + applyNutritionSourceSelection: (input: never) => controller.selectUsdaNutritionSource(input), + } as never; + return { controller, toolContext }; +} + +const network = { + request: async () => ({ status: 200, ok: true, data: {} }), + get: async () => ({ status: 200, ok: true, data: {} }), + post: async () => ({ status: 200, ok: true, data: { ok: true, kind: 'reply', text: 'unused', model_invocations_used: 1, tool_calls_used: 1 } }), +} as never; + +const context = { + recipe: { title: 'Breakfast Burritos', ingredientCount: 8, stepCount: 1, servings: 4 }, + nutrition: { available: false, summary: null, unresolvedCount: 8, needsAmountCount: 0, needsMatchCount: 8, unsavedWorkingReview: false }, + recipeKey: 'breakfast-live', + sessionIdentity: 'session-breakfast-live', +}; + describe('SHISO live acceptance — self-initialized real-catalogue investigation', () => { it('initializes without Advanced Nutrition, selects defensible real USDA lines, and asks once', async () => { - const recipe = { - id: 'breakfast-live', - fileName: 'Breakfast Burritos.md', - filePath: 'Recipes/Breakfast Burritos.md', - rawMarkdown: '', - title: 'Breakfast Burritos', - tags: ['food/recipes'], - category: 'Breakfast', - cuisine: 'Mexican', - difficulty: 'Easy', - rating: 0, - servings: 4, - ingredients: LINES.map((original) => { - const parsed = parseIngredient(original); - return { - original, - name: parsed.ok ? parsed.parsed.query : original, - ...(parsed.ok && parsed.parsed.amount !== null ? { amount: parsed.parsed.amount } : {}), - ...(parsed.ok && parsed.parsed.raw_unit !== undefined ? { unit: parsed.parsed.raw_unit } : {}), - }; - }), - instructions: [{ text: 'Cook the filling and fill the tortillas.' }], - callouts: [], - dataviewFields: {}, - wikilinks: [], - frontmatter: {}, - } as unknown as ObsidianRecipe; - const view = toShisoRecipeView(recipe); - if (view === null) throw new Error('recipe view failed'); - const controller = createShisoNutritionReviewController(recipe, session); - if (controller === null) throw new Error('review controller failed'); - let currentSnapshot: ReturnType = null; - const toolContext = { - session, - recipe: view, - get nutrition() { return currentSnapshot; }, - runAnalysis: () => { - const outcome = controller.analyze(); - currentSnapshot = controller.getSnapshot(); - return outcome; - }, - acceptNutritionContributions: () => true, - applyNutritionSourceSelection: (input: never) => controller.selectUsdaNutritionSource(input), - } as never; - - const outcome = await runShisoConversationTurn({ - network: { - request: async () => ({ status: 200, ok: true, data: {} }), - get: async () => ({ status: 200, ok: true, data: {} }), - post: async () => ({ status: 200, ok: true, data: { ok: true, kind: 'reply', text: 'unused', model_invocations_used: 1, tool_calls_used: 1 } }), - } as never, - context: { - recipe: { title: recipe.title, ingredientCount: 8, stepCount: 1, servings: 4 }, - nutrition: { available: false, summary: null, unresolvedCount: 8, needsAmountCount: 0, needsMatchCount: 8, unsavedWorkingReview: false }, - recipeKey: 'breakfast-live', - sessionIdentity: 'session-breakfast-live', - }, - toolContext, - }, initialShisoConversation(), "SHISO, investigate the unresolved nutrition for my Breakfast Burritos recipe. Use your available tools to identify the correct ingredients, find authenticated USDA sources, and resolve everything you can confidently resolve. Reject inappropriate food matches. Don't guess which ingredient alternatives I used. If you need information from me, ask one consolidated question covering all outstanding choices. Show me exactly what you've accomplished and what remains unresolved. Do not Apply or Save anything yet."); + const recipe = liveRecipe(); + const { controller, toolContext } = liveToolContext(recipe); + const outcome = await runShisoConversationTurn({ network, context, toolContext }, initialShisoConversation(), INITIAL_REQUEST); expect(outcome.ok).toBe(true); expect(outcome.toolsUsed).toContain('run_nutrition_analysis'); @@ -124,4 +133,43 @@ describe('SHISO live acceptance — self-initialized real-catalogue investigatio expect(tortillas?.selected_fdc_id ?? null).toBeNull(); expect(rows.filter((row) => row.status !== 'matched').length).toBeGreaterThan(0); }, 180000); + + it('processes the exact owner answers without losing the four verified real-catalogue selections', async () => { + const recipe = liveRecipe(); + const { controller, toolContext } = liveToolContext(recipe); + const initial = await runShisoConversationTurn({ network, context, toolContext }, initialShisoConversation(), INITIAL_REQUEST); + expect(initial.ok).toBe(true); + expect(controller.getSnapshot()!.rows.filter((row) => row.status === 'matched')).toHaveLength(4); + + const continuation = await runShisoConversationTurn( + { network, context, toolContext }, + initial.state, + OWNER_ANSWERS, + ); + + expect(continuation.ok).toBe(true); + expect(continuation.message).toMatch(/I processed your answers/i); + expect(continuation.message).toMatch(/No new authenticated source could be selected without guessing/i); + expect(continuation.message).toMatch(/multi-ingredient mixture/i); + expect(continuation.message).toMatch(/breakfast sausage/i); + expect(continuation.message).toMatch(/no authenticated mass portion/i); + expect(continuation.message).toMatch(/pinches/i); + expect(continuation.message).toMatch(/per-item count portion/i); + expect(continuation.message).toMatch(/sharp cheddar/i); + expect(continuation.message).toMatch(/existing Cheese, cheddar selection remains/i); + expect(continuation.message).toMatch(/Previously verified selections remain attached/i); + expect(continuation.message).toMatch(/Butter, without salt/); + expect(continuation.message).toMatch(/Cheese, cheddar/); + expect(continuation.message).toMatch(/4 of 8 ingredient lines are source-backed/i); + expect(continuation.message).toMatch(/Nothing was applied or saved/i); + expect(continuation.toolsUsed).not.toContain('apply_nutrition_review'); + expect(continuation.toolsUsed).not.toContain('save_working_recipe'); + + const rows = controller.getSnapshot()!.rows; + expect(rows.filter((row) => row.status === 'matched')).toHaveLength(4); + expect(rows.find((row) => row.original_text.includes('unsalted butter'))).toMatchObject({ status: 'matched', selected_description: 'Butter, without salt' }); + expect(rows.find((row) => row.original_text.includes('cheddar cheese'))).toMatchObject({ status: 'matched', selected_description: 'Cheese, cheddar' }); + expect(rows.find((row) => row.original_text.includes('breakfast sausage'))?.status).not.toBe('matched'); + expect(rows.find((row) => row.original_text.includes('burrito-size tortillas'))?.status).not.toBe('matched'); + }, 180000); }); From de10a90baad0b711465fba76289a352c118950e9 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 28 Nov 2026 11:32:59 -0500 Subject: [PATCH 2/2] fix(shiso): keep mutation replays terminal while cached reads continue --- src/application/shisoConversation.ts | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index 6e3e5fe..c6bb1f9 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -682,6 +682,27 @@ export async function runShisoConversationTurn( 'run_nutrition_analysis', 'apply_nutrition_review', 'save_working_recipe', + 'select_vault_recipe', + 'load_usda_catalog', + ]); + /** + * Only genuinely read-only capabilities may be re-served from cache and + * continue. Anything that can change recipe, review, selection, application, + * or persistence state is deliberately excluded and keeps the terminal + * replay-refusal behavior. + */ + const READ_ONLY_CACHED_CONTINUATION_TOOLS: ReadonlySet = new Set([ + 'get_current_recipe', + 'get_nutrition_review', + 'get_branded_evidence', + 'search_usda_foods', + 'inspect_usda_food', + 'investigate_ingredient_amount', + 'investigate_unresolved_ingredients', + 'get_vault_status', + 'search_vault_recipes', + 'get_vault_recipe', + 'get_capability_status', ]); /** H-2S: tool signature -> how many times an EQUIVALENT failure occurred. */ const failureCounts = new Map(); @@ -1325,6 +1346,20 @@ export async function runShisoConversationTurn( }; } if (cached.ok) { + if (!READ_ONLY_CACHED_CONTINUATION_TOOLS.has(turn.tool)) { + // A mutation replay must not advance as a harmless read. It already + // happened once; keep the established terminal refusal (including + // the Save replay message the H-2 adversarial test expects). + return { + ok: true, + state: working, + message: deterministicReport( + `I already verified the same ${turn.tool} request in this message, so I stopped instead of repeating it.`, + ), + status: null, + toolsUsed, + }; + } // A repeated SUCCESSFUL read is evidence, not a terminal event. Serve // the cached observation without charging the tool budget, and let the // model continue with the same verified facts. Only a genuinely