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
401 changes: 269 additions & 132 deletions server/metadataRecovery.ts

Large diffs are not rendered by default.

30 changes: 23 additions & 7 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
type VaultSessionKind,
type VaultTransition,
} from './core/vaultSession';
import { canPublishSavedImage } from './application/imageSaveRefresh';
import type { VaultAdapter } from './application/adapters/VaultAdapter';
import { createVaultAssetScope, type SessionAssetRunner, type VaultAssetScope, type VaultCollectionImportStart } from './utils/vaultAssets';
import { validateRecipeAssetReferences } from './utils/assetReferences';
Expand Down Expand Up @@ -552,6 +553,11 @@ export default function App({
const vaultHydratedRef = useRef(true);
const lastImageSaveSessionRef = useRef<VaultSession | null>(null);
const lastImageSaveRevisionRef = useRef<number | null>(null);
// Revisions captured around the image save's OWN collection invalidation.
// The handler must compare the pre-save and post-save values without treating
// this save's expected +1 as a concurrent-write conflict.
const lastImageSaveCommittedRevisionRef = useRef<number | null>(null);
const lastImageSavePostMarkRevisionRef = useRef<number | null>(null);
const appUnmountedRef = useRef(false);
const shutdownTransitionRef = useRef<VaultTransition | null>(null);
const assetScopeDisposalTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
Expand Down Expand Up @@ -862,13 +868,20 @@ export default function App({
if (!lease) throw new Error('The active Vault changed before the image could be saved.');
lastImageSaveSessionRef.current = active.session;
lastImageSaveRevisionRef.current = vaultAuthority.collectionRevision(active.session);
lastImageSaveCommittedRevisionRef.current = null;
lastImageSavePostMarkRevisionRef.current = null;
try {
const result = await saveGeneratedRecipeImageToVault(
{ vault: active.adapter, asset, assetScope: active.assetScope, previewSource },
{ recipePath, recipeTitle, token, activeVaultSessionId, approved: true }
);
// Capture the revision AFTER the committed save but BEFORE this save's
// own scan invalidation. The success handler uses this to distinguish
// its own +1 from a genuine concurrent write.
lastImageSaveCommittedRevisionRef.current = vaultAuthority.collectionRevision(active.session);
// Invalidate stale scans before releasing the write lease.
if (vaultAuthority.isCurrent(active.session)) vaultAuthority.markCollectionChanged(active.session);
lastImageSavePostMarkRevisionRef.current = vaultAuthority.collectionRevision(active.session);
return result;
} finally {
lease.release();
Expand Down Expand Up @@ -1659,14 +1672,17 @@ export default function App({
if (!saveSession || !vaultAuthority.isCurrent(saveSession) || vaultAuthority.writesBlocked()) return;
if (isBuiltInRecipe(recipesRef.current.find((r) => r.id === recipeId))) return;
const startRevision = lastImageSaveRevisionRef.current;
const committedRevision = lastImageSaveCommittedRevisionRef.current;
const postMarkRevision = lastImageSavePostMarkRevisionRef.current;
const currentRevision = vaultAuthority.collectionRevision(saveSession);
// Recovery has committed both the asset and canonical Markdown. Advance the
// collection revision so a scan that captured the pre-recovery snapshot
// cannot commit over this result.
vaultAuthority.markCollectionChanged(saveSession);
if (startRevision !== null && currentRevision !== null && currentRevision !== startRevision) {
// A newer collection mutation intervened. Do not publish a stale recipe
// projection; the next authoritative scan will read the committed files.
// The save itself advances the revision by one. Compare the pre-save
// revision with the revision captured immediately after the committed save
// (before our own invalidation), then verify no later mutation occurred.
// The save's invalidation already happened inside the write lease, so it
// must not be mistaken for a conflict here.
if (!canPublishSavedImage({ startRevision, committedRevision, postMarkRevision, currentRevision })) {
// A genuine newer collection mutation intervened. Do not publish a stale
// recipe projection; the next authoritative scan reads the committed files.
setVaultNotice({
tone: 'info',
message: 'The image was saved, but the Vault state changed during the operation. Refresh to view the latest state.',
Expand Down
40 changes: 40 additions & 0 deletions src/application/imageSaveRefresh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Revision reconciliation for the image-save success handler.
*
* The save flow holds a Vault write lease, commits the asset + canonical
* Markdown, captures the revision BEFORE its own scan invalidation, then
* advances the revision and releases the lease. The success handler must:
*
* - ignore that expected self-invalidation, and
* - still reject a genuine concurrent write during or after the save.
*
* Keeping the comparison pure makes the sequence testable and prevents the
* save's own +1 from being mistaken for a conflict.
*/
export interface ImageSaveRevisionSnapshot {
/** Revision captured when the save began. */
readonly startRevision: number | null;
/** Revision after the committed save, before this save's invalidation. */
readonly committedRevision: number | null;
/** Revision after this save's own invalidation. */
readonly postMarkRevision: number | null;
/** Revision observed by the success handler. */
readonly currentRevision: number | null;
}

export function canPublishSavedImage(snapshot: ImageSaveRevisionSnapshot): boolean {
const { startRevision, committedRevision, postMarkRevision, currentRevision } = snapshot;
if (
startRevision === null ||
committedRevision === null ||
postMarkRevision === null ||
currentRevision === null
) {
return false;
}
// A write during the save changed the revision before our invalidation.
if (committedRevision !== startRevision) return false;
// The expected self-invalidation produced postMarkRevision; anything later
// means a genuine concurrent write intervenes before the handler publishes.
return currentRevision === postMarkRevision;
}
10 changes: 8 additions & 2 deletions src/components/CreateForMeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -487,10 +487,16 @@ export function CreateForMeModal({ isOpen, onClose, network, onSaveRecipe }: Cre
// preparation/optional/timer fields and rejects empty required fields or
// any malformed edited shape; no partial draft is saved.
edited = normalizeGeneratedRecipeDraft(editedDraft ?? draft);
} catch {
} catch (error) {
const detail = error instanceof Error ? error.message : '';
const explicit = detail.startsWith('Generated recipe draft is invalid:')
? detail.slice('Generated recipe draft is invalid: '.length).trim()
: '';
dispatch({
type: 'SAVE_FAILURE',
message: 'Please complete the recipe title, every ingredient name, and every step before saving.',
message: explicit
? `Fix the invalid recipe fields before saving: ${explicit.slice(0, 400)}`
: 'Please complete the recipe title, every ingredient name, and every step before saving.',
});
session.current.setBusy(false);
return;
Expand Down
22 changes: 10 additions & 12 deletions src/components/VaultIntelligenceModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import {
summarizeVaultHealth,
mergeRecoveredMetadata,
normalizeTimeString,
defaultAcceptedRecoveredFields,
selectBatchAcceptedRecoveredFields,
} from '../utils/vaultIntelligence';
import {
assessRecipeImageHealth,
Expand Down Expand Up @@ -591,15 +593,10 @@ const res = await network.post<{ recovered?: any; error?: string }>(
const data = res.data;
if (data?.recovered) {
setRecoveredData(data.recovered);
// Default only missing fields to true, present fields to false to avoid overwriting unless user opts in
const newAccepted: Record<string, boolean> = {};
// Default only independently supported missing fields. Category,
// cuisine, tags, calories, and nutrition remain explicit opt-ins.
const missing = assessRecipeHealth(recipe).missingFields;

(Object.keys(data.recovered) as (keyof RecoveredRecipeMetadata)[]).forEach((field) => {
// If field is in missingFields or was empty, accept it by default
newAccepted[field] = missing.includes(field) || field === 'suggestedTags' || field === 'nutrition';
});
setAcceptedFields(newAccepted);
setAcceptedFields(defaultAcceptedRecoveredFields(data.recovered, missing));
} else {
throw new Error('No metadata recovery payload returned from server.');
}
Expand Down Expand Up @@ -685,9 +682,10 @@ const res = await network.post<{ recovered?: any; error?: string }>(
const data = res.data;
if (data?.recovered) {
const missing = assessRecipeHealth(rec).missingFields;
const fieldsToAccept = (Object.keys(data.recovered) as (keyof RecoveredRecipeMetadata)[]).filter(
(f) => missing.includes(f) || f === 'suggestedTags'
);
// Bulk recovery applies ONLY independently supported, high-confidence
// explicit/body-parsed values. Guesses stay in the per-recipe review.
const fieldsToAccept = selectBatchAcceptedRecoveredFields(data.recovered, missing);
if (fieldsToAccept.length === 0) continue;
const merged = mergeRecoveredMetadata(rec, data.recovered, fieldsToAccept);
updatedRecipes.push(merged);
await onSaveRecipe(merged);
Expand Down Expand Up @@ -1217,7 +1215,7 @@ const res = await network.post<{ recovered?: any; error?: string }>(
~{recoveredData.calories.value} kcal / serving
{recoveredData.nutrition?.value && (
<span className="text-[10px] text-gray-400 font-sans font-normal ml-2">
(P: {recoveredData.nutrition.value.protein}g | C: {recoveredData.nutrition.value.carbohydrates}g | F: {recoveredData.nutrition.value.fat}g)
(batch total: P {recoveredData.nutrition.value.protein}g | C {recoveredData.nutrition.value.carbohydrates}g | F {recoveredData.nutrition.value.fat}g)
</span>
)}
</div>
Expand Down
40 changes: 36 additions & 4 deletions src/schema/generatedRecipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ export const MAX_GENERATED_TAGS = 30;
export const MAX_CREATE_PROMPT_LENGTH = 1200;
/** Max constraint-list item count (e.g. dietary / exclude ingredients). */
export const MAX_CONSTRAINT_ITEMS = 20;
/**
* Bounded ingredient text. These are intentionally generous enough for real
* culinary descriptions (cut, brand, variety, preparation) while still
* preventing unbounded provider output. Over-limit fields are REJECTED, never
* silently truncated.
*/
export const MAX_GENERATED_INGREDIENT_NAME_LENGTH = 240;
export const MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH = 240;

/** A single generated ingredient. Deliberately wikilink-free (no auto-linking). */
export interface GeneratedIngredient {
Expand Down Expand Up @@ -118,6 +126,17 @@ function trimString(v: unknown, max: number): string | undefined {
return t.length > max ? t.slice(0, max) : t || undefined;
}

/** Trim only; callers must validate the bound before normalization. */
function trimExact(v: unknown): string | undefined {
if (typeof v !== 'string') return undefined;
const t = v.trim();
return t || undefined;
}

function exceeds(value: string, max: number): boolean {
return value.length > max;
}

function isFiniteNumber(v: unknown): v is number {
return typeof v === 'number' && Number.isFinite(v);
}
Expand All @@ -133,13 +152,15 @@ function normalizeIngredient(raw: unknown): GeneratedIngredient | null {
return name ? { name } : null;
}
if (!isPlainObject(raw)) return null;
const name = trimString(raw['name'], 80);
// The authoritative validator rejects over-limit values before this runs.
// Never slice here: a shortened ingredient is fabricated content.
const name = trimExact(raw['name']);
if (!name) return null;
return {
name,
...(isFiniteNumber(raw['amount']) ? { amount: raw['amount'] as number } : {}),
...(raw['unit'] !== undefined ? { unit: trimString(raw['unit'], 20) } : {}),
...(raw['preparation'] !== undefined ? { preparation: trimString(raw['preparation'], 80) } : {}),
...(raw['preparation'] !== undefined ? { preparation: trimExact(raw['preparation']) } : {}),
...(raw['optional'] === true ? { optional: true } : {}),
};
}
Expand Down Expand Up @@ -265,10 +286,21 @@ export function validateGeneratedRecipeDraft(raw: unknown): GeneratedRecipeValid
}
if (!isString(ing['name']) || !(ing['name'] as string).trim()) {
errors.push(`ingredients[${i}].name is required`);
} else if (exceeds((ing['name'] as string).trim(), MAX_GENERATED_INGREDIENT_NAME_LENGTH)) {
errors.push(`ingredients[${i}].name exceeds ${MAX_GENERATED_INGREDIENT_NAME_LENGTH} characters`);
}
if (ing['preparation'] !== undefined) {
if (!isString(ing['preparation'])) {
errors.push(`ingredients[${i}].preparation must be a string`);
} else if (exceeds((ing['preparation'] as string).trim(), MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH)) {
errors.push(`ingredients[${i}].preparation exceeds ${MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH} characters`);
}
}
if (ing['optional'] !== undefined && typeof ing['optional'] !== 'boolean') {
errors.push(`ingredients[${i}].optional must be a boolean`);
}
} else if (typeof ing === 'string' && exceeds(ing.trim(), MAX_GENERATED_INGREDIENT_NAME_LENGTH)) {
errors.push(`ingredients[${i}] exceeds ${MAX_GENERATED_INGREDIENT_NAME_LENGTH} characters`);
}
});
}
Expand Down Expand Up @@ -318,8 +350,8 @@ export function buildGeneratedRecipeSchema(): AiJsonSchema {
properties: {
amount: { type: 'number' },
unit: { type: 'string', description: 'Standardized unit, e.g. tbsp, cup, g, ml' },
name: { type: 'string', description: 'Ingredient name' },
preparation: { type: 'string', description: 'Preparation modifier, e.g. diced' },
name: { type: 'string', description: `Ingredient name (max ${MAX_GENERATED_INGREDIENT_NAME_LENGTH} characters)` },
preparation: { type: 'string', description: `Preparation modifier, e.g. diced (max ${MAX_GENERATED_INGREDIENT_PREPARATION_LENGTH} characters)` },
optional: { type: 'boolean' },
},
required: ['name'],
Expand Down
72 changes: 66 additions & 6 deletions src/utils/vaultIntelligence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,12 @@ export function assessRecipeHealth(recipe: ObsidianRecipe): MetadataHealthReport
if (hasCuisine) presentFields.push('cuisine');
else missingFields.push('cuisine');

// 5. Difficulty & Rating & Tags Check (Weight: 10)
// 5. Difficulty & Tags Check. A personal rating is OPTIONAL and must never be
// reported as missing metadata or lower the recipe's quality score.
if (recipe.difficulty) presentFields.push('difficulty');
else missingFields.push('difficulty');

if (recipe.rating) presentFields.push('rating');
else missingFields.push('rating');

const hasSpecificTags = recipe.tags && recipe.tags.length > 0 && !(recipe.tags.length === 1 && recipe.tags[0] === 'food/recipes');
if (hasSpecificTags) presentFields.push('tags');
Expand Down Expand Up @@ -184,9 +184,9 @@ export function assessRecipeHealth(recipe: ObsidianRecipe): MetadataHealthReport
if (hasCategory && hasCuisine) score += 15;
else if (hasCategory || hasCuisine) score += 8;

// Difficulty & Rating & Tags: up to 10 pts
if (recipe.difficulty) score += 3;
if (recipe.rating) score += 3;
// Difficulty & Tags: up to 10 pts. Rating is optional personal data and
// does not affect metadata quality or the score.
if (recipe.difficulty) score += 6;
if (hasSpecificTags) score += 4;

// Core structure: up to 10 pts
Expand Down Expand Up @@ -344,7 +344,10 @@ export function mergeRecoveredMetadata(
const nutr = item.value as RecipeNutrition;
updated.nutrition = nutr;
frontmatter.nutrition = nutr;
if (nutr.calories && !frontmatter.calories) {
// When `servings` is present the nutrition block is TOTAL batch
// nutrition. Never copy that total into the per-serving `calories`
// field; the separate calories suggestion carries per-serving values.
if (nutr.calories && !frontmatter.calories && !(typeof nutr.servings === 'number' && nutr.servings > 0)) {
frontmatter.calories = nutr.calories;
updated.calories = nutr.calories;
}
Expand Down Expand Up @@ -398,3 +401,60 @@ export function mergeRecoveredMetadata(

return updated;
}

/**
* Fields that are suggestions rather than independently supported facts. They
* may be displayed for manual review, but must never be selected by default or
* applied automatically by bulk recovery.
*/
const MANUAL_ONLY_RECOVERED_FIELDS = new Set<keyof RecoveredRecipeMetadata>([
'category',
'cuisine',
'difficulty',
'suggestedTags',
'calories',
'nutrition',
]);

/**
* Default checkbox state for the single-recipe recovery review. Only a missing,
* HIGH-confidence, non-speculative field is selected. Category/cuisine/tags/
* difficulty/nutrition guesses and every medium/low-confidence inference remain
* explicit opt-ins.
*/
export function defaultAcceptedRecoveredFields(
recovered: RecoveredRecipeMetadata,
missingFields: readonly string[],
): Record<string, boolean> {
const accepted: Record<string, boolean> = {};
for (const field of Object.keys(recovered) as (keyof RecoveredRecipeMetadata)[]) {
const item = recovered[field];
accepted[field] =
missingFields.includes(field) &&
!MANUAL_ONLY_RECOVERED_FIELDS.has(field) &&
item?.confidence === 'high';
}
return accepted;
}

/**
* Bulk recovery may apply ONLY independently supported, high-confidence fields
* that were missing. Inferred category/cuisine/tags/nutrition, difficulty, and
* every culinary-inference value are excluded; they remain available only via
* the explicit per-recipe review.
*/
export function selectBatchAcceptedRecoveredFields(
recovered: RecoveredRecipeMetadata,
missingFields: readonly string[],
): (keyof RecoveredRecipeMetadata)[] {
const accepted: (keyof RecoveredRecipeMetadata)[] = [];
for (const field of Object.keys(recovered) as (keyof RecoveredRecipeMetadata)[]) {
if (!missingFields.includes(field)) continue;
if (MANUAL_ONLY_RECOVERED_FIELDS.has(field)) continue;
const item = recovered[field];
if (!item || item.confidence !== 'high') continue;
if (item.source !== 'instructions_explicit' && item.source !== 'body_parsed') continue;
accepted.push(field);
}
return accepted;
}
Loading