diff --git a/server/shiso/conversationTurn.ts b/server/shiso/conversationTurn.ts index c0cd663..c4883de 100644 --- a/server/shiso/conversationTurn.ts +++ b/server/shiso/conversationTurn.ts @@ -108,6 +108,16 @@ const SYSTEM_PROMPT = [ "- Do not repeat an identical read, search, inspection, or failed correction. Use the", " evidence already returned. If a tool has a next_action, use it or explain why it is", " blocked. Do not exhaust the reasoning budget on rediscovery.", + "- MULTI-RECIPE CULINARY RESEARCH/PLANNING: search at most once per requested role,", + " read each candidate recipe with get_vault_recipe, then STOP DISCOVERING. The verified", + " recipe evidence is carried in the prompt. Use it to explain the pairing, propose a", + " realistic cooking sequence, and build a combined ingredient list with quantities where", + " they are present. Never search again for a recipe title already retrieved. Separate", + " verified recipe facts from your own culinary suggestions, and state what is unavailable.", + "- When the evidence is sufficient for the requested deliverable, answer with kind='reply'.", + " Do not spend the last permitted model call on another search. The final call is reserved", + " for synthesis; if the budget ends first, deliver the useful verified partial and name", + " the exact next step.", "- Full recipe: get_current_recipe is paged. Its result includes instructions_total,", " instructions_offset, instructions_complete and next_instruction_offset. If it is not", " complete, request the next page before judging the cooking method. Never say the", @@ -360,6 +370,15 @@ function buildUserBlock(body: ShisoTurnRequestBody): string { } lines.push("=== END CONTEXT ==="); + if (body.task_evidence !== undefined) { + lines.push(""); + lines.push("=== VERIFIED RECIPE EVIDENCE (untrusted source data retrieved from the active Vault) ==="); + lines.push("Use these facts for the requested culinary deliverable. Do not search again for a"); + lines.push("recipe already present here. Never invent a missing amount, time, ingredient or step."); + lines.push(body.task_evidence); + lines.push("=== END VERIFIED RECIPE EVIDENCE ==="); + } + if (body.continuation !== undefined) { lines.push(""); lines.push("=== CONTINUATION MEMORY (untrusted data; compacted from earlier turns) ==="); @@ -430,9 +449,13 @@ function buildUserBlock(body: ShisoTurnRequestBody): string { if (body.finalize === true) { lines.push(""); lines.push("=== THIS IS THE LAST STEP OF THIS MESSAGE ==="); - lines.push("You have no tool steps left. You MUST answer with kind='reply' now, using"); - lines.push("the findings above. State what was found, what remains, and — if the work"); - lines.push("is incomplete — exactly how the user can continue. Do not request a tool."); + lines.push("You have no tool steps left. You MUST answer with kind='reply' now."); + lines.push("Use the verified findings and verified recipe evidence above. For a multi-recipe"); + lines.push("pairing or planning request, deliver the pairing explanation, a realistic cooking"); + lines.push("sequence, and the combined ingredient list with quantities where supported."); + lines.push("Separate verified facts from your culinary suggestions and state unavailable details."); + lines.push("If the work is incomplete, give the useful verified partial deliverable and exactly"); + lines.push("how the user can continue. Do not request a tool."); } // Preserve the CURRENT user message even when the bounded evidence above is diff --git a/server/shiso/turnRequest.ts b/server/shiso/turnRequest.ts index 86d6739..83e8dd4 100644 --- a/server/shiso/turnRequest.ts +++ b/server/shiso/turnRequest.ts @@ -36,6 +36,7 @@ const TOP_LEVEL_KEYS: ReadonlySet = new Set([ "context", "observation", "collected", + "task_evidence", "finalize", "model_invocations_used", "tool_calls_used", @@ -214,6 +215,9 @@ export function readShisoTurnRequest(raw: unknown): ShisoTurnRequestBody | null const observation = readObservation(raw["observation"]); const collected = readCollected(raw["collected"]); const continuation = readContinuation(raw["continuation"]); + const taskEvidence = typeof raw["task_evidence"] === "string" + ? raw["task_evidence"].trim().slice(0, SHISO_LIMITS.maxTaskEvidenceChars) + : ""; return { turn_version: SHISO_TURN_CONTRACT_VERSION, user_message: trimmed, @@ -222,6 +226,7 @@ export function readShisoTurnRequest(raw: unknown): ShisoTurnRequestBody | null context: readContext(raw["context"]), ...(observation !== undefined ? { observation } : {}), ...(collected.length > 0 ? { collected } : {}), + ...(taskEvidence.length > 0 ? { task_evidence: taskEvidence } : {}), ...(raw["finalize"] === true ? { finalize: true } : {}), model_invocations_used: boundedInt(raw["model_invocations_used"], 1000), tool_calls_used: boundedInt(raw["tool_calls_used"], 1000), diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index c6bb1f9..a473e4d 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -42,6 +42,11 @@ import type { NetworkAdapter, NetworkResponse } from './adapters/NetworkAdapter' import { buildAiSelectionRequestOptions } from './aiSelection'; import { executeShisoTool, type ShisoToolContext } from './shisoTools'; import { tryCulinaryChoiceContinuation } from './shisoChoiceContinuation'; +import { + captureShisoTaskEvidence, + createShisoTaskEvidenceStore, + renderShisoTaskEvidence, +} from './shisoTaskEvidence'; import { planDeterministicIngredientEdit } from '../core/shiso/deterministicEdit'; import { classifySaveIntent } from '../core/shiso/saveAuthorization'; import { @@ -661,6 +666,8 @@ export async function runShisoConversationTurn( const cache = new Map(); /** Cached successful reads served without a new tool execution. */ const cachedRepeatServes = new Map(); + /** Bounded Vault recipe facts retained across multi-step tool work. */ + const taskEvidence = createShisoTaskEvidenceStore(); const EVIDENCE_READ_TOOLS: ReadonlySet = new Set([ 'get_current_recipe', 'get_nutrition_review', @@ -1144,13 +1151,20 @@ export async function runShisoConversationTurn( collected.length === 0 ? 'I did not gather any results before this stopped.' : collected.map((f, i) => `${i + 1}. **${f.tool}** — ${f.summary}`).join('\n'); + const facts = renderShisoTaskEvidence(taskEvidence); + const factsBlock = facts.length > 0 + ? `\n\n**Verified recipe facts already retrieved (untrusted source data):**\n${facts}` + : ''; + const continuation = facts.length > 0 + ? '\n\nTo continue, ask me to finish the pairing, cooking sequence and combined ingredient list from these verified recipes.' + : ''; const editAttempted = toolsUsed.some((tool) => EDITING_TOOLS.has(tool)); const editSucceeded = collected.some((f) => f.ok && EDITING_TOOLS.has(f.tool)); const changeNote = editAttempted && !editSucceeded ? '\n\n**No recipe change was applied in this message.** No edit or save succeeded, so your working copy is exactly as it was.' : ''; - return `${lead}\n\n${body}${changeNote}`; + return `${lead}\n\n${body}${factsBlock}${continuation}${changeNote}`; }; /** @@ -1228,7 +1242,12 @@ export async function runShisoConversationTurn( // counter the server also enforces, or exhausts the hard ceiling below. for (let step = 0; step <= SHISO_LIMITS.maxModelInvocationsPerTurn; step += 1) { if (deps.signal?.aborted) return cancelled(working, toolsUsed); - const outOfModels = modelInvocations >= SHISO_LIMITS.maxModelInvocationsPerTurn; + // Reserve the final permitted model invocation for the answer itself. If + // the client waits until the ceiling to set `finalize`, the finalize request + // is a seventh call and the server correctly refuses it; the user then sees + // only a budget error. Five tool steps + the sixth call for synthesis is the + // hard-ceiling-preserving contract. + const outOfModels = modelInvocations >= Math.max(1, SHISO_LIMITS.maxModelInvocationsPerTurn - 1); const outOfTools = toolCalls >= SHISO_LIMITS.maxToolCallsPerTurn; // Guarantee a report: the FIRST time either budget is spent, spend the next @@ -1245,6 +1264,7 @@ export async function runShisoConversationTurn( if (sendFinalize) finalizeSent = true; const continuation = buildShisoContinuation(working, deps.workingStateNote); + const taskFacts = renderShisoTaskEvidence(taskEvidence); const body: ShisoTurnRequestBody = { turn_version: SHISO_TURN_CONTRACT_VERSION, user_message: trimmed, @@ -1253,6 +1273,7 @@ export async function runShisoConversationTurn( context: boundContext(deps.context), ...(observation !== undefined ? { observation } : {}), ...(collected.length > 0 ? { collected: Object.freeze([...collected]) } : {}), + ...(taskFacts.length > 0 ? { task_evidence: taskFacts } : {}), ...(sendFinalize ? { finalize: true } : {}), model_invocations_used: modelInvocations, tool_calls_used: toolCalls, @@ -1291,7 +1312,9 @@ export async function runShisoConversationTurn( if (!response || response.ok !== true || data === undefined || data.ok !== true) { const failure = data as { code?: unknown; message?: unknown } | undefined; const message = typeof failure?.message === 'string' ? failure.message : null; - const lead = message ?? 'Shiso is unavailable right now.'; + const lead = failure?.code === 'budget_exhausted' + ? "Shiso reached this message's reasoning budget before finishing the full culinary task." + : message ?? 'Shiso is unavailable right now.'; // H-1F: the provider failing is NOT a reason to throw away real USDA // evidence. This is the case that produced "try a shorter message" while // six verified records sat unused in the browser. @@ -1422,7 +1445,10 @@ export async function runShisoConversationTurn( } // A failure is never recorded as a finding — it is either a real result or // the one prerequisite that stops the turn. - if (executed.ok) retain(executed); + if (executed.ok) { + captureShisoTaskEvidence(taskEvidence, executed); + retain(executed); + } observation = executed; toolsUsed.push(turn.tool); deps.onProgress?.({ kind: 'tool', step: toolCalls, tool: turn.tool, ok: executed.ok }); diff --git a/src/application/shisoTaskEvidence.ts b/src/application/shisoTaskEvidence.ts new file mode 100644 index 0000000..07c93ce --- /dev/null +++ b/src/application/shisoTaskEvidence.ts @@ -0,0 +1,162 @@ +/** + * SHISO — bounded, application-produced recipe evidence for multi-step tasks. + * + * The model sees only the observation returned by the immediately preceding + * tool call. A multi-recipe research task therefore loses the first recipe's + * facts as soon as the second recipe is retrieved. This module keeps a small, + * bounded, verified transcript of exactly the Vault recipe facts needed for a + * culinary deliverable: identity, servings, timing, authored ingredients and + * instructions. It never invents a missing value and never carries the Vault + * filesystem or an unbounded recipe payload. + */ + +import { SHISO_LIMITS, type ShisoObservation } from '../core/shiso/protocol'; + +const MAX_RECIPES = 4; +const MAX_RECIPE_CHARS = 2200; +const MAX_INGREDIENTS = 40; +const MAX_INSTRUCTIONS = 24; +const MAX_STEP_CHARS = 360; + +interface RecipeEvidence { + readonly title: string; + readonly provenance: string; + servings: string; + timing: string; + ingredients: string[]; + ingredientTotal: number; + ingredientsTruncated: boolean; + instructions: Map; + instructionTotal: number; + instructionsTruncated: boolean; +} + +export interface ShisoTaskEvidenceStore { + readonly recipes: Map; +} + +export function createShisoTaskEvidenceStore(): ShisoTaskEvidenceStore { + return { recipes: new Map() }; +} + +function text(value: unknown, limit = 400): string { + return typeof value === 'string' ? value.trim().slice(0, limit) : ''; +} + +function numberValue(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null; +} + +function ingredientText(entry: unknown): string { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return ''; + const item = entry as Record; + const authored = text(item['text'], 300); + if (authored.length > 0) return authored; + const amount = typeof item['amount'] === 'number' && Number.isFinite(item['amount']) ? String(item['amount']) : ''; + const unit = text(item['unit'], 40); + const name = text(item['name'], 200); + return `${amount} ${unit} ${name}`.trim(); +} + +function instructionText(entry: unknown): string { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return ''; + return text((entry as Record)['text'], MAX_STEP_CHARS); +} + +function instructionIndex(entry: unknown, fallback: number): number { + if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) { + const index = numberValue((entry as Record)['index']); + if (index !== null) return Math.floor(index); + } + return fallback; +} + +function timingText(data: Record): string { + const parts = [ + ['prep', text(data['prepTime'] ?? data['prep_time'], 80)], + ['cook', text(data['cookTime'] ?? data['cook_time'], 80)], + ['total', text(data['totalTime'] ?? data['total_time'], 80)], + ].filter(([, value]) => value.length > 0); + return parts.length > 0 ? parts.map(([label, value]) => `${label}: ${value}`).join('; ') : 'not provided'; +} + +function identityFor(data: Record): { title: string; provenance: string } { + const title = text(data['title'], 200) || 'Untitled recipe'; + const path = text(data['file_path'] ?? data['filePath'], 240); + const id = text(data['id'], 160); + const provenance = path.length > 0 + ? path + : id.length > 0 + ? `Vault recipe ${id}` + : 'Vault recipe'; + return { title, provenance }; +} + +/** + * Captures only a successful Vault recipe read. Other observations are ignored, + * so the evidence store cannot become an arbitrary tool-output sink. + */ +export function captureShisoTaskEvidence( + store: ShisoTaskEvidenceStore, + observation: ShisoObservation, +): void { + if (!observation.ok || (observation.tool !== 'get_vault_recipe' && observation.tool !== 'get_current_recipe')) return; + const data = observation.data; + const { title, provenance } = identityFor(data); + const key = provenance === 'Vault recipe' ? title : provenance; + const existing = store.recipes.get(key); + const ingredientEntries = Array.isArray(data['ingredients']) ? data['ingredients'] : []; + const ingredients = ingredientEntries + .slice(0, MAX_INGREDIENTS) + .map(ingredientText) + .filter((entry) => entry.length > 0); + const instructions = existing?.instructions ?? new Map(); + const instructionEntries = Array.isArray(data['instructions']) ? data['instructions'] : []; + instructionEntries.slice(0, MAX_INSTRUCTIONS).forEach((entry, index) => { + const step = instructionText(entry); + if (step.length > 0) instructions.set(instructionIndex(entry, index), step); + }); + const instructionTotal = numberValue(data['instructions_total']) ?? instructions.size; + const ingredientsTruncated = data['ingredients_truncated'] === true || ingredientEntries.length > MAX_INGREDIENTS; + const instructionsTruncated = data['instructions_truncated'] === true || data['instructions_complete'] === false; + if (ingredients.length === 0 && instructions.size === 0) return; + store.recipes.set(key, { + title, + provenance, + servings: data['servings'] === undefined || data['servings'] === null ? 'not provided' : text(String(data['servings']), 40), + timing: timingText(data), + ingredients, + ingredientTotal: Math.max(numberValue(data['ingredients_total']) ?? ingredients.length, ingredients.length), + ingredientsTruncated, + instructions, + instructionTotal: Math.max(instructionTotal, instructions.size), + instructionsTruncated, + }); +} + +function renderRecipe(recipe: RecipeEvidence): string { + const sortedSteps = [...recipe.instructions.entries()].sort(([a], [b]) => a - b); + const stepText = sortedSteps.map(([index, step]) => `${index + 1}. ${step}`).join(' '); + const ingredients = recipe.ingredients.join('; '); + const ingredientNote = recipe.ingredientsTruncated ? `, first ${recipe.ingredients.length}` : ''; + const instructionNote = recipe.instructionsTruncated ? `, shown ${sortedSteps.length}` : ''; + const body = [ + `RECIPE: ${recipe.title}`, + `provenance: ${recipe.provenance}`, + `servings: ${recipe.servings}`, + `timing: ${recipe.timing}`, + `ingredients (${recipe.ingredientTotal} total${ingredientNote}): ${ingredients}`, + `instructions (${recipe.instructionTotal} total${instructionNote}): ${stepText || 'not provided'}`, + ].join('\n'); + return body.length <= MAX_RECIPE_CHARS ? body : `${body.slice(0, MAX_RECIPE_CHARS - 1)}…`; +} + +/** + * Renders the bounded evidence sent on every model step. The caller owns the + * final total cap; this function only guarantees each recipe is bounded. + */ +export function renderShisoTaskEvidence(store: ShisoTaskEvidenceStore): string { + const blocks = [...store.recipes.values()].slice(0, MAX_RECIPES).map(renderRecipe); + if (blocks.length === 0) return ''; + return blocks.join('\n\n').slice(0, SHISO_LIMITS.maxTaskEvidenceChars); +} diff --git a/src/core/shiso/protocol.ts b/src/core/shiso/protocol.ts index 5fd001f..b43ae8e 100644 --- a/src/core/shiso/protocol.ts +++ b/src/core/shiso/protocol.ts @@ -77,6 +77,8 @@ export const SHISO_LIMITS = Object.freeze({ maxAssistantMessageChars: 8000, /** Maximum characters of recipe/nutrition context sent per turn. */ maxContextChars: 12000, + /** Bounded verified recipe evidence carried across multi-step Vault tasks. */ + maxTaskEvidenceChars: 5000, /** USDA catalog search result ceiling (the authority's own max is 100). */ maxSearchResults: 20, /** Maximum Vault recipes returned by one agent search. */ @@ -715,6 +717,13 @@ export interface ShisoTurnRequestBody { * spending another tool call. Application-produced strings only. */ readonly collected?: readonly ShisoCollectedFinding[]; + /** + * Application-produced, bounded recipe facts retrieved from the active Vault + * during this turn. It keeps a multi-recipe task from losing the first + * recipe's ingredients, measurements, timings and instructions after a later + * tool call. It is untrusted display/evidence data, never authority. + */ + readonly task_evidence?: string; /** * Set by the client on the last request of a turn, once no further tool call * is affordable. The model MUST answer with what it has; requesting another diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index 3998e08..4947ad3 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -877,4 +877,95 @@ describe('SHISO agent foundation real App save closure', () => { expect(document.body.textContent).not.toMatch(/already verified the same get_nutrition_review request/i); }, 120000); + it('AUDIT multi-recipe culinary research completes with verified recipe facts and a final answer', async () => { + await hydrateAiSelections(settings); + const rootPath = await mkdtemp(join('/tmp', 'tkc-multi-recipe-')); + roots.push(rootPath); + const mainPath = join(rootPath, 'Recipes', 'Main', 'Honey Glazed Salmon.md'); + const sidePath = join(rootPath, 'Recipes', 'Sides', 'Cucumber Salad with Sesame and Rice Vinegar.md'); + await mkdir(dirname(mainPath), { recursive: true }); + await mkdir(dirname(sidePath), { recursive: true }); + const mainMarkdown = [ + '---', 'title: "Honey Glazed Salmon"', 'tags:', ' - food/recipes', ' - main', ' - salmon', + 'category: Main Course', 'cuisine: American', 'servings: 2', + 'prepTime: 15 mins', 'cookTime: 20 mins', 'totalTime: 35 mins', '---', + '# Honey Glazed Salmon', '## Ingredients', + '- 2 salmon fillets (6 oz each)', '- 3 tbsp honey', '- 1 tbsp soy sauce', + '## Instructions', + '1. Heat the oven to 400°F.', '2. Whisk the glaze and brush it over the salmon.', + '3. Roast until the salmon flakes, about 12 minutes.', '', + ].join('\n'); + const sideMarkdown = [ + '---', 'title: "Cucumber Salad with Sesame and Rice Vinegar"', 'tags:', ' - food/recipes', ' - side', ' - salad', + 'category: Side Dish', 'cuisine: Asian', 'servings: 4', + 'prepTime: 10 mins', 'totalTime: 10 mins', '---', + '# Cucumber Salad with Sesame and Rice Vinegar', '## Ingredients', + '- 2 cucumbers, thinly sliced', '- 1 tbsp rice vinegar', '- 1 tsp sesame oil', + '## Instructions', + '1. Salt the cucumbers and drain for 10 minutes.', '2. Toss with rice vinegar and sesame oil.', '', + ].join('\n'); + await writeFile(mainPath, mainMarkdown, 'utf8'); + await writeFile(sidePath, sideMarkdown, 'utf8'); + const root = new DiskDirectoryHandle('Disposable Multi Recipe Vault', rootPath); + (window as unknown as { showDirectoryPicker: () => Promise }).showDirectoryPicker = async () => root; + const initial = await loadVaultContent(createBrowserVaultAdapter(root)); + const mainId = initial.recipes.find((recipe) => recipe.title === 'Honey Glazed Salmon')?.id; + const sideId = initial.recipes.find((recipe) => recipe.title === 'Cucumber Salad with Sesame and Rice Vinegar')?.id; + if (mainId === undefined || sideId === undefined) throw new Error('multi-recipe fixtures were not scanned'); + + const finalAnswer = [ + 'Pairing: Honey Glazed Salmon with Cucumber Salad.', + 'Cooking sequence: start the salmon glaze, roast the salmon, then toss the salad while it rests.', + 'Combined ingredients: 2 salmon fillets, 3 tbsp honey, 1 tbsp soy sauce, 2 cucumbers, 1 tbsp rice vinegar, 1 tsp sesame oil.', + 'Suggestions: add sesame seeds or scallions to the salad. These are culinary suggestions, not verified recipe facts.', + 'Unavailable: the Vault does not provide an exact weight beyond the authored salmon line.', + ].join(' '); + const captured = capturingNetwork([ + { ok: true, kind: 'tool_request', tool: 'search_vault_recipes', args: { tool: 'search_vault_recipes', query: 'main', limit: 10 } }, + { ok: true, kind: 'tool_request', tool: 'search_vault_recipes', args: { tool: 'search_vault_recipes', query: 'side', limit: 10 } }, + { ok: true, kind: 'tool_request', tool: 'get_vault_recipe', args: { tool: 'get_vault_recipe', recipe_id: sideId } }, + { ok: true, kind: 'tool_request', tool: 'search_vault_recipes', args: { tool: 'search_vault_recipes', query: 'salmon', limit: 10 } }, + { ok: true, kind: 'tool_request', tool: 'get_vault_recipe', args: { tool: 'get_vault_recipe', recipe_id: mainId } }, + { ok: true, kind: 'reply', text: finalAnswer, 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 Multi Recipe Vault"/); + fireEvent.click(screen.getByRole('button', { name: 'Close Vault settings' })); + fireEvent.click(await screen.findByRole('button', { name: 'Chat with SHISO' })); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'Search my Vault for a main dish and a side dish. Read both recipes. Explain why they pair, suggest realistic improvements, coordinate the cooking order, and give me a combined ingredient list with quantities. If something is unavailable, say so.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await waitFor(() => expect(document.body.textContent).toContain('Pairing: Honey Glazed Salmon with Cucumber Salad.'), { timeout: 25000 }); + + expect(captured.turns).toHaveLength(6); + const finalBody = captured.turns[5]!; + expect(finalBody['finalize']).toBe(true); + expect(finalBody['model_invocations_used']).toBe(5); + const evidence = String(finalBody['task_evidence'] ?? ''); + expect(evidence).toContain('Honey Glazed Salmon'); + expect(evidence).toContain('Cucumber Salad with Sesame and Rice Vinegar'); + expect(evidence).toContain('2 salmon fillets (6 oz each)'); + expect(evidence).toContain('1 tbsp rice vinegar'); + expect(evidence).toContain('Heat the oven to 400°F.'); + expect(evidence).toContain('Salt the cucumbers'); + expect(document.body.textContent).toContain('Combined ingredients: 2 salmon fillets'); + expect(document.body.textContent).toMatch(/Suggestions:/); + expect(document.body.textContent).toMatch(/Unavailable:/); + const persisted = await loadVaultContent(createBrowserVaultAdapter(root)); + expect(persisted.recipes.find((entry) => entry.title === 'Honey Glazed Salmon')?.codexNutrition).toBeUndefined(); + expect(persisted.recipes.find((entry) => entry.title === 'Cucumber Salad with Sesame and Rice Vinegar')?.codexNutrition).toBeUndefined(); + expect(await readFile(mainPath, 'utf8')).toBe(mainMarkdown); + expect(await readFile(sidePath, 'utf8')).toBe(sideMarkdown); + }, 120000); + }); diff --git a/tests/security/shisoConversation.test.ts b/tests/security/shisoConversation.test.ts index 209b21e..4e4a1f8 100644 --- a/tests/security/shisoConversation.test.ts +++ b/tests/security/shisoConversation.test.ts @@ -40,6 +40,7 @@ import type { SettingsAdapter } from '../../src/application/adapters/SettingsAda import { parseIngredient } from '../../src/core/nutritionV2/matching/parse'; import { isShisoToolName, SHISO_LIMITS } from '../../src/core/shiso/protocol'; import { readShisoTurnRequest } from '../../server/shiso/turnRequest'; +import { SHISO_SYSTEM_PROMPT } from '../../server/shiso/conversationTurn'; const BUNDLE_DIR = join( __dirname, @@ -175,6 +176,26 @@ describe('SHISO — closed vocabulary and argument validation', () => { expect(parsed!.history).toHaveLength(1); }); + it('accepts and bounds verified task evidence in the turn body', () => { + const evidence = 'R'.repeat(SHISO_LIMITS.maxTaskEvidenceChars + 100); + const parsed = readShisoTurnRequest({ + turn_version: 'shiso_turn_request_v1', + user_message: 'finish the multi-recipe plan', + context: { recipe: null, nutrition: { available: false } }, + task_evidence: evidence, + model_invocations_used: 5, + tool_calls_used: 5, + }); + expect(parsed).not.toBeNull(); + expect(parsed!.task_evidence).toHaveLength(SHISO_LIMITS.maxTaskEvidenceChars); + }); + + it('encodes multi-recipe completion discipline in the system prompt', () => { + expect(SHISO_SYSTEM_PROMPT).toContain('MULTI-RECIPE CULINARY RESEARCH/PLANNING'); + expect(SHISO_SYSTEM_PROMPT).toContain('STOP DISCOVERING'); + expect(SHISO_SYSTEM_PROMPT).toContain('final call is reserved'); + }); + it('preserves the bounded stale-recipe diagnostic from nutrition review tools', () => { const parsed = readShisoTurnRequest({ turn_version: 'shiso_turn_request_v1', @@ -629,6 +650,32 @@ describe('SHISO — bounded conversational turn against the real route', () => { expect(prov.calls).toBeLessThanOrEqual(SHISO_LIMITS.maxModelInvocationsPerTurn); }, 60000); + it('allows the reserved final model call to answer with verified recipe evidence', async () => { + prov.script = [{ kind: 'reply', text: 'Pairing: salmon with cucumber salad.' }]; + const res = await fetch(`${baseUrl}/api/shiso/turn`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', authorization: `Bearer ${AI_ENDPOINT_TOKEN}` }, + body: JSON.stringify({ + turn_version: 'shiso_turn_request_v1', + user_message: 'finish the multi-recipe plan', + history: [], + context: { recipe: null, nutrition: { available: false } }, + task_evidence: 'RECIPE: Honey Glazed Salmon\nRECIPE: Cucumber Salad', + finalize: true, + model_invocations_used: 5, + tool_calls_used: 5, + }), + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.ok).toBe(true); + expect(body.kind).toBe('reply'); + expect(prov.calls).toBe(1); + expect(prov.prompts[0]).toContain('VERIFIED RECIPE EVIDENCE'); + expect(prov.prompts[0]).toContain('RECIPE: Honey Glazed Salmon'); + expect(prov.prompts[0]).toContain('THIS IS THE LAST STEP'); + }, 60000); + it('keeps conversation continuity across turns', async () => { prov.script = [{ kind: 'reply', text: 'first answer' }]; const first = await runShisoConversationTurn( diff --git a/tests/unit/shisoMultiRecipeCompletion.test.ts b/tests/unit/shisoMultiRecipeCompletion.test.ts new file mode 100644 index 0000000..3ec0ac8 --- /dev/null +++ b/tests/unit/shisoMultiRecipeCompletion.test.ts @@ -0,0 +1,224 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { initialShisoConversation, runShisoConversationTurn } from '../../src/application/shisoConversation'; +import { hydrateAiSelections } from '../../src/application/aiSelection'; +import { createShisoVaultCapability } from '../../src/application/shisoVaultCapabilities'; +import type { ShisoToolContext } from '../../src/application/shisoTools'; +import type { NetworkAdapter } from '../../src/application/adapters/NetworkAdapter'; +import type { ObsidianRecipe } from '../../src/types'; +import { SHISO_LIMITS } from '../../src/core/shiso/protocol'; + +const MAIN: ObsidianRecipe = { + id: 'main-salmon', + fileName: 'Honey Glazed Salmon.md', + filePath: 'Recipes/Main/Honey Glazed Salmon.md', + rawMarkdown: '', + title: 'Honey Glazed Salmon', + tags: ['main', 'salmon'], + category: 'Main Course', + cuisine: 'American', + difficulty: 'Easy', + rating: 0, + servings: 2, + prepTime: '15 mins', + cookTime: '20 mins', + totalTime: '35 mins', + ingredients: [ + { original: '2 salmon fillets (6 oz each)', name: 'salmon fillets', amount: 2, unit: null }, + { original: '3 tbsp honey', name: 'honey', amount: 3, unit: 'tbsp' }, + { original: '1 tbsp soy sauce', name: 'soy sauce', amount: 1, unit: 'tbsp' }, + ], + instructions: [ + { text: 'Heat the oven to 400°F.' }, + { text: 'Whisk the glaze and brush it over the salmon.' }, + { text: 'Roast until the salmon flakes, about 12 minutes.' }, + ], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, +} as unknown as ObsidianRecipe; + +const SIDE: ObsidianRecipe = { + id: 'side-cucumber', + fileName: 'Cucumber Salad with Sesame and Rice Vinegar.md', + filePath: 'Recipes/Sides/Cucumber Salad with Sesame and Rice Vinegar.md', + rawMarkdown: '', + title: 'Cucumber Salad with Sesame and Rice Vinegar', + tags: ['side', 'salad'], + category: 'Side Dish', + cuisine: 'Asian', + difficulty: 'Easy', + rating: 0, + servings: 4, + prepTime: '10 mins', + totalTime: '10 mins', + ingredients: [ + { original: '2 cucumbers, thinly sliced', name: 'cucumbers', amount: 2, unit: null }, + { original: '1 tbsp rice vinegar', name: 'rice vinegar', amount: 1, unit: 'tbsp' }, + { original: '1 tsp sesame oil', name: 'sesame oil', amount: 1, unit: 'tsp' }, + ], + instructions: [ + { text: 'Salt the cucumbers and drain for 10 minutes.' }, + { text: 'Toss with rice vinegar and sesame oil.' }, + ], + callouts: [], + dataviewFields: {}, + wikilinks: [], + frontmatter: {}, +} as unknown as ObsidianRecipe; + +function vaultCapability() { + return createShisoVaultCapability({ + getRecipes: () => [MAIN, SIDE], + getNoteCount: () => 0, + getIdentity: () => ({ id: 'disposable-multi-recipe-vault', source: 'personal' }), + }); +} + +function toolContext(): ShisoToolContext { + return { + session: null, + recipe: null, + nutrition: null, + vault: vaultCapability(), + } as unknown as ShisoToolContext; +} + +const SEARCH_MAIN = { + ok: true, + kind: 'tool_request', + tool: 'search_vault_recipes', + args: { tool: 'search_vault_recipes', query: 'main', limit: 10 }, +} as const; +const SEARCH_SIDE = { + ok: true, + kind: 'tool_request', + tool: 'search_vault_recipes', + args: { tool: 'search_vault_recipes', query: 'side', limit: 10 }, +} as const; +const GET_SIDE = { + ok: true, + kind: 'tool_request', + tool: 'get_vault_recipe', + args: { tool: 'get_vault_recipe', recipe_id: SIDE.id }, +} as const; +const SEARCH_SALMON = { + ok: true, + kind: 'tool_request', + tool: 'search_vault_recipes', + args: { tool: 'search_vault_recipes', query: 'salmon', limit: 10 }, +} as const; +const GET_MAIN = { + ok: true, + kind: 'tool_request', + tool: 'get_vault_recipe', + args: { tool: 'get_vault_recipe', recipe_id: MAIN.id }, +} as const; +const REDUNDANT_SEARCH = { + ok: true, + kind: 'tool_request', + tool: 'search_vault_recipes', + args: { tool: 'search_vault_recipes', query: 'Cucumber Salad', limit: 10 }, +} as const; + +const FINAL_ANSWER = [ + 'Pairing: Honey Glazed Salmon with Cucumber Salad.', + 'Cooking sequence: start the salmon glaze, roast the salmon, then toss the salad while it rests.', + 'Combined ingredients: 2 salmon fillets, 3 tbsp honey, 1 tbsp soy sauce, 2 cucumbers, 1 tbsp rice vinegar, 1 tsp sesame oil.', + 'Suggestions: add sesame seeds or scallions to the salad. These are culinary suggestions, not verified recipe facts.', + 'Unavailable: the Vault does not provide exact salmon fillet weight beyond the authored line.', +].join(' '); + +function network(mode: 'reply' | 'budget', steps: readonly unknown[]) { + const calls: Array> = []; + let index = 0; + const post = async (path: string, body?: unknown) => { + if (path !== '/api/shiso/turn') return { status: 200, ok: true, data: {} }; + const sent = JSON.parse(JSON.stringify(body ?? {})) as Record; + calls.push(sent); + if (sent['finalize'] === true) { + return { + status: 200, + ok: true, + data: mode === 'reply' + ? { ok: true, kind: 'reply', text: FINAL_ANSWER, proposals: [] } + : { ok: false, code: 'budget_exhausted', message: 'This conversation turn reached its reasoning budget. Please rephrase or start a new message.' }, + }; + } + const next = steps[index++] ?? { ok: true, kind: 'reply', text: 'unexpected early reply', proposals: [] }; + return { status: 200, ok: true, data: next }; + }; + return { + network: { request: post, get: post, post } as unknown as NetworkAdapter, + calls, + }; +} + +const CONTEXT = { + recipe: null, + nutrition: { available: false, summary: null, unresolvedCount: 0, needsAmountCount: 0, needsMatchCount: 0, unsavedWorkingReview: false }, + recipeKey: null, + sessionIdentity: null, +}; + +const REQUEST = 'Search my Vault for a main dish and a side dish. Read both recipes. Explain why they pair, suggest realistic improvements, coordinate the cooking order, and give me a combined ingredient list with quantities. If something is unavailable, say so.'; + +beforeAll(async () => { await hydrateAiSelections({ get: async () => null }); }); + +describe('SHISO culinary task completion', () => { + it('reserves the final model call for synthesis and carries both recipe facts into it', async () => { + const { network: adapter, calls } = network('reply', [ + SEARCH_MAIN, SEARCH_SIDE, GET_SIDE, SEARCH_SALMON, GET_MAIN, REDUNDANT_SEARCH, + ]); + const outcome = await runShisoConversationTurn( + { network: adapter, context: CONTEXT, toolContext: toolContext() }, + initialShisoConversation(), + REQUEST, + ); + expect(outcome.ok).toBe(true); + expect(outcome.toolsUsed).toEqual([ + 'search_vault_recipes', + 'search_vault_recipes', + 'get_vault_recipe', + 'search_vault_recipes', + 'get_vault_recipe', + ]); + expect(outcome.toolsUsed).not.toContain('apply_nutrition_review'); + expect(outcome.toolsUsed).not.toContain('save_working_recipe'); + expect(outcome.message).toBe(FINAL_ANSWER); + expect(calls).toHaveLength(6); + const finalBody = calls[5]!; + expect(finalBody['finalize']).toBe(true); + expect(finalBody['model_invocations_used']).toBe(SHISO_LIMITS.maxModelInvocationsPerTurn - 1); + const evidence = String(finalBody['task_evidence'] ?? ''); + expect(evidence).toContain('Honey Glazed Salmon'); + expect(evidence).toContain('Cucumber Salad with Sesame and Rice Vinegar'); + expect(evidence).toContain('2 salmon fillets'); + expect(evidence).toContain('1 tbsp rice vinegar'); + expect(evidence).toContain('Heat the oven to 400°F.'); + expect(evidence).toContain('Salt the cucumbers'); + }); + + it('returns a verified partial deliverable when six tool requests exhaust the finalize budget', async () => { + const { network: adapter, calls } = network('budget', [ + SEARCH_MAIN, SEARCH_SIDE, GET_SIDE, SEARCH_SALMON, GET_MAIN, REDUNDANT_SEARCH, + ]); + const outcome = await runShisoConversationTurn( + { network: adapter, context: CONTEXT, toolContext: toolContext() }, + initialShisoConversation(), + REQUEST, + ); + expect(outcome.ok).toBe(true); + expect(outcome.toolsUsed).toHaveLength(5); + expect(calls).toHaveLength(6); + expect(calls[5]!['finalize']).toBe(true); + expect(outcome.message).toContain('reasoning budget'); + expect(outcome.message).toContain('Verified recipe facts already retrieved'); + expect(outcome.message).toContain('Honey Glazed Salmon'); + expect(outcome.message).toContain('Cucumber Salad with Sesame and Rice Vinegar'); + expect(outcome.message).toContain('2 salmon fillets'); + expect(outcome.message).toContain('1 tbsp rice vinegar'); + expect(outcome.message).toContain('To continue'); + expect(outcome.message).not.toBe('This conversation turn reached its reasoning budget. Please rephrase or start a new message.'); + }); +}); diff --git a/tests/unit/shisoTaskEvidence.test.ts b/tests/unit/shisoTaskEvidence.test.ts new file mode 100644 index 0000000..6dd52df --- /dev/null +++ b/tests/unit/shisoTaskEvidence.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; +import { + captureShisoTaskEvidence, + createShisoTaskEvidenceStore, + renderShisoTaskEvidence, +} from '../../src/application/shisoTaskEvidence'; +import type { ShisoObservation } from '../../src/core/shiso/protocol'; + +function ok(tool: 'get_vault_recipe' | 'get_current_recipe', data: Record): ShisoObservation { + return { ok: true, tool, summary: `${tool} fixture`, data } as ShisoObservation; +} + +describe('SHISO task evidence — bounded multi-recipe facts', () => { + it('retains ingredients, quantities, instructions, servings and timing for both recipes', () => { + const store = createShisoTaskEvidenceStore(); + captureShisoTaskEvidence(store, ok('get_vault_recipe', { + id: 'salmon', + title: 'Honey Glazed Salmon', + file_path: 'Recipes/Main/Honey Glazed Salmon.md', + servings: 2, + prepTime: '15 mins', + cookTime: '20 mins', + totalTime: '35 mins', + ingredients: [ + { text: '2 salmon fillets (6 oz each)', name: 'salmon fillets', amount: 2 }, + { text: '3 tbsp honey', name: 'honey', amount: 3, unit: 'tbsp' }, + { text: '1 tbsp soy sauce', name: 'soy sauce', amount: 1, unit: 'tbsp' }, + ], + instructions: [ + { text: 'Heat the oven to 400°F.' }, + { text: 'Whisk the glaze and brush it over the salmon.' }, + { text: 'Roast until the salmon flakes, about 12 minutes.' }, + ], + instructions_total: 3, + })); + captureShisoTaskEvidence(store, ok('get_vault_recipe', { + id: 'cucumber', + title: 'Cucumber Salad with Sesame and Rice Vinegar', + file_path: 'Recipes/Sides/Cucumber Salad.md', + servings: 4, + prepTime: '10 mins', + totalTime: '10 mins', + ingredients: [ + { text: '2 cucumbers, thinly sliced', name: 'cucumbers', amount: 2 }, + { text: '1 tbsp rice vinegar', name: 'rice vinegar', amount: 1, unit: 'tbsp' }, + { text: '1 tsp sesame oil', name: 'sesame oil', amount: 1, unit: 'tsp' }, + ], + instructions: [ + { text: 'Salt the cucumbers and drain for 10 minutes.' }, + { text: 'Toss with rice vinegar and sesame oil.' }, + ], + instructions_total: 2, + })); + const rendered = renderShisoTaskEvidence(store); + expect(rendered).toContain('Honey Glazed Salmon'); + expect(rendered).toContain('Cucumber Salad with Sesame and Rice Vinegar'); + expect(rendered).toContain('2 salmon fillets (6 oz each)'); + expect(rendered).toContain('3 tbsp honey'); + expect(rendered).toContain('1 tbsp rice vinegar'); + expect(rendered).toContain('Heat the oven to 400°F.'); + expect(rendered).toContain('Salt the cucumbers'); + expect(rendered).toContain('servings: 2'); + expect(rendered).toContain('prep: 15 mins'); + expect(rendered).toContain('Recipes/Sides/Cucumber Salad.md'); + expect(rendered.length).toBeLessThanOrEqual(5000); + }); + + it('merges paged current-recipe instructions without inventing missing pages', () => { + const store = createShisoTaskEvidenceStore(); + captureShisoTaskEvidence(store, ok('get_current_recipe', { + title: 'Honey Glazed Salmon', + servings: 2, + prep_time: '15 mins', + ingredients: [{ text: '2 salmon fillets', name: 'salmon fillets', amount: 2 }], + instructions: [ + { index: 0, text: 'Heat the oven.' }, + { index: 1, text: 'Mix the glaze.' }, + ], + instructions_total: 3, + instructions_complete: false, + next_instruction_offset: 2, + })); + captureShisoTaskEvidence(store, ok('get_current_recipe', { + title: 'Honey Glazed Salmon', + servings: 2, + prep_time: '15 mins', + ingredients: [{ text: '2 salmon fillets', name: 'salmon fillets', amount: 2 }], + instructions: [{ index: 2, text: 'Roast the salmon.' }], + instructions_total: 3, + instructions_complete: true, + })); + const rendered = renderShisoTaskEvidence(store); + expect(rendered).toContain('1. Heat the oven.'); + expect(rendered).toContain('2. Mix the glaze.'); + expect(rendered).toContain('3. Roast the salmon.'); + expect(rendered).not.toContain('invented'); + }); + + it('ignores non-recipe and failed observations', () => { + const store = createShisoTaskEvidenceStore(); + captureShisoTaskEvidence(store, { ok: true, tool: 'search_vault_recipes', summary: 'search', data: { results: [] } } as ShisoObservation); + captureShisoTaskEvidence(store, { ok: false, tool: 'get_vault_recipe', code: 'record_not_found', message: 'missing' } as ShisoObservation); + expect(renderShisoTaskEvidence(store)).toBe(''); + }); +});