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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 170 additions & 6 deletions src/App.tsx

Large diffs are not rendered by default.

58 changes: 56 additions & 2 deletions src/application-ui/shisoEntryPoints.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,11 @@ export interface ShisoRecipeEditApplier {
* when the CURRENT user turn issued a save authorization at send time.
*/
export interface ShisoSaveRequest {
readonly via?: 'ui' | 'assistant';
readonly via?: 'ui' | 'assistant' | 'standing_nutrition';
readonly recipe_identity?: string;
readonly vault_scope?: string;
readonly turn?: number;
readonly nutrition_applied?: true;
}

export interface ShisoEntryPoints {
Expand Down Expand Up @@ -154,6 +158,12 @@ export interface ShisoEntryPoints {
readonly runAnalysis: (() => Promise<ShisoAnalysisOutcome>) | null;
readonly canRunAnalysis: boolean;
readonly registerAnalysisApplier: (applier: () => Promise<ShisoAnalysisOutcome>) => () => void;
/** Applies the currently displayed authoritative review through Phase 5. */
readonly applyNutritionReview: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>;
readonly canApplyNutritionReview: boolean;
readonly registerNutritionReviewApplier: (
applier: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>,
) => () => void;

// -------------------------------------------------------------------------
// H-2 — authorized editing ports
Expand Down Expand Up @@ -225,6 +235,9 @@ const INERT: ShisoEntryPoints = {
runAnalysis: null,
canRunAnalysis: false,
registerAnalysisApplier: () => () => {},
applyNutritionReview: async () => ({ ok: false, applied: false, message: 'No current nutrition review is available to apply.' }),
canApplyNutritionReview: false,
registerNutritionReviewApplier: () => () => {},
applyIngredientEdits: async () => ({
ok: false,
applied: [],
Expand Down Expand Up @@ -275,6 +288,7 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
const [snapshot, setSnapshot] = useState<ShisoNutritionSnapshot | null>(null);
const [applier, setApplier] = useState<((b: ShisoBoundProposal) => Promise<ShisoApplyResult>) | null>(null);
const [analysisApplier, setAnalysisApplier] = useState<(() => Promise<ShisoAnalysisOutcome>) | null>(null);
const [nutritionReviewApplier, setNutritionReviewApplier] = useState<(() => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>) | null>(null);
const [nutritionAnalysisRunner, setNutritionAnalysisRunner] = useState<(() => Promise<ShisoNutritionAnalysisOutcome>) | null>(null);
const [recipeEditApplier, setRecipeEditApplier] = useState<ShisoRecipeEditApplier | null>(null);
const [correctionsApplier, setCorrectionsApplier] = useState<
Expand Down Expand Up @@ -324,6 +338,16 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
setNutritionAnalysisRunner(() => next);
return () => setNutritionAnalysisRunner((current) => current === next ? null : current);
}, []);
const registerNutritionReviewApplier = useCallback((next: () => Promise<{ readonly ok: boolean; readonly applied: boolean; readonly message: string }>) => {
setNutritionReviewApplier(() => next);
return () => setNutritionReviewApplier((current) => current === next ? null : current);
}, []);
const applyNutritionReview = useCallback(async () => {
if (nutritionReviewApplier === null) {
return { ok: false, applied: false, message: 'No current nutrition review is available to apply.' };
}
return nutritionReviewApplier();
}, [nutritionReviewApplier]);
const runNutritionAnalysis = useCallback(async (): Promise<ShisoNutritionAnalysisOutcome> => {
if (nutritionAnalysisRunner === null) {
return { ok: false, contributionCount: 0, message: 'SHISO nutrition analysis is not available right now. You can calculate without AI.' };
Expand Down Expand Up @@ -417,6 +441,32 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
turn: 0,
});
}
if (via === 'standing_nutrition') {
if (
typeof request?.recipe_identity !== 'string' || request.recipe_identity.length === 0 ||
typeof request.vault_scope !== 'string' || request.vault_scope.length === 0 ||
request.nutrition_applied !== true
) {
return {
ok: false,
saved: false,
reason_code: 'not_authorized',
message: 'Standing nutrition authority was not valid for this recipe and Vault. Nothing was saved.',
};
}
try {
return await recipeEditApplier.save({
authorized: true,
via: 'standing_nutrition',
recipe_identity: request.recipe_identity,
vault_scope: request.vault_scope,
turn: request.turn ?? 0,
nutrition_applied: true,
});
} catch {
return { ok: false, saved: false, reason_code: 'write_failed', message: 'The recipe could not be saved.' };
}
}
// Assistant path: require a CURRENT, unconsumed authorization issued from
// THE USER'S OWN MESSAGE of this turn. No authorization means no write.
const decision = beginSaveAuthorization(saveAuthorizationRef.current);
Expand Down Expand Up @@ -501,6 +551,9 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
runAnalysis,
canRunAnalysis: analysisApplier !== null,
registerAnalysisApplier,
applyNutritionReview,
canApplyNutritionReview: nutritionReviewApplier !== null,
registerNutritionReviewApplier,
applyIngredientEdits,
canApplyIngredientEdits: recipeEditApplier !== null,
registerRecipeEditApplier,
Expand All @@ -522,7 +575,8 @@ export function ShisoEntryProvider({ children }: { readonly children: ReactNode
open, openForNutritionAnalysis, state.nutritionAnalysisRequest, runNutritionAnalysis, registerNutritionAnalysisRunner,
close, state.open, state.source, publishNutrition, snapshot,
applyProposal, applier, registerApplier, runAnalysis, analysisApplier,
registerAnalysisApplier, applyIngredientEdits, recipeEditApplier,
registerAnalysisApplier, applyNutritionReview, nutritionReviewApplier, registerNutritionReviewApplier,
applyIngredientEdits, recipeEditApplier,
registerRecipeEditApplier, saveWorkingRecipe, issueSaveAuthorizationEntry,
clearSaveAuthorizationEntry, discardWorkingRecipe,
workingRecipe, publishWorkingRecipe, applyNutritionCorrections,
Expand Down
55 changes: 55 additions & 0 deletions src/application/nutritionChangeHistory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { ObsidianRecipe } from '../types';
import { decodeCodexNutrition } from '../core/nutritionV2/validate';

export const SHISO_NUTRITION_HISTORY_SETTING = 'shiso_nutrition_change_history_v1';
export const MAX_SHISO_NUTRITION_HISTORY = 20;

export interface ShisoNutritionChangeRecord {
readonly id: string;
readonly vault_scope: string;
readonly recipe_identity: string;
readonly recipe_title: string;
readonly changed_at: string;
readonly reason: string;
readonly evidence: string;
readonly previous: ObsidianRecipe['codexNutrition'];
readonly next: ObsidianRecipe['codexNutrition'];
}

export function parseNutritionChangeHistory(value: unknown): readonly ShisoNutritionChangeRecord[] {
if (!Array.isArray(value)) return [];
return Object.freeze(value.flatMap((item) => {
if (item === null || typeof item !== 'object' || Array.isArray(item)) return [];
const record = item as Record<string, unknown>;
if (
typeof record['id'] !== 'string' || record['id'].length > 160 ||
typeof record['vault_scope'] !== 'string' || !/^vault:[0-9a-f]{64}$/.test(record['vault_scope']) ||
typeof record['recipe_identity'] !== 'string' || record['recipe_identity'].length === 0 || record['recipe_identity'].length > 500 ||
typeof record['recipe_title'] !== 'string' || record['recipe_title'].length > 300 ||
typeof record['changed_at'] !== 'string' || Number.isNaN(Date.parse(record['changed_at'])) ||
typeof record['reason'] !== 'string' || record['reason'].length > 500 ||
typeof record['evidence'] !== 'string' || record['evidence'].length > 1000
) return [];
const previousDecoded = decodeCodexNutrition(record['previous']);
const nextDecoded = decodeCodexNutrition(record['next']);
if (previousDecoded.kind === 'malformed' || nextDecoded.kind === 'malformed' || nextDecoded.kind === 'none') return [];
return [{
id: record['id'],
vault_scope: record['vault_scope'],
recipe_identity: record['recipe_identity'],
recipe_title: record['recipe_title'],
changed_at: record['changed_at'],
reason: record['reason'],
evidence: record['evidence'],
previous: previousDecoded.kind === 'none' ? undefined : previousDecoded.value,
next: nextDecoded.value,
}];
}).slice(-MAX_SHISO_NUTRITION_HISTORY));
}

export function appendNutritionChange(
history: readonly ShisoNutritionChangeRecord[],
record: ShisoNutritionChangeRecord,
): readonly ShisoNutritionChangeRecord[] {
return Object.freeze([...history.filter((item) => item.id !== record.id), record].slice(-MAX_SHISO_NUTRITION_HISTORY));
}
71 changes: 66 additions & 5 deletions src/application/shisoConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ export interface ShisoTurnDeps {
readonly retry?: boolean;
/** Application-produced note about unsaved working changes. */
readonly workingStateNote?: string;
/** Trusted UI policy; model prose cannot enable or override it. */
readonly nutritionAuthority?: {
readonly enabled: boolean;
};
/**
* C1.7 S5: optional, read-only progress notifications for REAL engine steps.
* No token-level or speculative updates; the UI must not imply streaming.
Expand Down Expand Up @@ -462,6 +466,22 @@ export async function runShisoConversationTurn(
const notes = Array.isArray(data['notes'])
? data['notes'].filter((note): note is string => typeof note === 'string').slice(0, 3)
: [];
const alternativeSummary = Array.isArray(data['alternative_scenarios'])
? data['alternative_scenarios'].slice(0, 3).flatMap((scenario) => {
if (scenario === null || typeof scenario !== 'object' || Array.isArray(scenario)) return [];
const branches = (scenario as Record<string, unknown>)['branches'];
if (!Array.isArray(branches)) return [];
const labels = branches.slice(0, 4).flatMap((branch) => {
if (branch === null || typeof branch !== 'object' || Array.isArray(branch)) return [];
const value = branch as Record<string, unknown>;
if (typeof value['name'] !== 'string') return [];
const grams = typeof value['resolved_grams'] === 'number' ? `, ${value['resolved_grams']} g` : ', unresolved';
const fdc = typeof value['fdc_id'] === 'number' ? `, FDC ${value['fdc_id']}` : '';
return [`${value['name']}${fdc}${grams}`];
});
return labels.length > 0 ? [`Alternative scenarios (not combined): ${labels.join(' versus ')}.`] : [];
}).join(' ')
: '';
const steps = Array.isArray(data['steps']) ? data['steps'] : [];
const aiStep = steps.find((step) => step !== null && typeof step === 'object' && !Array.isArray(step) && (step as Record<string, unknown>)['stage'] === 'ai_estimate') as Record<string, unknown> | undefined;
const aiFailed = aiStep?.['attempted'] === true && (aiStep?.['selected'] ?? 0) === 0;
Expand All @@ -478,26 +498,67 @@ export async function runShisoConversationTurn(
typeof nutrientCoverage === 'object' &&
!Array.isArray(nutrientCoverage) &&
typeof (nutrientCoverage as Record<string, unknown>)['gap_lines_examined'] === 'number';
const requiresAlternativeChoice = Array.isArray(data['alternative_scenarios']) &&
data['alternative_scenarios'].some((scenario) =>
scenario !== null && typeof scenario === 'object' && !Array.isArray(scenario) &&
(scenario as Record<string, unknown>)['definitive_choice_required'] === true
);
// `complete_nutrition` is deliberately honest about its own unsaved stage,
// but that sentence must not survive into a final response after a later
// Apply/Save transaction succeeds. The transaction outcome below is the
// sole persistence claim in the delivered message.
const calculatedSummary = summary.replace(/\s*Nothing was applied or saved\.\s*$/i, '').trim();
let persistenceMessage = requiresAlternativeChoice
? 'An equal ingredient alternative still needs your choice. Select the branch actually used before Apply or Save. Nothing was applied or saved.'
: 'Calculated only: the prepared contributions remain in the UNSAVED Advanced Nutrition review. Nothing was applied or saved.';
const shortcutTools = ['complete_nutrition'];
let shortcutState = working;
if (!requiresAlternativeChoice && result.ok && deps.nutritionAuthority?.enabled === true && classifySaveIntent(trimmed).reason !== 'save_negated') {
shortcutTools.push('apply_nutrition_review');
const applied = await executeShisoTool({ tool: 'apply_nutrition_review' }, deps.toolContext, deps.signal);
const appliedSummary = applied.ok ? applied.summary : (applied as Extract<ShisoObservation, { ok: false }>).message;
shortcutState = recordFinding(shortcutState, {
tool: applied.tool,
ok: applied.ok,
summary: appliedSummary,
});
if (applied.ok) {
shortcutTools.push('save_working_recipe');
const saved = await executeShisoTool({ tool: 'save_working_recipe' }, deps.toolContext, deps.signal);
const savedSummary = saved.ok ? saved.summary : (saved as Extract<ShisoObservation, { ok: false }>).message;
shortcutState = recordFinding(shortcutState, {
tool: saved.tool,
ok: saved.ok,
summary: savedSummary,
});
persistenceMessage = saved.ok && saved.data['saved'] === true
? 'Standing nutrition authority applied the reviewed result and the canonical Vault save confirmed persistence.'
: `The review was applied to the working recipe, but Vault persistence was not confirmed: ${savedSummary}`;
} else {
persistenceMessage = `Standing nutrition authority could not apply this review: ${appliedSummary} Nothing was saved.`;
}
}
const message = result.ok
? isNutrientGapPass
? `${summary}${notes.length > 0 ? ` Notes: ${notes.join(' ')}` : ''}`
? `${calculatedSummary}${notes.length > 0 ? ` Notes: ${notes.join(' ')}` : ''}${alternativeSummary.length > 0 ? ` ${alternativeSummary}` : ''} ${persistenceMessage}`
: `I completed a bounded source-first pass: ${resolvedNew} of ${initialUnresolved} previously unresolved line(s) resolved; ` +
`${accounted} of ${total} ingredient lines covered (${sourceBreakdown}). ` +
`${remaining > 0 ? `${remaining} still need attention. ` : 'Every ingredient line is accounted for. '}` +
`${partialKnown > 0 ? `${partialKnown} line(s) retain unknown nutrients. ` : ''}` +
`${aiFailed && aiFailureNote ? `No AI nutrition estimate was confirmed. ${aiFailureNote} ` : ''}` +
`${notes.length > 0 && !aiFailed ? `Source notes: ${notes.join(' ')} ` : ''}` +
`The prepared contributions are in the UNSAVED Advanced Nutrition review; inspect assumptions and unknown values before Apply. Nothing was applied or saved.`
`${alternativeSummary.length > 0 ? `${alternativeSummary} ` : ''}` +
persistenceMessage
: `${summary} No ingredient edits or saves were made.`;
const nextState = result.ok
? recordFinding(appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 }), { tool: result.tool, ok: true, summary: result.summary })
: appendShisoMessage(working, { role: 'assistant', text: message, proposalCount: 0 });
? recordFinding(appendShisoMessage(shortcutState, { role: 'assistant', text: message, proposalCount: 0 }), { tool: result.tool, ok: true, summary: result.summary })
: appendShisoMessage(shortcutState, { role: 'assistant', text: message, proposalCount: 0 });
return {
ok: true,
state: nextState,
message,
status: null,
toolsUsed: Object.freeze(['complete_nutrition']) as readonly string[],
toolsUsed: Object.freeze(shortcutTools) as readonly string[],
};
}

Expand Down
18 changes: 17 additions & 1 deletion src/application/shisoNutritionReview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export function createShisoNutritionReviewController(

const getLiveRows = (): readonly LiveRowState[] => {
const analyzedByRef = new Map<string, AnalyzedRow>(analysis.rows.map((row) => [row.line_ref, row]));
return projectLiveRows(
const rows = projectLiveRows(
state,
analyzedByRef,
adapted,
Expand All @@ -129,6 +129,22 @@ export function createShisoNutritionReviewController(
analysis.portions,
analysis.countPortions,
);
// The core calculator preserves an automatically discovered equal-
// alternative as raw diagnostic evidence, but SHISO's working review must
// present that line as unresolved until the user chooses a branch. This is
// a presentation-level projection only; Phase 5 independently enforces the
// same boundary before Apply/Save.
return rows.map((row) => {
const evidence = state.preview?.ingredients.find((entry) => entry.line_ref === row.line_ref);
if (evidence?.outcome !== 'ambiguous' || evidence.match_status === 'user_confirmed') return row;
return {
...row,
status: 'needs_match' as const,
resolved_grams: undefined,
mass_source: undefined,
portion_index: undefined,
};
});
};

const getSnapshot = (): ShisoNutritionSnapshot => {
Expand Down
Loading