From b3307d9669f288ecb88917ed229205be53bdabe2 Mon Sep 17 00:00:00 2001 From: Luna Date: Thu, 3 Dec 2026 11:20:44 -0500 Subject: [PATCH] fix(nutrition): enforce operation-scoped save authority and preserve recipe drafts Scope automatic nutrition writes to an exact reviewed operation, preserve mixed and newer working drafts, enforce guarded persistence through the final reversible checkpoint, invalidate staged standing saves when a Vault transition starts, and retain only verifiable pending Undo history. --- src/App.tsx | 488 +++++++- src/application/adapters/VaultAdapter.ts | 9 + src/application/vaultRecipe.ts | 22 +- src/components/AdvancedNutritionCard.tsx | 11 +- src/components/ShisoModal.tsx | 4 +- src/core/shiso/nutritionAuthority.ts | 14 + src/core/shiso/nutritionWriteAuthority.ts | 407 ++++++ src/core/shiso/protocol.ts | 8 +- src/core/shiso/workingRecipe.ts | 13 +- .../browser/BrowserFsaVaultAdapter.ts | 38 + src/platform/obsidian/ObsidianVaultAdapter.ts | 16 + tests/diagnostic/nutAuth01Evidence.ts | 143 +++ .../nutAuth01MixedWorkingCopy.test.ts | 355 ++++++ tests/diagnostic/nutAuth02Evidence.ts | 129 ++ .../nutAuth02F1AdapterBoundary.test.ts | 214 ++++ .../diagnostic/nutAuth02F1Lifecycle.test.tsx | 1090 +++++++++++++++++ .../shisoAgentFoundationAppOnDisk.test.tsx | 219 ++++ tests/unit/nutritionWriteAuthority.test.ts | 367 ++++++ 18 files changed, 3519 insertions(+), 28 deletions(-) create mode 100644 src/core/shiso/nutritionWriteAuthority.ts create mode 100644 tests/diagnostic/nutAuth01Evidence.ts create mode 100644 tests/diagnostic/nutAuth01MixedWorkingCopy.test.ts create mode 100644 tests/diagnostic/nutAuth02Evidence.ts create mode 100644 tests/diagnostic/nutAuth02F1AdapterBoundary.test.ts create mode 100644 tests/diagnostic/nutAuth02F1Lifecycle.test.tsx create mode 100644 tests/unit/nutritionWriteAuthority.test.ts diff --git a/src/App.tsx b/src/App.tsx index 2551ddf..0a60c79 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -65,6 +65,7 @@ import { import { createAppServices, loadVaultContent, + GuardedVaultWriteUnavailableError, saveRecipeWithVaultAdapter, deleteRecipeWithVaultAdapter, saveMealPlanWithVaultAdapter, @@ -81,7 +82,7 @@ import { applyAdvancedNutrition, ADVANCED_NUTRITION_APPLY_UI_MESSAGE, } from './application'; -import { rebaseRecipeOntoLatest, enqueueRecipeWrite as enqueueRecipeWriteHelper, normalizeRecipeWriteKey } from './application/recipeWriteCoordination'; +import { deepEqualRecipeValue, rebaseRecipeOntoLatest, enqueueRecipeWrite as enqueueRecipeWriteHelper, normalizeRecipeWriteKey } from './application/recipeWriteCoordination'; import { resolveRecipeVaultPath } from './core/vaultPath'; import { createBrowserSettingsAdapter, @@ -188,6 +189,15 @@ import { type ShisoSaveGrant, } from './core/shiso/saveAuthorization'; import { resolveShisoBoundRecipe, shisoAllowsAmbientRecipe } from './core/shiso/recipeBinding'; +import { + createNutritionWriteAuthority, + currentSavedRecipeForStandingWrite, + validateNutritionWriteAuthority, + semanticRecipeDigest, + NutritionWriteAuthorityBlockedError, + type NutritionWriteAuthority, + type NutritionWriteAuthorityFailure, +} from './core/shiso/nutritionWriteAuthority'; import { SHISO_NUTRITION_AUTHORITY_SETTING, grantNutritionAuthority, @@ -336,6 +346,14 @@ function isVaultSessionSuperseded(error: unknown): boolean { return Boolean(error) && (error as { name?: unknown }).name === 'VaultSessionSupersededError'; } +/** NUT-AUTH-02-F1: an Apply completion that lost its initiating lifecycle. */ +class NutritionApplyLifecycleStaleError extends Error { + constructor() { + super('nutrition_apply_lifecycle_stale'); + this.name = 'NutritionApplyLifecycleStaleError'; + } +} + function vaultSessionSupersededError(): Error { const error = new Error('The active Vault changed before this operation could complete.'); Object.defineProperty(error, 'name', { value: 'VaultSessionSupersededError' }); @@ -351,7 +369,156 @@ function vaultSessionSupersededError(): Error { * state is memory-only: it is never persisted, and it is discarded on Save, * Discard, or any successful canonical write of the same recipe. */ -type ShisoWorkingRecipeState = ShisoWorkingRecipeCore; +type ShisoWorkingRecipeState = ShisoWorkingRecipeCore & { + /** Set only when a completed Save cannot prove the retained Undo ancestry. */ + readonly historyConflict?: string; +}; + +/** + * NUT-AUTH-02-F2: the bounded result of completing a canonical write against + * the SHISO draft it represents. + */ +type DraftCompletionKind = 'none' | 'cleared' | 'retained' | 'conflict'; + +interface DraftCompletion { + readonly state: ShisoWorkingRecipeState | null; + readonly kind: DraftCompletionKind; +} + +interface RecipeCommitOutcome { + readonly committed: ObsidianRecipe | null; + readonly draft: DraftCompletionKind; +} + +/** + * A history entry sequence is a verifiable descendant only when the saved + * operation's history is an exact prefix of the newer ledger. Array length + * alone is not ancestry. + */ +function historyIsPrefix( + saved: readonly { readonly index: number; readonly previous: TIngredient }[], + latest: readonly { readonly index: number; readonly previous: TIngredient }[], +): boolean { + if (latest.length < saved.length) return false; + for (let index = 0; index < saved.length; index += 1) { + if (!deepEqualRecipeValue(saved[index], latest[index])) return false; + } + return true; +} + +/** + * The first pending edit per ingredient index must start from the value the + * completed Save actually committed. Later pending edits may chain through + * intermediate user values, but the first Undo must never cross the committed + * boundary. + */ +function pendingHistoryStartsAtCommitted( + committed: ObsidianRecipe, + pending: readonly { readonly index: number; readonly previous: ParsedIngredient }[], +): boolean { + if (pending.length === 0) return true; + const committedIngredients = Array.isArray(committed.ingredients) + ? committed.ingredients as ParsedIngredient[] + : []; + const firstByIndex = new Map(); + for (const entry of pending) { + if (!firstByIndex.has(entry.index)) firstByIndex.set(entry.index, entry.previous); + } + for (const [index, previous] of firstByIndex) { + if (!deepEqualRecipeValue(committedIngredients[index], previous)) return false; + } + return true; +} + +function draftConflictState(draft: ShisoWorkingRecipeState): ShisoWorkingRecipeState { + return Object.freeze({ + ...draft, + historyConflict: + 'This draft changed while an earlier save completed. Discard it and reapply your changes before saving.', + }); +} + +/** + * NUT-AUTH-02-F2: reconcile a retained descendant draft onto the recipe that a + * canonical Save actually committed. + * + * - It never touches a draft with a different saved base (a newer independent + * draft). + * - It keeps only the pending history suffix whose first entry starts at the + * committed ingredient value. + * - If ancestry cannot be proven, it preserves the content and marks a bounded + * conflict instead of manufacturing a new history baseline. + */ +function reconcileWorkingCopyAfterCommit( + committed: ObsidianRecipe, + savedDraft: ShisoWorkingRecipeState, + latestDraft: ShisoWorkingRecipeState | null, +): DraftCompletion { + if (latestDraft === null) return { state: null, kind: 'none' }; + if (!sameCanonicalRecipeIdentity(latestDraft.base, committed)) { + return { state: latestDraft, kind: 'none' }; + } + // A draft based on a different saved snapshot began independently of this + // write. Leave it untouched; its own next Save will rebase it safely. + if ( + semanticRecipeDigest(latestDraft.base, { includeNutrition: true }) !== + semanticRecipeDigest(savedDraft.base, { includeNutrition: true }) + ) { + return { state: latestDraft, kind: 'retained' }; + } + if (latestDraft.historyConflict) { + return { state: latestDraft, kind: 'conflict' }; + } + + // Ownership and ancestry must be established BEFORE any equality-based + // clearing. An Undo during Save can make the rebased result equal to the + // committed recipe while the newer working value is still the user's action. + if (!historyIsPrefix(savedDraft.history, latestDraft.history)) { + return { state: draftConflictState(latestDraft), kind: 'conflict' }; + } + const pendingHistory = latestDraft.history.slice(savedDraft.history.length); + if (!pendingHistoryStartsAtCommitted(committed, pendingHistory)) { + return { state: draftConflictState(latestDraft), kind: 'conflict' }; + } + + const rebased = rebaseRecipeOntoLatest(committed, latestDraft.base, latestDraft.working); + if ( + semanticRecipeDigest(rebased, { includeNutrition: true }) === + semanticRecipeDigest(committed, { includeNutrition: true }) + ) { + return { state: null, kind: 'cleared' }; + } + + const committedIngredients = Array.isArray(committed.ingredients) + ? committed.ingredients as ParsedIngredient[] + : []; + const workingIngredients = Array.isArray(rebased.ingredients) + ? rebased.ingredients as ParsedIngredient[] + : []; + const pendingIndices = new Set(); + const max = Math.max(committedIngredients.length, workingIngredients.length); + for (let index = 0; index < max; index += 1) { + if (!deepEqualRecipeValue(committedIngredients[index], workingIngredients[index])) { + pendingIndices.add(index); + } + } + const changes = pendingIndices.size > 0 + ? [...pendingIndices].sort((a, b) => a - b).map((index) => { + const before = committedIngredients[index]?.original ?? ''; + const after = workingIngredients[index]?.original ?? ''; + return `${before} → ${after}`; + }) + : ['Recipe changed while saving']; + return { + state: Object.freeze({ + base: committed, + working: rebased, + changes, + history: pendingHistory, + }), + kind: 'retained', + }; +} function conversationKeyBelongsToContext(conversationKey: string, contextKey: string): boolean { if (contextKey === 'global') { @@ -956,7 +1123,9 @@ export default function App({ const nutritionAuthorityActive = nutritionAuthorityEnabled(nutritionAuthorityRecord, nutritionAuthorityScope); const setNutritionAuthority = useCallback(async (enabled: boolean) => { + shisoLifecycleEpochRef.current += 1; if (!enabled) { + nutritionWriteAuthorityRef.current = null; setNutritionAuthorityRecord(null); await settingsAdapter.remove(SHISO_NUTRITION_AUTHORITY_SETTING); return; @@ -1278,10 +1447,40 @@ export default function App({ // working copy rather than a stale render closure. const [shisoWorkingRecipe, setShisoWorkingRecipe] = useState(null); const shisoWorkingRecipeRef = useRef(null); - const updateShisoWorkingRecipe = useCallback((next: ShisoWorkingRecipeState | null) => { + // NUT-AUTH-02: the authority for the CURRENT nutrition Apply operation. It is + // created only after a successful Apply and cleared on save/discard/switch. + const nutritionWriteAuthorityRef = useRef(null); + const nutritionWriteOperationSeqRef = useRef(0); + // NUT-AUTH-02-F1: monotonic identities. Draft generations change on every + // working-copy mutation. Lifecycle epochs change on edits, discard, recipe or + // Vault switch, revocation, a new Apply and save completion. Identities are + // never reused or derived from recipe content. + const shisoDraftGenerationRef = useRef(0); + const shisoLifecycleEpochRef = useRef(0); + // Monotonic per-edit identity. Unlike an ingredient index or previous value, + // it cannot be reused after Undo, discard or replacement. + const shisoEditSequenceRef = useRef(0); + const updateShisoWorkingRecipe = useCallback(( + next: ShisoWorkingRecipeState | null, + options?: { readonly bumpEpoch?: boolean; readonly invalidateOperation?: boolean }, + ) => { shisoWorkingRecipeRef.current = next; + shisoDraftGenerationRef.current += 1; + if (next === null || (options?.invalidateOperation ?? true)) { + nutritionWriteAuthorityRef.current = null; + } + if (options?.bumpEpoch ?? true) shisoLifecycleEpochRef.current += 1; setShisoWorkingRecipe(next); }, []); + /** + * NUT-AUTH-02-F2: a Vault transition starts synchronously invalidating every + * reversible standing nutrition operation. The draft itself is preserved. + * Returning to the original Vault does not restore the operation. + */ + const invalidateStandingNutritionOperation = useCallback(() => { + shisoLifecycleEpochRef.current += 1; + nutritionWriteAuthorityRef.current = null; + }, []); // Filters & Search const [searchQuery, setSearchQuery] = useState(''); @@ -1412,6 +1611,9 @@ export default function App({ assetScope: VaultAssetScope, options?: { showSignaturePrompt?: boolean; persistHandle?: boolean; preserveEditor?: boolean } ): Promise<{ accepted: boolean; session?: VaultSession; writesSettled: boolean }> => { + // Defense in depth for every caller: no reversible standing operation may + // survive the transition boundary even if a begin-site was missed. + invalidateStandingNutritionOperation(); const adapter = createBrowserVaultAdapter(handle); let adopted = false; let outcome; @@ -1556,6 +1758,7 @@ export default function App({ } const transition = vaultAuthority.beginTransition('filesystem'); if (!transition) throw new Error('A Vault change is already in progress. Please try again.'); + invalidateStandingNutritionOperation(); const assetScope = createVaultAssetScope(null, { active: false }); try { const result = await loadVaultFromHandle(handle, assetScope); @@ -1617,6 +1820,7 @@ export default function App({ const transition = intent ? vaultAuthority.beginCollectionTransition(intent, 'uploaded') : vaultAuthority.beginTransition('uploaded'); + invalidateStandingNutritionOperation(); if (!transition) { assetScope.deactivate(); return false; @@ -1686,6 +1890,7 @@ export default function App({ scope.deactivate(); } const intent = vaultAuthority.beginCollectionIntent(); + invalidateStandingNutritionOperation(); const assetScope = createVaultAssetScope(null, { active: false }); pendingImportScopesRef.current.set(intent.id, assetScope); return { intent, assetScope }; @@ -1696,6 +1901,7 @@ export default function App({ // the "Reconnect Vault" button. It never clears a valid handle on failure. const handleReconnectVault = useCallback(async () => { const transition = vaultAuthority.beginTransition('filesystem'); + invalidateStandingNutritionOperation(); const assetScope = createVaultAssetScope(null, { active: false }); setVaultHydratedState(false); const outcome = await reconnectRememberedVault({ @@ -1824,6 +2030,7 @@ export default function App({ const handle = createDesktopDirectoryHandle(info.path); const transition = vaultAuthority.beginAutomaticTransition('filesystem'); if (!transition) return; + invalidateStandingNutritionOperation(); const assetScope = createVaultAssetScope(null, { active: false }); setVaultHydratedState(false); try { @@ -1870,6 +2077,7 @@ export default function App({ // returns null and A never becomes authoritative. const transition = vaultAuthority.beginAutomaticTransition('filesystem'); if (!transition) return; + invalidateStandingNutritionOperation(); const assetScope = createVaultAssetScope(null, { active: false }); setVaultHydratedState(false); try { @@ -2214,6 +2422,9 @@ export default function App({ // An explicit folder selection is a new authority decision. Revoke the // previous Vault's standing nutrition grant before the new handle can win, // including the browser edge case where two folders share the same name. + // Selection is the user's intent boundary. Invalidate before the settings + // await so a staged standing write cannot slip through while it runs. + invalidateStandingNutritionOperation(); setNutritionAuthorityRecord(null); await settingsAdapter.remove(SHISO_NUTRITION_AUTHORITY_SETTING).catch(() => undefined); const transition = vaultAuthority.beginTransition('filesystem'); @@ -2314,7 +2525,30 @@ export default function App({ }, []); const commitRecipeWrite = useCallback( - async (savedRecipe: ObsidianRecipe, baseRecipe?: ObsidianRecipe, options?: { readonly useDesiredRawMarkdown?: boolean }) => { + async ( + savedRecipe: ObsidianRecipe, + baseRecipe?: ObsidianRecipe, + options?: { + readonly useDesiredRawMarkdown?: boolean; + readonly beforeWrite?: (input: { + readonly latest: ObsidianRecipe | undefined; + readonly base: ObsidianRecipe | undefined; + readonly toWrite: ObsidianRecipe; + }) => void; + /** Last reversible authority check inside the adapter, before commit. */ + readonly beforeCommit?: (input: { + readonly latest: ObsidianRecipe | undefined; + readonly base: ObsidianRecipe | undefined; + readonly toWrite: ObsidianRecipe; + }) => void; + /** The exact working draft this write represents, when it owns one. */ + readonly draft?: ShisoWorkingRecipeState; + /** The caller has established that `draft` is the complete write. */ + readonly draftIsComplete?: boolean; + /** Reject any destination that cannot provide a guarded commit. */ + readonly requireGuardedDestination?: boolean; + }, + ) => { if (isBuiltInRecipe(savedRecipe) || isBuiltInRecipe(baseRecipe)) { throw new Error('Signature Collection originals are read-only. Save this recipe to My Vault first.'); } @@ -2325,6 +2559,11 @@ export default function App({ const requested = activeVaultRef.current; const requestedSession = requested.session; const requestedAdapter = requested.adapter; + // The draft this write was created from. A newer draft remains owned by + // its own operation until this canonical publication completes. + const savedDraft = options?.draft ?? shisoWorkingRecipeRef.current; + let committed: ObsidianRecipe | null = null; + let draftOutcome: DraftCompletionKind = 'none'; const run = async () => { if (vaultAuthority.writesBlocked() || !vaultAuthority.isCurrent(requestedSession)) { throw vaultSessionSupersededError(); @@ -2332,11 +2571,21 @@ export default function App({ if (requestedSession.kind === 'filesystem' && !requestedAdapter) { throw vaultSessionSupersededError(); } + if ( + options?.requireGuardedDestination && + (!requestedAdapter || typeof requestedAdapter.writeTextGuarded !== 'function') + ) { + throw new GuardedVaultWriteUnavailableError(); + } const latest = committedRecipesRef.current.find((r) => sameCanonicalRecipeIdentity(r, savedRecipe)); const rebased = rebaseRecipeOntoLatest(latest, base, savedRecipe); const toWrite = options?.useDesiredRawMarkdown === true ? { ...rebased, rawMarkdown: savedRecipe.rawMarkdown } : rebased; + // NUT-AUTH-02: revalidate at the queued-write boundary. A decision made + // before queueing is not authoritative if the saved base changed while + // this task waited. + options?.beforeWrite?.({ latest, base, toWrite }); if (requestedAdapter) { const lease = vaultAuthority.beginWrite(requestedSession); if (!lease) throw vaultSessionSupersededError(); @@ -2352,7 +2601,12 @@ export default function App({ if (!validation.ok) { throw new Error(validation.reason || 'The active Vault could not verify this recipe image reference.'); } - await saveRecipeWithVaultAdapter(requestedAdapter, toWrite); + await saveRecipeWithVaultAdapter(requestedAdapter, toWrite, { + beforeCommit: options?.beforeCommit + ? () => options.beforeCommit!({ latest, base, toWrite }) + : undefined, + }); + committed = toWrite; } finally { lease.release(); } @@ -2360,7 +2614,9 @@ export default function App({ vaultAuthority.markCollectionChanged(requestedSession); } else { // Disconnected workflow: preserve the existing download-to-disk fallback. + options?.beforeCommit?.({ latest, base, toWrite }); await saveRecipeToVaultFile(toWrite, undefined); + committed = toWrite; } // A pending transition keeps the OLD session authoritative until it // commits. Updating the old state here is safe: a later commit replaces @@ -2369,12 +2625,28 @@ export default function App({ committedRecipesRef.current = upsertCanonicalRecipe(committedRecipesRef.current, toWrite); setPersonalRecipes((prev) => upsertCanonicalRecipe(prev, toWrite)); setSelectedRecipe((prev) => (prev && sameCanonicalRecipeIdentity(prev, toWrite) ? toWrite : prev)); - const working = shisoWorkingRecipeRef.current; - if (working !== null && sameCanonicalRecipeIdentity(working.base, toWrite)) { - updateShisoWorkingRecipe(null); + // NUT-AUTH-02-F2: the canonical writer is the ONE draft-completion + // owner. It completes before any auxiliary await (for example the + // nutrition-history settings write) can run. + if (savedDraft !== null) { + const completesDraft = options?.draftIsComplete ?? ( + sameCanonicalRecipeIdentity(savedDraft.base, toWrite) && + semanticRecipeDigest(savedDraft.working, { includeNutrition: true }) === + semanticRecipeDigest(toWrite, { includeNutrition: true }) + ); + if (completesDraft) { + const completion = reconcileWorkingCopyAfterCommit(toWrite, savedDraft, shisoWorkingRecipeRef.current); + if (completion.kind === 'cleared') { + updateShisoWorkingRecipe(null); + } else if (completion.kind === 'retained' || completion.kind === 'conflict') { + updateShisoWorkingRecipe(completion.state); + } + draftOutcome = completion.kind; + } } }; await enqueueRecipeWrite(savedRecipe, run); + return { committed, draft: draftOutcome } satisfies RecipeCommitOutcome; }, [updateShisoWorkingRecipe, enqueueRecipeWrite, vaultAuthority], ); @@ -2675,6 +2947,16 @@ export default function App({ const applyShisoEdits = useCallback( async (edits: readonly ShisoIngredientEditArgs[]): Promise => { const currentWorking = shisoWorkingRecipeRef.current; + if (currentWorking?.historyConflict) { + return { + ok: false, + applied: [], + refused: [], + summary: currentWorking.historyConflict, + working_unsaved: true, + note: 'Nothing was changed. Discard the conflicted draft and reapply your edits before saving.', + }; + } const base = currentWorking !== null && selectedRecipe !== null && @@ -2714,6 +2996,7 @@ export default function App({ ledger: result.ledger.map((entry) => ({ index: entry.index, previous: entry.previous as ParsedIngredient, + editId: `shiso-edit-${shisoEditSequenceRef.current += 1}`, })), changeLines: result.applied.map((entry) => `${entry.before} → ${entry.after}`.slice(0, 300)), maxChanges: 24, @@ -2739,7 +3022,7 @@ export default function App({ */ const undoLastShisoEdit = useCallback(() => { const current = shisoWorkingRecipeRef.current; - if (current === null) return; + if (current === null || current.historyConflict) return; const next = undoLastWorkingEdit(current, (working, index, previous) => { const ingredients = [...(working.ingredients as ParsedIngredient[])]; if (ingredients[index] === undefined) return null; @@ -2790,16 +3073,128 @@ export default function App({ : 'Saving needs your explicit instruction (for example “save my changes”) or the Save button. Nothing was saved.', }; } + const requestDraftGeneration = shisoDraftGenerationRef.current; + const requestEpoch = shisoLifecycleEpochRef.current; + const requestAuthority = nutritionWriteAuthorityRef.current; + // F2: bind the request to the exact live Vault session too. Captured + // scope alone does not prove that a transition has not started. + const requestVaultSession = activeVaultRef.current.session; + const assertStandingRequestCurrent = () => { + if ( + shisoLifecycleEpochRef.current !== requestEpoch || + shisoDraftGenerationRef.current !== requestDraftGeneration || + shisoWorkingRecipeRef.current !== current || + nutritionWriteAuthorityRef.current !== requestAuthority || + activeVaultRef.current.session !== requestVaultSession || + !vaultAuthority.isCurrent(requestVaultSession) || + vaultAuthority.pendingTransition() !== null + ) { + throw new NutritionWriteAuthorityBlockedError('stale_operation'); + } + }; + const revalidateStandingWrite = (input: { + readonly latest: ObsidianRecipe | undefined; + readonly toWrite: ObsidianRecipe; + }) => { + assertStandingRequestCurrent(); + // B7: an existing-recipe standing save requires the CURRENT saved + // recipe. Falling back to the captured base would treat a missing or + // deleted current recipe as proof of the saved revision. + const currentSaved = currentSavedRecipeForStandingWrite({ latest: input.latest, base: current.base }); + if (currentSaved === null) { + throw new NutritionWriteAuthorityBlockedError('stale_recipe'); + } + const recheck = validateNutritionWriteAuthority({ + authority: requestAuthority, + base: currentSaved, + working: input.toWrite, + vaultScope: nutritionAuthorityScope, + }); + if (!recheck.ok) { + const reason = (recheck as { readonly ok: false; readonly reason: NutritionWriteAuthorityFailure }).reason; + throw new NutritionWriteAuthorityBlockedError(reason); + } + }; + if (grant?.via === 'standing_nutrition') { + const validation = validateNutritionWriteAuthority({ + authority: requestAuthority, + base: current.base, + working: current.working, + vaultScope: nutritionAuthorityScope, + }); + if (!validation.ok) { + const reason = (validation as { readonly ok: false; readonly reason: string }).reason; + if (reason === 'nothing_unsaved') { + return { + ok: false, + saved: false, + reason_code: 'nothing_unsaved', + message: 'There is nothing new to save.', + }; + } + if (reason === 'mixed_working_copy') { + return { + ok: false, + saved: false, + reason_code: 'mixed_working_copy', + message: 'Nutrition updated. Other recipe changes are pending. Review and save your recipe.', + }; + } + return { + ok: false, + saved: false, + reason_code: 'stale_nutrition_operation', + message: reason === 'missing_authority' + ? 'Nutrition was applied but automatic save authorization is unavailable. Review and save your recipe.' + : reason === 'stale_vault' + ? 'The active Vault changed after the nutrition review. Refresh the review before saving.' + : 'The recipe changed after the nutrition review. Refresh the review before saving.', + }; + } + } + if (current.historyConflict) { + return { + ok: false, + saved: false, + reason_code: 'write_failed', + message: current.historyConflict, + }; + } const nutritionChanged = JSON.stringify(current.working.codexNutrition ?? null) !== JSON.stringify(current.base.codexNutrition ?? null); + let commitOutcome: RecipeCommitOutcome | null = null; try { - await commitRecipeWrite(current.working, current.base); + commitOutcome = await commitRecipeWrite(current.working, current.base, { + draft: current, + draftIsComplete: true, + ...(grant?.via === 'standing_nutrition' + ? { + requireGuardedDestination: true, + beforeWrite: revalidateStandingWrite, + beforeCommit: revalidateStandingWrite, + } + : {}), + }); } catch (err) { + if (err instanceof NutritionWriteAuthorityBlockedError) { + return { + ok: false, + saved: false, + reason_code: err.reason === 'mixed_working_copy' ? 'mixed_working_copy' : 'stale_nutrition_operation', + message: err.reason === 'mixed_working_copy' + ? 'Nutrition updated. Other recipe changes are pending. Review and save your recipe.' + : 'The recipe changed after the nutrition review. Refresh the review before saving.', + }; + } + if (err instanceof GuardedVaultWriteUnavailableError) { + return { ok: false, saved: false, reason_code: 'write_failed', message: err.message }; + } if (isVaultSessionSuperseded(err)) { return { ok: false, saved: false, reason_code: 'write_failed', message: 'The Vault changed before this save completed. Nothing was written to the new Vault.' }; } reportVaultError('save', current.working.title || 'recipe', err); return { ok: false, saved: false, reason_code: 'write_failed', message: 'The recipe could not be saved to the vault.' }; } + const retainedNewerDraft = commitOutcome?.draft === 'retained' || commitOutcome?.draft === 'conflict'; let historyRecorded = true; if (nutritionChanged) { const block = current.working.codexNutrition; @@ -2827,14 +3222,13 @@ export default function App({ historyRecorded = false; } } - updateShisoWorkingRecipe(null); return { ok: true, saved: true, - message: `Saved "${current.working.title}" with ${current.changes.length + Number(nutritionChanged)} recipe change(s).${historyRecorded ? '' : ' The recipe was saved, but the local nutrition restore history could not be recorded.'}`, + message: `Saved "${current.working.title}" with ${current.changes.length + Number(nutritionChanged)} recipe change(s).${retainedNewerDraft ? ' Newer unsaved changes remain.' : ''}${historyRecorded ? '' : ' The recipe was saved, but the local nutrition restore history could not be recorded.'}`, }; }, - [commitRecipeWrite, nutritionAuthorityScope, nutritionChangeHistory, settingsAdapter, updateShisoWorkingRecipe], + [commitRecipeWrite, nutritionAuthorityScope, nutritionChangeHistory, settingsAdapter, updateShisoWorkingRecipe, vaultAuthority], ); // SHISO H-2 — register the recipe-edit/save applier with the ONE Shiso entry @@ -3024,6 +3418,15 @@ export default function App({ const handleApplyAdvancedNutrition: AdvancedNutritionApplyHandler = async ( args: AdvancedNutritionApplyHandlerArgs ): Promise => { + if (shisoWorkingRecipeRef.current?.historyConflict) { + return { ok: false, message: shisoWorkingRecipeRef.current.historyConflict }; + } + // A new Apply attempt invalidates any previous operation authority and + // lifecycle before any early return. A failed attempt must never leave an + // older grant or a stale completion able to authorize a later save. + shisoLifecycleEpochRef.current += 1; + const applyEpoch = shisoLifecycleEpochRef.current; + nutritionWriteAuthorityRef.current = null; // AUTHORITATIVE PRODUCT-ACCESS GATE. The Advanced Apply operation is not a // Basic feature. This check runs at the operation boundary, not only in the // button render, so a Basic deployment cannot apply an Advanced review even if @@ -3085,6 +3488,8 @@ export default function App({ }, }; } + let appliedBase: ObsidianRecipe | null = null; + let appliedWorking: ObsidianRecipe | null = null; const result = await applyAdvancedNutrition({ session: args.session, recipe: args.recipe, @@ -3092,6 +3497,9 @@ export default function App({ expectedMode: args.expectedMode, ...(args.reviewReasons !== undefined ? { reviewReasons: args.reviewReasons } : {}), write: async (updated: ObsidianRecipe) => { + if (shisoLifecycleEpochRef.current !== applyEpoch) { + throw new NutritionApplyLifecycleStaleError(); + } const existingWorking = shisoWorkingRecipeRef.current; const sameWorking = existingWorking !== null && sameCanonicalRecipeIdentity(existingWorking.base, updated) ? existingWorking @@ -3100,6 +3508,8 @@ export default function App({ ? selectedRecipe : args.recipe; const base = sameWorking?.base ?? selectedBase; + appliedBase = base; + appliedWorking = updated; updateShisoWorkingRecipe(Object.freeze({ base, working: updated, @@ -3107,15 +3517,36 @@ export default function App({ // nutrition change is reported separately in the working banner. changes: sameWorking?.changes ?? Object.freeze([]), history: sameWorking?.history ?? Object.freeze([]), - })); + }), { bumpEpoch: false, invalidateOperation: false }); }, }); if (result.ok) { + if (shisoLifecycleEpochRef.current !== applyEpoch) { + return { + ok: false, + message: 'The recipe changed while nutrition was being applied. Review the current working recipe before saving.', + }; + } + if (appliedBase !== null && appliedWorking !== null) { + // NUT-AUTH-02 Phase B: no trusted nutrition-specific recipe-ingredient + // correction operation exists yet. The authority therefore authorizes + // the nutrition block only; a future trusted operation must supply + // explicit line refs here. Arbitrary SHISO ingredient edits must never + // be retroactively authorized by the nutrition review. + const created = createNutritionWriteAuthority({ + base: appliedBase, + reviewed: args.recipe, + applied: appliedWorking, + vaultScope: nutritionAuthorityScope, + operationId: `nutrition-op-${Date.now()}-${nutritionWriteOperationSeqRef.current += 1}`, + }); + if (created.ok) nutritionWriteAuthorityRef.current = created.authority; + } return { ok: true, mode: result.result.mode, - message: 'Nutrition was applied to the working recipe. It is not saved to your Vault yet; use Save to vault in the recipe banner when ready.', + message: 'Nutrition was applied to the working recipe. It is not saved to your Vault yet; use Save all recipe changes in the recipe banner when ready.', }; } const failureCode = (result as { ok: false; failure: { code: keyof typeof ADVANCED_NUTRITION_APPLY_UI_MESSAGE } }) @@ -3895,7 +4326,14 @@ export default function App({ recipesRef.current = recipes; }, [recipes]); const selectedRecipeRef = useRef(selectedRecipe); + const nutritionAuthorityRecipeIdentityRef = useRef(''); useEffect(() => { + const nextIdentity = selectedRecipe === null ? '' : recipeIdentityOf(selectedRecipe); + if (nextIdentity !== nutritionAuthorityRecipeIdentityRef.current) { + nutritionAuthorityRecipeIdentityRef.current = nextIdentity; + shisoLifecycleEpochRef.current += 1; + nutritionWriteAuthorityRef.current = null; + } selectedRecipeRef.current = selectedRecipe; // Global/create SHISO never adopts an ambient selected recipe. An explicit // in-conversation selection sets the SHISO ref directly and is preserved. @@ -4945,14 +5383,24 @@ export default function App({

- Unsaved recipe changes.{' '} - {shisoWorkingChangeLines.length} change - {shisoWorkingChangeLines.length === 1 ? '' : 's'} are in the working copy. Your Vault recipe is unchanged until you save. + {shisoWorkingForSelected.historyConflict ? ( + <> + Draft conflict.{' '} + {shisoWorkingForSelected.historyConflict} Your Vault recipe is unchanged. + + ) : ( + <> + Unsaved recipe changes.{' '} + {shisoWorkingChangeLines.length} change + {shisoWorkingChangeLines.length === 1 ? '' : 's'} are in the working copy. Saving writes the complete recipe. Your Vault recipe is unchanged until you save. + + )}