Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

add catalog_ingredient_media join table for typed image/audio/video attachments

[._.]/ Adam Eivy1a6dc49f184a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b520a3a88c..39851ad81a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,8 @@
## Added
+- **[catalog-ingredient-media-refs] Catalog ingredients can now carry typed media attachments — a portrait, mood/reference images, and more.** A new "Media" panel on each ingredient detail page lets you set one portrait (rendered large at the head) and attach additional reference images, scoped to your existing media gallery via a "Pick from gallery" picker or by dragging a gallery image onto the panel. Each attachment stores a `media_key` *reference* into your media library (the bytes are never duplicated into the catalog), so a federated peer that receives an ingredient gets its media-key list and matches it against its own library — keys whose asset hasn't arrived yet show a "missing" badge (via the same syncing-asset surface used elsewhere) instead of a broken image. Backed by a new `catalog_ingredient_media` Postgres table (kinds: portrait / reference / audio / video / document) with soft-delete tombstones from day one, so detaches propagate to peers; the rows ride the catalog sync envelope as a new `media` block (`PORTOS_SCHEMA_VERSIONS.catalog` bumped to 6 — a peer on an older catalog schema gets a clean 412 rather than silently dropping every attachment). `POST/DELETE /api/catalog/ingredients/:id/media`, `POST …/media/portrait`, and `GET …/media` + `…/media/missing` are Zod-validated; attaching rejects a key that doesn't resolve against the local library with a 422. Voice-memo capture is intentionally left as a clean seam for the separate source-kinds work.
+
- **[catalog-ingredient-revisions] Catalog ingredients now keep an edit history with inline diff + restore.** Every time a catalog ingredient's name, payload, or tags change — a manual detail-page save, an ingest commit, or a future AI refinement pass — a revision row is recorded, and a new "Revision history" panel on the ingredient detail page lists them newest-first with a source badge (user / extract / refine / sync) and a relative timestamp. Expand any revision to see a field-by-field diff against the current saved state, and click "Restore" on an older revision to roll back (the restore is itself recorded as a new revision, so it's auditable and reversible). Backed by a new append-only `catalog_ingredient_revisions` Postgres table (foreign-keyed to `catalog_ingredients` with ON DELETE CASCADE); retention is capped at the most recent 50 revisions per ingredient (configurable via the `CATALOG_REVISION_RETENTION` env var) so history can't grow unbounded from rapid edits. The history is local audit data — it is intentionally NOT federated (the synced ingredient row already last-write-wins-merges the latest state across peers), so the catalog sync wire version is unchanged.
- **[catalog-ingredient-relations] Catalog ingredients can now link to each other — the catalog is a graph, not a flat list.** A new "Relations" panel on each ingredient detail page lets you connect one ingredient to another via the existing Ingredient Picker — a character to the place they *live in*, a scene to the cast that *appears in* it, a concept *referenced by* an object, and so on (kinds: appears-in, lives-in, created-by, parent-of, variant-of, references, related-to). Edges are directed: the panel shows both outbound relations (this ingredient → other, editable here) and inbound ones (other → this ingredient, read-only because the other end owns them, rendered with the inverse label). Backed by a new `catalog_ingredient_relations` Postgres table with both ids foreign-keyed to `catalog_ingredients` (ON DELETE CASCADE) and soft-delete tombstones from day one, so unlinks propagate to federated peers instead of silently vanishing. The edges ride the existing catalog sync envelope as a new `relations` block (`PORTOS_SCHEMA_VERSIONS.catalog` bumped to 4 — a peer on an older catalog schema gets a clean 412 rather than silently dropping every relation). `POST`/`DELETE /api/catalog/ingredients/:id/relations` and `GET …/relations` are Zod-validated; self-edges are rejected.
diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.js
index 3ca5b02b40..21d37b566d 100644
--- a/client/src/lib/catalogTypes.js
+++ b/client/src/lib/catalogTypes.js
@@ -139,6 +139,28 @@ export function getRelationKind(id) {
return RELATION_BY_ID[id];
}
+/**
+ * Catalog ingredient MEDIA-attachment kinds — client mirror of
+ * `server/lib/catalogTypes.js` MEDIA_KINDS. Drives the "Media" panel attach
+ * picker / drag-drop on the ingredient detail page. `accept` is the file-input
+ * MIME filter. Drift is asserted by `client/src/lib/catalogTypes.test.js`
+ * against the server registry — change one side, change the other.
+ */
+export const MEDIA_KINDS = Object.freeze([
+ { id: 'portrait', label: 'Portrait', accept: 'image/*' },
+ { id: 'reference', label: 'Reference', accept: 'image/*' },
+ { id: 'audio', label: 'Audio', accept: 'audio/*' },
+ { id: 'video', label: 'Video', accept: 'video/*' },
+ { id: 'document', label: 'Document', accept: '.pdf,.txt,.md' },
+]);
+
+const MEDIA_BY_ID = Object.freeze(Object.fromEntries(MEDIA_KINDS.map((m) => [m.id, m])));
+
+/** Look up a media-kind entry by id. Returns `undefined` for unknown ids. */
+export function getMediaKind(id) {
+ return MEDIA_BY_ID[id];
+}
+
const BY_ID = Object.freeze(Object.fromEntries(CATALOG_TYPES.map((t) => [t.id, t])));
/** Look up a registry entry by type id. Returns `undefined` for unknown ids. */
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 1f2bb2c1b3..d4fe843875 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -5,9 +5,9 @@
* pipeline series / issues / writers-room). Full-width page; owns its scroll.
*/
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
-import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw } from 'lucide-react';
+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
getCatalogIngredient,
@@ -18,8 +18,15 @@ import {
unlinkCatalogIngredientRelation,
listCatalogIngredientRevisions,
restoreCatalogIngredientRevision,
+ listCatalogIngredientMedia,
+ listCatalogIngredientMissingMedia,
+ attachCatalogIngredientMedia,
+ setCatalogIngredientPortrait,
+ detachCatalogIngredientMedia,
} from '../services/apiCatalog';
+import { listImageGallery } from '../services/apiImageVideo';
import IngredientPicker from '../components/IngredientPicker';
+import MediaImage from '../components/MediaImage';
import TagPicker from '../components/TagPicker';
import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';
import { timeAgo } from '../utils/formatters';
@@ -65,6 +72,11 @@ export default function CatalogIngredient() {
// remove without re-fetching the whole detail payload.
const [relations, setRelations] = useState({ outbound: [], inbound: [] });
const [revisions, setRevisions] = useState([]);
+ // Media attachments + the subset of their keys that don't resolve against the
+ // local library (federated-in but asset not yet present). `missingMedia` is a
+ // Set of media_keys driving the integrity badge on each thumbnail.
+ const [media, setMedia] = useState([]);
+ const [missingMedia, setMissingMedia] = useState(new Set());
const refreshRevisions = useCallback(() => {
if (!id) return;
@@ -151,6 +163,53 @@ export default function CatalogIngredient() {
}));
};
+ // Load media attachments + the integrity (missing-key) overlay. Both refresh
+ // independently of the detail payload so attach/detach updates the panel
+ // without re-fetching the whole record.
+ const refreshMedia = useCallback(() => {
+ if (!id) return;
+ listCatalogIngredientMedia(id, { silent: true })
+ .then((rows) => setMedia(Array.isArray(rows) ? rows : []))
+ .catch(() => { /* media is non-critical — leave the panel empty */ });
+ listCatalogIngredientMissingMedia(id, { silent: true })
+ .then((r) => setMissingMedia(new Set(Array.isArray(r?.missing) ? r.missing.map((m) => m.mediaKey) : [])))
+ .catch(() => { /* integrity overlay is best-effort */ });
+ }, [id]);
+
+ useEffect(() => { refreshMedia(); }, [refreshMedia]);
+
+ // Attach a media key (gallery filename) as a typed attachment. `kind` defaults
+ // to 'reference' for drag-drop / picker; the "set portrait" path routes
+ // through handleSetPortrait instead. Optimistic — prepend then reconcile.
+ const handleAttachMedia = async (mediaKey, kind = 'reference') => {
+ if (!record || !mediaKey) return;
+ const ok = await attachCatalogIngredientMedia(record.id, { mediaKey, kind }, { silent: true })
+ .then(() => true)
+ .catch((err) => { toast.error(err?.message || 'Failed to attach media'); return false; });
+ if (!ok) return;
+ refreshMedia();
+ toast.success('Media attached');
+ };
+
+ const handleSetPortrait = async (mediaKey) => {
+ if (!record || !mediaKey) return;
+ const ok = await setCatalogIngredientPortrait(record.id, { mediaKey }, { silent: true })
+ .then(() => true)
+ .catch((err) => { toast.error(err?.message || 'Failed to set portrait'); return false; });
+ if (!ok) return;
+ refreshMedia();
+ toast.success('Portrait set');
+ };
+
+ const handleDetachMedia = async (mediaKey, kind) => {
+ if (!record) return;
+ const ok = await detachCatalogIngredientMedia(record.id, { mediaKey, kind }, { silent: true })
+ .then(() => true)
+ .catch((err) => { toast.error(err?.message || 'Failed to detach media'); return false; });
+ if (!ok) return;
+ setMedia((prev) => prev.filter((m) => !(m.mediaKey === mediaKey && m.kind === kind)));
+ };
+
const handleSave = async () => {
if (!record) return;
const trimmedName = name.trim();
@@ -316,6 +375,14 @@ export default function CatalogIngredient() {
onRemove={handleRemoveRelation}
/>
+ <MediaPanel
+ media={media}
+ missingMedia={missingMedia}
+ onAttach={handleAttachMedia}
+ onSetPortrait={handleSetPortrait}
+ onDetach={handleDetachMedia}
+ />
+
<RevisionsPanel
revisions={revisions}
current={record}
@@ -416,6 +483,171 @@ function RelationsPanel({ record, relations, onAdd, onRemove }) {
);
}
+// "Media" panel — typed image/audio/video/document attachments. Each row
+// stores a `media_key` REFERENCE into the media library (never the bytes), so
+// the panel scopes its picker to the existing gallery/history. The portrait
+// (one per ingredient) renders large at the head; other attachments tile below.
+// Drag-and-drop accepts an in-app gallery filename dragged as text (the
+// dashboard/gallery tiles set `dataTransfer.setData('text/plain', filename)`);
+// file-upload + voice-memo capture are intentionally out of scope here and
+// land via the separate `[catalog-source-kinds-url-file-voice]` item — the
+// `onAttach(mediaKey, kind)` seam is all those paths need to reuse.
+function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach }) {
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [dragOver, setDragOver] = useState(false);
+ const list = Array.isArray(media) ? media : [];
+ const portrait = list.find((m) => m.kind === 'portrait');
+ const others = list.filter((m) => m.kind !== 'portrait');
+
+ const onDrop = (e) => {
+ e.preventDefault();
+ setDragOver(false);
+ // In-app gallery DnD: the dragged tile carries its filename as text.
+ const key = (e.dataTransfer.getData('text/plain') || '').trim();
+ if (key) { onAttach(key, 'reference'); return; }
+ toast.error('Drop a gallery image, or use “Pick from gallery”. File upload coming soon.');
+ };
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center justify-between mb-3">
+ <h2 className="text-sm font-semibold text-white flex items-center gap-1.5">
+ <ImageIcon size={14} aria-hidden="true" /> Media
+ </h2>
+ <button type="button" onClick={() => setPickerOpen(true)}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">
+ <Plus size={12} aria-hidden="true" /> Pick from gallery
+ </button>
+ </div>
+
+ <div
+ onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
+ onDragLeave={() => setDragOver(false)}
+ onDrop={onDrop}
+ className={`mb-3 rounded-lg border border-dashed p-3 text-center text-xs transition-colors ${dragOver ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-500'}`}
+ >
+ Drag a gallery image here to attach it as a reference.
+ </div>
+
+ {portrait && (
+ <div className="mb-3">
+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Portrait</div>
+ <MediaTile m={portrait} missing={missingMedia.has(portrait.mediaKey)} isPortrait
+ onSetPortrait={onSetPortrait} onDetach={onDetach} />
+ </div>
+ )}
+
+ {others.length > 0 && (
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
+ {others.map((m) => (
+ <MediaTile key={`${m.mediaKey}:${m.kind}`} m={m} missing={missingMedia.has(m.mediaKey)}
+ onSetPortrait={onSetPortrait} onDetach={onDetach} />
+ ))}
+ </div>
+ )}
+
+ {list.length === 0 && (
+ <p className="text-xs text-gray-500">No media yet. Attach a generated portrait, a mood/reference image, or a recorded memo (memo capture coming soon).</p>
+ )}
+
+ {pickerOpen && (
+ <GalleryPickerModal
+ onClose={() => setPickerOpen(false)}
+ onPick={(filename, asPortrait) => {
+ if (asPortrait) onSetPortrait(filename);
+ else onAttach(filename, 'reference');
+ setPickerOpen(false);
+ }}
+ />
+ )}
+ </section>
+ );
+}
+
+// One media attachment tile. Images render via <MediaImage> (gracefully shows a
+// "syncing" placeholder when the asset hasn't arrived — the same surface the
+// `missing` integrity flag warns about). Non-image kinds render a labeled chip.
+function MediaTile({ m, missing, isPortrait = false, onSetPortrait, onDetach }) {
+ const isImage = m.kind === 'portrait' || m.kind === 'reference';
+ return (
+ <div className="relative group rounded border border-port-border overflow-hidden bg-port-bg">
+ {isImage ? (
+ <MediaImage src={`/data/images/${m.mediaKey}`} alt={m.caption || m.kind}
+ className={isPortrait ? 'w-full max-w-[180px] aspect-square object-cover' : 'w-full aspect-square object-cover'} />
+ ) : (
+ <div className="w-full aspect-square flex items-center justify-center text-[10px] uppercase tracking-wider text-gray-400 px-1 text-center">
+ {m.kind}<br />{m.mediaKey}
+ </div>
+ )}
+ {missing && (
+ <span className="absolute top-1 left-1 text-[9px] px-1 py-0.5 rounded bg-port-warning/20 text-port-warning border border-port-warning/40"
+ title="This asset isn't in your media library yet (received from a peer before the file arrived).">
+ missing
+ </span>
+ )}
+ <div className="absolute top-1 right-1 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
+ {!isPortrait && isImage && (
+ <button type="button" onClick={() => onSetPortrait(m.mediaKey)} title="Set as portrait"
+ className="p-1 rounded bg-black/60 text-gray-200 hover:text-port-warning">
+ <Star size={12} aria-hidden="true" />
+ </button>
+ )}
+ <button type="button" onClick={() => onDetach(m.mediaKey, m.kind)} title="Detach"
+ className="p-1 rounded bg-black/60 text-gray-200 hover:text-port-error">
+ <X size={12} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+// Modal that lists the existing media gallery (history) so the user can attach
+// or set-portrait from already-generated assets — the "scoped to existing media
+// history" requirement. Never uploads; it only references library keys.
+function GalleryPickerModal({ onClose, onPick }) {
+ const [items, setItems] = useState(null); // null = loading, [] = loaded-empty
+ const closeRef = useRef(null);
+
+ useEffect(() => {
+ listImageGallery()
+ .then((rows) => setItems(Array.isArray(rows) ? rows : []))
+ .catch(() => setItems([]));
+ }, []);
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" onClick={onClose}>
+ <div className="bg-port-card border border-port-border rounded-lg w-full max-w-2xl max-h-[80vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
+ <div className="flex items-center justify-between p-3 border-b border-port-border">
+ <h3 className="text-sm font-semibold text-white">Pick from media gallery</h3>
+ <button ref={closeRef} type="button" onClick={onClose} className="text-gray-400 hover:text-white" aria-label="Close">
+ <X size={16} />
+ </button>
+ </div>
+ <div className="p-3 overflow-y-auto">
+ {items === null && <p className="text-xs text-gray-500">Loading gallery…</p>}
+ {items?.length === 0 && <p className="text-xs text-gray-500">No images in the gallery yet. Generate one in Image Gen first.</p>}
+ {items && items.length > 0 && (
+ <div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
+ {items.map((it) => (
+ <div key={it.filename} className="relative group rounded border border-port-border overflow-hidden">
+ <MediaImage src={it.path || `/data/images/${it.filename}`} alt={it.filename}
+ className="w-full aspect-square object-cover" />
+ <div className="absolute inset-x-0 bottom-0 flex opacity-0 group-hover:opacity-100 transition-opacity">
+ <button type="button" onClick={() => onPick(it.filename, false)}
+ className="flex-1 text-[10px] py-1 bg-black/70 text-gray-200 hover:text-white">Attach</button>
+ <button type="button" onClick={() => onPick(it.filename, true)}
+ className="flex-1 text-[10px] py-1 bg-black/70 text-gray-200 hover:text-port-warning">Portrait</button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
function SourcesPanel({ sources }) {
const list = Array.isArray(sources) ? sources : [];
return (
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 585c1d2997..f195b761af 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -109,6 +109,23 @@ export const linkCatalogIngredientRelation = (id, body, options) =>
export const unlinkCatalogIngredientRelation = (id, body, options) =>
request(`/catalog/ingredients/${enc(id)}/relations`, { method: 'DELETE', body: JSON.stringify(body), ...options });
+// --- Media attachments (portrait / reference / audio / video / document) ---
+
+export const listCatalogIngredientMedia = (id, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media`, options);
+
+export const listCatalogIngredientMissingMedia = (id, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media/missing`, options);
+
+export const attachCatalogIngredientMedia = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media`, { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const setCatalogIngredientPortrait = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media/portrait`, { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const detachCatalogIngredientMedia = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media`, { method: 'DELETE', body: JSON.stringify(body), ...options });
+
// --- Bulk import / export ----------------------------------------------
export const bulkImportCatalogIngredients = (body, options) =>
diff --git a/scripts/migrations/052-catalog-ingredient-media.js b/scripts/migrations/052-catalog-ingredient-media.js
new file mode 100644
index 0000000000..ac8ab4dcba
--- /dev/null
+++ b/scripts/migrations/052-catalog-ingredient-media.js
@@ -0,0 +1,27 @@
+/**
+ * Registration stub for the catalog_ingredient_media table (typed media
+ * attachments — portrait / reference / audio / video / document).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS catalog_ingredient_media` plus
+ * its indexes and the `trg_catalog_media_sync_seq` trigger — is idempotent and
+ * lives in `ensureSchema()` (`server/lib/db.js`) and the fresh-install seed
+ * (`server/scripts/init-db.sql`), both of which run at server boot AFTER the DB
+ * pool is up. The `scripts/migrations/` runner executes BEFORE the pool is
+ * initialized, so a DB-table create cannot live here — the same reason
+ * migrations 048/049/050/051 are boot-time + stub-registered.
+ *
+ * This stub exists so the media-attachment change is *registered the standard
+ * way*: it lands in `data/migrations.applied.json` so the migration ledger and
+ * `git log` show when ingredient media attachments were introduced. The table
+ * is additive (a brand-new table) and stores only `media_key` REFERENCES into
+ * the existing media library — no bytes are duplicated and there is no existing
+ * data to backfill.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('🖼️ catalog_ingredient_media: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.js
index 1ce54af31b..029b257d9c 100644
--- a/server/lib/catalogTypes.js
+++ b/server/lib/catalogTypes.js
@@ -288,6 +288,45 @@ export function getRelationKind(id) {
return RELATION_BY_ID[id];
}
+/**
+ * Catalog ingredient MEDIA-attachment kinds. An ingredient can carry typed
+ * media references (a generated portrait, a mood/reference image, a recorded
+ * voice memo, …) that point at the install's media library by `media_key` —
+ * the bytes are never duplicated into the catalog. `label` drives the attach
+ * picker; `accept` is the file-input MIME filter for drag-and-drop. The
+ * `portrait` kind is special-cased by `setPortraitMedia` (one active portrait
+ * per ingredient; attaching a new one demotes the prior). Client mirror lives
+ * in `client/src/lib/catalogTypes.js` (drift asserted by the type tests).
+ */
+const MEDIA_KIND_REGISTRY = [
+ { id: 'portrait', label: 'Portrait', accept: 'image/*' },
+ { id: 'reference', label: 'Reference', accept: 'image/*' },
+ { id: 'audio', label: 'Audio', accept: 'audio/*' },
+ { id: 'video', label: 'Video', accept: 'video/*' },
+ { id: 'document', label: 'Document', accept: '.pdf,.txt,.md' },
+];
+
+// Fail-fast at module load — duplicate / malformed media kinds block boot.
+const seenMediaIds = new Set();
+for (const m of MEDIA_KIND_REGISTRY) {
+ if (!m.id || typeof m.id !== 'string') throw new Error('catalogTypes: media entry missing id');
+ if (seenMediaIds.has(m.id)) throw new Error(`catalogTypes: duplicate media kind "${m.id}"`);
+ seenMediaIds.add(m.id);
+ if (!m.label) throw new Error(`catalogTypes: media "${m.id}" missing label`);
+}
+
+export const MEDIA_KINDS = Object.freeze(MEDIA_KIND_REGISTRY.map((m) => Object.freeze({ ...m })));
+
+/** Frozen ordered list of media kind ids — the canonical enum source. */
+export const MEDIA_KIND_IDS = Object.freeze(MEDIA_KINDS.map((m) => m.id));
+
+const MEDIA_BY_ID = Object.freeze(Object.fromEntries(MEDIA_KINDS.map((m) => [m.id, m])));
+
+/** Look up a media-kind entry by id. Returns `undefined` for unknown ids. */
+export function getMediaKind(id) {
+ return MEDIA_BY_ID[id];
+}
+
/**
* Run a payload through its registered upgrader chain up to the current
* version. Each upgrader is keyed by the FROM version. Returns the upgraded
diff --git a/server/lib/catalogTypes.test.js b/server/lib/catalogTypes.test.js
index 61aef22541..6ab0a26629 100644
--- a/server/lib/catalogTypes.test.js
+++ b/server/lib/catalogTypes.test.js
@@ -27,6 +27,9 @@ import {
RELATION_KINDS,
RELATION_KIND_IDS,
getRelationKind,
+ MEDIA_KINDS,
+ MEDIA_KIND_IDS,
+ getMediaKind,
canonicalTagKey,
tagIdForKey,
defaultTagsForType,
@@ -243,3 +246,38 @@ describe('catalogTypes — relation kinds', () => {
expect(getRelationKind('nemesis-of')).toBeUndefined();
});
});
+
+describe('catalogTypes — media kinds', () => {
+ it('exposes the documented media kinds, frozen + unique', () => {
+ expect(Object.isFrozen(MEDIA_KINDS)).toBe(true);
+ for (const k of ['portrait', 'reference', 'audio', 'video', 'document']) {
+ expect(MEDIA_KIND_IDS).toContain(k);
+ }
+ expect(new Set(MEDIA_KIND_IDS).size).toBe(MEDIA_KIND_IDS.length);
+ });
+
+ it('every media kind has a label and an accept filter', () => {
+ for (const m of MEDIA_KINDS) {
+ expect(typeof m.label).toBe('string');
+ expect(m.label.length).toBeGreaterThan(0);
+ expect(typeof m.accept).toBe('string');
+ expect(m.accept.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('getMediaKind resolves a known id and returns undefined for unknown', () => {
+ expect(getMediaKind('portrait')?.label).toBe('Portrait');
+ expect(getMediaKind('hologram')).toBeUndefined();
+ });
+
+ it('client mirror has the same media kind ids + accept filters', async () => {
+ const client = await import('../../client/src/lib/catalogTypes.js');
+ expect(client.MEDIA_KINDS.map((m) => m.id)).toEqual([...MEDIA_KIND_IDS]);
+ for (const serverKind of MEDIA_KINDS) {
+ const clientKind = client.getMediaKind(serverKind.id);
+ expect(clientKind, `client mirror missing media kind ${serverKind.id}`).toBeTruthy();
+ expect(clientKind.label).toBe(serverKind.label);
+ expect(clientKind.accept).toBe(serverKind.accept);
+ }
+ });
+});
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index d58c1997fc..e120f2cee1 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -12,7 +12,7 @@
import { z } from 'zod';
import { BIBLE_LIMITS } from './storyBible.js';
-import { INGREDIENT_TYPE_IDS, RELATION_KIND_IDS } from './catalogTypes.js';
+import { INGREDIENT_TYPE_IDS, RELATION_KIND_IDS, MEDIA_KIND_IDS } from './catalogTypes.js';
// Derived from the shared type registry (`catalogTypes.js`) — adding a type
// there flows through to every Zod enum below automatically. Kept as a frozen
@@ -31,6 +31,9 @@ export const REF_KINDS = Object.freeze([
// a kind there flows through to the Zod enum below.
export const RELATION_KINDS = RELATION_KIND_IDS;
+// Media-attachment kinds derived from the shared registry — same pattern.
+export const MEDIA_KINDS = MEDIA_KIND_IDS;
+
const tag = z.string().trim().min(1).max(BIBLE_LIMITS.TAG_MAX);
const tags = z.array(tag).max(BIBLE_LIMITS.TAGS_PER_ENTRY_MAX).optional();
@@ -123,6 +126,31 @@ export const catalogRelationLinkSchema = z.object({
kind: z.enum(RELATION_KINDS),
}).strict();
+// Media attach body. `mediaKey` is a REFERENCE into the media library (a
+// gallery filename / history sidecar key), not the bytes — capped at a generous
+// 512 to allow nested paths but reject blobs. `kind` is gated to the shared
+// media registry; `role`/`caption` are optional metadata. The route validates
+// that the key resolves against the local library before persisting.
+export const catalogMediaAttachSchema = z.object({
+ mediaKey: z.string().trim().min(1).max(512),
+ kind: z.enum(MEDIA_KINDS),
+ role: z.string().trim().max(64).optional().nullable(),
+ caption: z.string().trim().max(2_000).optional().nullable(),
+}).strict();
+
+// Set-portrait body — same as attach minus `kind` (the route forces 'portrait').
+export const catalogPortraitSetSchema = z.object({
+ mediaKey: z.string().trim().min(1).max(512),
+ role: z.string().trim().max(64).optional().nullable(),
+ caption: z.string().trim().max(2_000).optional().nullable(),
+}).strict();
+
+// Media detach body — identifies the tuple to soft-delete.
+export const catalogMediaDetachSchema = z.object({
+ mediaKey: z.string().trim().min(1).max(512),
+ kind: z.enum(MEDIA_KINDS),
+}).strict();
+
export const catalogScrapCommitSchema = z.object({
accepted: z.array(catalogIngredientCreateSchema.extend({
// Optional source-span hint (server forwards as-is to linkIngredientToSource).
@@ -297,6 +325,23 @@ export const catalogSyncTagSchema = z.object({
syncSequence: z.string().optional(),
}).passthrough();
+// Media rows carry tombstone fields + editable metadata (role/caption).
+// `kind` is freeform on the wire (not the strict enum) for the same forward-
+// compat reason as relations: a newer peer's extra media kind stores
+// harmlessly rather than 400-ing the whole envelope. `mediaKey` is a reference,
+// not bytes — the receiver matches it against its own library on apply.
+export const catalogSyncMediaSchema = z.object({
+ ingredientId: z.string().max(80),
+ mediaKey: z.string().max(512),
+ kind: z.string().max(32),
+ role: z.string().max(64).nullable().optional(),
+ caption: z.string().max(2_000).nullable().optional(),
+ createdAt: isoDate,
+ deleted: z.boolean().optional(),
+ deletedAt: z.string().nullable().optional(),
+ syncSequence: z.string().optional(),
+}).passthrough();
+
export const catalogSyncEnvelopeSchema = z.object({
scraps: z.array(catalogSyncScrapSchema).max(5_000).optional(),
ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),
@@ -304,5 +349,6 @@ export const catalogSyncEnvelopeSchema = z.object({
refs: z.array(catalogSyncRefSchema).max(20_000).optional(),
relations: z.array(catalogSyncRelationSchema).max(20_000).optional(),
tags: z.array(catalogSyncTagSchema).max(20_000).optional(),
+ media: z.array(catalogSyncMediaSchema).max(20_000).optional(),
portosMeta,
}).passthrough();
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
index cdf0ec6f46..41385301f3 100644
--- a/server/lib/catalogValidation.test.js
+++ b/server/lib/catalogValidation.test.js
@@ -23,6 +23,10 @@ import {
catalogExportQuerySchema,
catalogRelationLinkSchema,
RELATION_KINDS,
+ catalogMediaAttachSchema,
+ catalogMediaDetachSchema,
+ catalogPortraitSetSchema,
+ MEDIA_KINDS,
} from './catalogValidation.js';
describe('catalogValidation — ingredient types & ref kinds', () => {
@@ -383,3 +387,71 @@ describe('catalogValidation — catalogSyncEnvelopeSchema relations block', () =
})).toThrow();
});
});
+
+describe('catalogValidation — media kinds & catalogMediaAttachSchema', () => {
+ it('exposes the media kinds as a frozen list including the documented set', () => {
+ expect(Object.isFrozen(MEDIA_KINDS)).toBe(true);
+ for (const k of ['portrait', 'reference', 'audio', 'video', 'document']) {
+ expect(MEDIA_KINDS).toContain(k);
+ }
+ });
+
+ it('accepts a valid media attach body with optional role/caption', () => {
+ const out = catalogMediaAttachSchema.parse({ mediaKey: 'hero.png', kind: 'portrait', role: 'hero-shot', caption: 'angry' });
+ expect(out).toEqual({ mediaKey: 'hero.png', kind: 'portrait', role: 'hero-shot', caption: 'angry' });
+ });
+
+ it('accepts an attach body without role/caption', () => {
+ expect(() => catalogMediaAttachSchema.parse({ mediaKey: 'a.png', kind: 'reference' })).not.toThrow();
+ });
+
+ it('accepts every registered media kind', () => {
+ for (const k of MEDIA_KINDS) {
+ expect(() => catalogMediaAttachSchema.parse({ mediaKey: 'x.png', kind: k })).not.toThrow();
+ }
+ });
+
+ it('rejects an unknown media kind', () => {
+ expect(() => catalogMediaAttachSchema.parse({ mediaKey: 'x.png', kind: 'hologram' })).toThrow();
+ });
+
+ it('rejects a missing or empty mediaKey', () => {
+ expect(() => catalogMediaAttachSchema.parse({ kind: 'portrait' })).toThrow();
+ expect(() => catalogMediaAttachSchema.parse({ mediaKey: '', kind: 'portrait' })).toThrow();
+ });
+
+ it('rejects unknown keys (strict)', () => {
+ expect(() => catalogMediaAttachSchema.parse({ mediaKey: 'x.png', kind: 'portrait', bytes: 'nope' })).toThrow();
+ });
+
+ it('portrait-set body omits kind; detach body requires kind', () => {
+ expect(() => catalogPortraitSetSchema.parse({ mediaKey: 'x.png' })).not.toThrow();
+ expect(() => catalogPortraitSetSchema.parse({ mediaKey: 'x.png', kind: 'portrait' })).toThrow(); // strict: no kind
+ expect(() => catalogMediaDetachSchema.parse({ mediaKey: 'x.png', kind: 'portrait' })).not.toThrow();
+ expect(() => catalogMediaDetachSchema.parse({ mediaKey: 'x.png' })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogSyncEnvelopeSchema media block', () => {
+ it('accepts an envelope carrying a media array with tombstone + metadata fields', () => {
+ const out = catalogSyncEnvelopeSchema.parse({
+ media: [
+ { ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait', createdAt: '2026-01-01T00:00:00Z' },
+ { ingredientId: 'i1', mediaKey: 'b.png', kind: 'reference', role: 'mood', caption: 'rainy', createdAt: '2026-01-01T00:00:00Z', deleted: true, deletedAt: '2026-01-02T00:00:00Z' },
+ ],
+ });
+ expect(out.media).toHaveLength(2);
+ });
+
+ it('tolerates a forward (unknown) media kind on the wire', () => {
+ expect(() => catalogSyncEnvelopeSchema.parse({
+ media: [{ ingredientId: 'i1', mediaKey: 'a.png', kind: 'future-kind', createdAt: '2026-01-01T00:00:00Z' }],
+ })).not.toThrow();
+ });
+
+ it('requires ingredientId + mediaKey + createdAt on a media row', () => {
+ expect(() => catalogSyncEnvelopeSchema.parse({
+ media: [{ kind: 'portrait', createdAt: '2026-01-01T00:00:00Z' }],
+ })).toThrow();
+ });
+});
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index 602e626d0d..ab9ef71443 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -31,6 +31,7 @@ const CATALOG_TABLES = [
'catalog_ingredient_relations',
'catalog_tags',
'catalog_ingredient_revisions',
+ 'catalog_ingredient_media',
];
// Strip line comments + collapse whitespace so column lists compare cleanly.
diff --git a/server/lib/db.js b/server/lib/db.js
index 810b1ef837..489a9892c0 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -293,6 +293,30 @@ export async function ensureSchema() {
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_revisions_ingredient
ON catalog_ingredient_revisions (ingredient_id, created_at DESC)`,
+ // Typed media attachments — `media_key` REFERENCES the media library
+ // (data/images + history.jsonl sidecar) by key; the bytes are never copied
+ // here, so federation ships the key and the receiver matches its own
+ // library (missing → metadata-missing integrity surface). `kind` is an
+ // app-layer enum (MEDIA_KINDS in catalogTypes.js), not a DB CHECK. Soft-
+ // delete from day one so detaches tombstone + propagate. Mirrors the
+ // catalog_ingredient_media block in init-db.sql (parity is asserted by
+ // db.catalogDdlParity.test.js).
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_media (
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ media_key TEXT NOT NULL,
+ kind VARCHAR(32) NOT NULL,
+ role VARCHAR(64),
+ caption TEXT,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL,
+ PRIMARY KEY (ingredient_id, media_key, kind)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence)`,
+
`CREATE OR REPLACE FUNCTION update_catalog_ingredient_timestamp()
RETURNS TRIGGER AS $$
DECLARE
@@ -409,6 +433,27 @@ export async function ensureSchema() {
FOR EACH ROW
EXECUTE FUNCTION update_catalog_relation_sync_seq()`,
+ // Media UPDATE bumps sync_sequence on soft-delete/revival OR a mutable
+ // field (role/caption) change so a peer sees the edit/tombstone next pull.
+ // Mirrors the relation trigger but also watches the editable metadata.
+ `CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ IF NEW.deleted IS DISTINCT FROM OLD.deleted
+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at
+ OR NEW.role IS DISTINCT FROM OLD.role
+ OR NEW.caption IS DISTINCT FROM OLD.caption THEN
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));
+ END IF;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_media_sync_seq ON catalog_ingredient_media`,
+ `CREATE TRIGGER trg_catalog_media_sync_seq
+ BEFORE UPDATE ON catalog_ingredient_media
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_media_sync_seq()`,
+
// Tag UPDATE bumps sync_sequence + updated_at on a mutable-field change
// (label/description/color/parent_id) so a peer sees the edit on its next
// pull. Mirrors the scrap timestamp trigger.
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index c757bf389a..c2f63d526c 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -93,7 +93,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// TEXT[]` column is unchanged — canonical tag rows are an additive index, so
// a v5 receiver still accepts ≤v4 ingredient/scrap/ref/relation pushes; those
// envelopes simply carry no `tags` block.
- catalog: 5,
+ // v6 = `catalog_ingredient_media` join table (typed image/audio/video/doc
+ // attachments) + a new `media: [...]` block in the catalog sync envelope.
+ // Each media row ships a `media_key` REFERENCE into the receiver's own media
+ // library (data/images + history.jsonl sidecar) — never the bytes. Same
+ // gating rationale as v4/v5: a ≤v5 receiver doesn't understand the `media`
+ // block, so a v6 sender pushing to it is sender-ahead on `catalog` and gets
+ // a 412 (otherwise the older peer would silently drop every attachment). A v6
+ // receiver still accepts ≤v5 senders (sender-behind); those envelopes carry
+ // no `media` block. Media keys that don't resolve against the receiver's own
+ // library surface via the metadata-missing integrity endpoint rather than
+ // failing the apply.
+ catalog: 6,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index c85a79da1c..56a661923e 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -14,6 +14,9 @@ import {
catalogIngredientPatchSchema,
catalogIngredientLinkSchema,
catalogRelationLinkSchema,
+ catalogMediaAttachSchema,
+ catalogMediaDetachSchema,
+ catalogPortraitSetSchema,
catalogIngredientQuerySchema,
catalogTagQuerySchema,
catalogScrapCommitSchema,
@@ -27,6 +30,7 @@ import {
catalogRevisionRestoreSchema,
} from '../lib/catalogValidation.js';
import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
+import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
import { extractIngredients } from '../services/catalogExtraction.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
@@ -295,6 +299,70 @@ router.delete('/ingredients/:id/relations', asyncHandler(async (req, res) => {
res.status(204).end();
}));
+// --- Ingredient media attachments ---------------------------------------
+// `media_key` is a reference into the media library (data/images + history
+// sidecar); the catalog never stores the bytes. The attach/portrait routes
+// reject a key that doesn't resolve against the local IMAGE library with a 422
+// so a typo can't persist a permanently-broken reference. Federated keys that
+// don't resolve are tolerated (they ride in via sync) and surface on the
+// integrity endpoint instead — that's a different code path that never throws.
+//
+// Only image kinds resolve against the gallery today; audio/video/document
+// keys have no library resolver yet, so they skip the existence guard.
+const IMAGE_MEDIA_KINDS = new Set(['portrait', 'reference']);
+
+router.get('/ingredients/:id/media', asyncHandler(async (req, res) => {
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ res.json(await catalogDB.listMediaForIngredient(req.params.id));
+}));
+
+// Integrity surface: media keys on this ingredient that don't resolve against
+// the local library (typically arrived via federation before their asset did).
+router.get('/ingredients/:id/media/missing', asyncHandler(async (req, res) => {
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ res.json({ missing: await catalogDB.getMissingMediaForIngredient(req.params.id) });
+}));
+
+router.post('/ingredients/:id/media', asyncHandler(async (req, res) => {
+ validateRequest(catalogMediaAttachSchema, req.body);
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ // Only IMAGE kinds resolve against the gallery today, so only they get the
+ // existence guard — attaching an audio/video/document key (no library
+ // resolver yet) stores the reference without a 422. The integrity endpoint
+ // mirrors this scoping when reporting missing assets.
+ if (IMAGE_MEDIA_KINDS.has(req.body.kind) && !resolveImageInputPath(req.body.mediaKey)) {
+ throw new ServerError(`Media key "${req.body.mediaKey}" not found in the media library`, { status: 422 });
+ }
+ const media = await catalogDB.attachMedia(req.params.id, req.body.mediaKey, req.body.kind, {
+ role: req.body.role ?? null,
+ caption: req.body.caption ?? null,
+ });
+ res.status(201).json(media);
+}));
+
+router.post('/ingredients/:id/media/portrait', asyncHandler(async (req, res) => {
+ validateRequest(catalogPortraitSetSchema, req.body);
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ if (!resolveImageInputPath(req.body.mediaKey)) {
+ throw new ServerError(`Media key "${req.body.mediaKey}" not found in the media library`, { status: 422 });
+ }
+ const media = await catalogDB.setPortraitMedia(req.params.id, req.body.mediaKey, {
+ role: req.body.role ?? null,
+ caption: req.body.caption ?? null,
+ });
+ res.status(201).json(media);
+}));
+
+router.delete('/ingredients/:id/media', asyncHandler(async (req, res) => {
+ validateRequest(catalogMediaDetachSchema, req.body);
+ await catalogDB.detachMedia(req.params.id, req.body.mediaKey, req.body.kind);
+ res.status(204).end();
+}));
+
// Bulk-create ingredients from a markdown / CSV / JSON dump — no LLM round
// trip, unlike the scrap → extract → commit path. The whole batch commits
// or rolls back together so a malformed entry can't leave the catalog
@@ -382,10 +450,11 @@ router.post('/bulk-import', asyncHandler(async (req, res) => {
// Export one ref slice (universe/series/issue/work) as a portable bundle.
// JSON is the canonical round-trip format; markdown + YAML are convenience
-// outputs. Relations and media-refs are intentionally absent — those tables
-// don't exist yet; when they ship the export helper will include them
-// without a payload-shape break (the consumer treats unknown keys as
-// passthrough).
+// outputs. Each ingredient carries its `media` attachments (media-key
+// references, not bytes — the importer matches keys against its own library).
+// Relations are still absent (their table predates a portable shape); when
+// they ship the export helper will include them without a payload-shape break
+// (the consumer treats unknown keys as passthrough).
router.get('/export', asyncHandler(async (req, res) => {
const params = validateRequest(catalogExportQuerySchema, req.query);
const format = params.format || 'json';
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 1e1d284599..111e0f4fac 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -328,6 +328,34 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_revisions (
CREATE INDEX IF NOT EXISTS idx_catalog_ing_revisions_ingredient
ON catalog_ingredient_revisions (ingredient_id, created_at DESC);
+-- Typed media attachments for an ingredient (a generated portrait, a mood /
+-- reference image, a recorded voice memo, …). `media_key` is a REFERENCE into
+-- this install's media library (data/images + the history.jsonl sidecar /
+-- generated assets) — the bytes are NEVER duplicated here, so federation ships
+-- the key and the receiver matches it against its OWN library (a missing match
+-- surfaces via the metadata-missing integrity endpoint rather than failing the
+-- sync). `kind` is an app-layer enum (MEDIA_KINDS in catalogTypes.js), not a DB
+-- CHECK, so a newer peer's extra kind stores harmlessly. Soft-delete
+-- (deleted/deleted_at) from day one so detaches tombstone + propagate to peers
+-- — same lesson as the refs/relations tables. PK is (ingredient_id, media_key,
+-- kind): the same asset can ride as both a portrait and a reference, but not
+-- twice as the same kind.
+CREATE TABLE IF NOT EXISTS catalog_ingredient_media (
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ media_key TEXT NOT NULL, -- filename/key into the media library; not an FK
+ kind VARCHAR(32) NOT NULL, -- portrait|reference|audio|video|document (MEDIA_KINDS)
+ role VARCHAR(64), -- optional free label (e.g. 'hero-shot', 'angry')
+ caption TEXT,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so detaches propagate to peers
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL,
+ PRIMARY KEY (ingredient_id, media_key, kind)
+);
+CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id);
+CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key);
+CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence);
+
-- Auto-update updated_at and bump sync_sequence on content/metadata changes.
-- Mirrors update_memory_timestamp's pattern: skip the bump on no-content-change
-- so cosmetic touches don't trigger sync. Respects explicit updated_at (used by
@@ -461,6 +489,29 @@ CREATE TRIGGER trg_catalog_relation_sync_seq
FOR EACH ROW
EXECUTE FUNCTION update_catalog_relation_sync_seq();
+-- Media UPDATE bumps sync_sequence when a soft-delete/revival OR a mutable
+-- field (role/caption) changes, so peers receive the edit (or the tombstone)
+-- on their next pull. Unlike refs/relations, media rows carry editable
+-- metadata, so the change-detector also watches role + caption.
+CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF NEW.deleted IS DISTINCT FROM OLD.deleted
+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at
+ OR NEW.role IS DISTINCT FROM OLD.role
+ OR NEW.caption IS DISTINCT FROM OLD.caption THEN
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS trg_catalog_media_sync_seq ON catalog_ingredient_media;
+CREATE TRIGGER trg_catalog_media_sync_seq
+ BEFORE UPDATE ON catalog_ingredient_media
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_media_sync_seq();
+
-- Tag UPDATE bumps sync_sequence + updated_at when a mutable field changes
-- (label/description/color/parent_id) so peers receive the edit on their next
-- pull. Respects an explicit updated_at (the sync apply path preserves the
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 6dfdb337d7..858eb2bb59 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -19,6 +19,7 @@ import {
tagIdForKey,
defaultTagsForType,
} from '../lib/catalogTypes.js';
+import { resolveImageInputPath } from '../lib/fileUtils.js';
import { getInstanceId } from './instances.js';
function newIngredientId(type) {
@@ -113,6 +114,21 @@ function rowToRelation(row) {
};
}
+function rowToMedia(row) {
+ if (!row) return null;
+ return {
+ ingredientId: row.ingredient_id,
+ mediaKey: row.media_key,
+ kind: row.kind,
+ role: row.role ?? null,
+ caption: row.caption ?? null,
+ createdAt: row.created_at.toISOString(),
+ deleted: !!row.deleted,
+ deletedAt: row.deleted_at?.toISOString() ?? null,
+ syncSequence: String(row.sync_sequence),
+ };
+}
+
function rowToSource(row) {
if (!row) return null;
return {
@@ -753,6 +769,139 @@ export async function upsertRelationFromPeer(rel) {
}
+// --- Ingredient media attachments ----------------------------------------
+// Typed references (portrait/reference/audio/video/document) into the install's
+// media library. `media_key` is a key into the library (data/images + the
+// history.jsonl sidecar) — never duplicated bytes. Soft-deleted on detach so
+// peers receive the tombstone; ON CONFLICT DO UPDATE revives a detached row and
+// updates its role/caption (the trg_catalog_media_sync_seq trigger only bumps
+// sync_sequence when one of those actually changes, so a no-op replay stays
+// silent).
+
+export async function attachMedia(ingredientId, mediaKey, kind, { role = null, caption = null } = {}) {
+ const result = await query(
+ `INSERT INTO catalog_ingredient_media (ingredient_id, media_key, kind, role, caption)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
+ SET deleted = false, deleted_at = NULL,
+ role = EXCLUDED.role, caption = EXCLUDED.caption
+ RETURNING *`,
+ [ingredientId, mediaKey, kind, role, caption],
+ );
+ return rowToMedia(result.rows[0]);
+}
+
+export async function detachMedia(ingredientId, mediaKey, kind) {
+ // Soft-delete (mirrors unlinkIngredientRelation): keep the row as a tombstone
+ // so the sync_sequence bump propagates the detach to peers. `AND deleted =
+ // false` keeps a re-detach from re-bumping the sequence needlessly.
+ await query(
+ `UPDATE catalog_ingredient_media
+ SET deleted = true, deleted_at = NOW()
+ WHERE ingredient_id = $1 AND media_key = $2 AND kind = $3
+ AND deleted = false`,
+ [ingredientId, mediaKey, kind],
+ );
+}
+
+// Set THE portrait for an ingredient: attach `mediaKey` as kind 'portrait' and
+// demote any other live portrait. One active portrait per ingredient — the UI
+// renders it as the ingredient's avatar. Serialized as two statements; the
+// single-user trust model means no competing writer can interleave.
+export async function setPortraitMedia(ingredientId, mediaKey, { role = null, caption = null } = {}) {
+ await query(
+ `UPDATE catalog_ingredient_media
+ SET deleted = true, deleted_at = NOW()
+ WHERE ingredient_id = $1 AND kind = 'portrait'
+ AND media_key <> $2 AND deleted = false`,
+ [ingredientId, mediaKey],
+ );
+ return attachMedia(ingredientId, mediaKey, 'portrait', { role, caption });
+}
+
+// Live (non-tombstoned) media rows for an ingredient's detail "Media" panel,
+// newest first. Portrait(s) first so the avatar is easy to pluck off the head.
+export async function listMediaForIngredient(ingredientId) {
+ const result = await query(
+ `SELECT * FROM catalog_ingredient_media
+ WHERE ingredient_id = $1 AND deleted = false
+ ORDER BY (kind = 'portrait') DESC, created_at DESC`,
+ [ingredientId],
+ );
+ return result.rows.map(rowToMedia);
+}
+
+// The media kinds whose `media_key` resolves against the image library today.
+// Non-image kinds (audio/video/document) have no library resolver yet, so the
+// integrity check skips them rather than reporting a false "missing" — when an
+// audio/video library lands, add its resolver and widen this set.
+const RESOLVABLE_MEDIA_KINDS = new Set(['portrait', 'reference']);
+
+// Integrity surface: which of an ingredient's live IMAGE media_keys DON'T
+// resolve against this install's media library. Federation ships keys, not
+// bytes, so a received attachment whose asset never arrived (or was pruned)
+// shows up here — the detail page surfaces it as `metadata-missing` rather than
+// rendering a broken <img>. `resolveImageInputPath` returns null when the key
+// isn't under any approved image root. Non-image kinds are excluded (no
+// resolver yet). Returns the list of missing `{ mediaKey, kind }`.
+export async function getMissingMediaForIngredient(ingredientId) {
+ const rows = await listMediaForIngredient(ingredientId);
+ return rows
+ .filter((m) => RESOLVABLE_MEDIA_KINDS.has(m.kind) && !resolveImageInputPath(m.mediaKey))
+ .map((m) => ({ mediaKey: m.mediaKey, kind: m.kind }));
+}
+
+export async function getMediaChangesSince(since = '0', limit = 100) {
+ const result = await query(
+ `SELECT * FROM catalog_ingredient_media WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
+ [since, limit + 1],
+ );
+ const hasMore = result.rows.length > limit;
+ const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
+ return { items: rows.map(rowToMedia), hasMore };
+}
+
+export async function upsertMediaFromPeer(media) {
+ // Mirrors upsertRefFromPeer's mixed-version handling: a peer that predates
+ // the media feature never emits these rows, so there's no pre-tombstone
+ // shape to defend against. We still treat "tombstone keys absent" as "peer
+ // has no opinion" so a forked peer that omits them preserves local state on
+ // conflict. On INSERT a tombstone-less row defaults to deleted=false, which
+ // is correct (brand-new locally, peer believes it active). role/caption are
+ // always adopted from the peer (LWW is implicit — last writer's envelope wins
+ // for these tuple-unique rows, same as refs).
+ const hasTombstoneFields =
+ Object.prototype.hasOwnProperty.call(media, 'deleted') ||
+ Object.prototype.hasOwnProperty.call(media, 'deletedAt');
+ if (hasTombstoneFields) {
+ await query(
+ `INSERT INTO catalog_ingredient_media
+ (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
+ SET role = EXCLUDED.role,
+ caption = EXCLUDED.caption,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ media.ingredientId, media.mediaKey, media.kind,
+ media.role ?? null, media.caption ?? null, media.createdAt,
+ !!media.deleted, media.deletedAt || null,
+ ],
+ );
+ } else {
+ await query(
+ `INSERT INTO catalog_ingredient_media
+ (ingredient_id, media_key, kind, role, caption, created_at)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
+ SET role = EXCLUDED.role, caption = EXCLUDED.caption`,
+ [media.ingredientId, media.mediaKey, media.kind, media.role ?? null, media.caption ?? null, media.createdAt],
+ );
+ }
+}
+
+
// --- Tag taxonomy --------------------------------------------------------
// `catalog_tags` is the canonical index over the freeform
// `catalog_ingredients.tags TEXT[]` column. `normalizeTags` maps user input
@@ -919,7 +1068,8 @@ export async function getMaxSequences() {
COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_sources), 0)::text AS sources,
COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_refs), 0)::text AS refs,
COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_relations), 0)::text AS relations,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_tags), 0)::text AS tags
+ COALESCE((SELECT MAX(sync_sequence) FROM catalog_tags), 0)::text AS tags,
+ COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_media), 0)::text AS media
`);
return result.rows[0];
}
@@ -1126,20 +1276,21 @@ export async function listScrapsForIngredient(ingredientId) {
/**
* Build an export bundle for one ref (universe/series/issue/work).
- * Hydrates each ingredient + its scraps + ref links. Relations and media
- * refs are intentionally omitted — the underlying tables (catalog_ingredient_relations,
- * catalog_ingredient_media) don't exist yet (see PLAN items
- * `[catalog-ingredient-relations]` / `[catalog-ingredient-media-refs]`).
- * When they land, extend this helper to hydrate them too.
+ * Hydrates each ingredient + its scraps + ref links + media attachments. The
+ * media bundle carries `media_key` REFERENCES (not bytes) — a receiving peer
+ * matches each key against its own library and surfaces unresolved ones via
+ * the metadata-missing integrity surface. Relations are still omitted here
+ * (see `[catalog-ingredient-relations]`); when they land, extend this helper.
*/
export async function exportSliceForRef(refKind, refId) {
const rows = await listIngredientsForRef(refKind, refId);
- // Hydrate scraps + refs in parallel per ingredient. Small N (one slice
- // is typically <100 ingredients); a per-row round-trip is fine.
+ // Hydrate scraps + refs + media in parallel per ingredient. Small N (one
+ // slice is typically <100 ingredients); a per-row round-trip is fine.
const ingredients = await Promise.all(rows.map(async ({ ingredient, role }) => {
- const [scraps, refs] = await Promise.all([
+ const [scraps, refs, media] = await Promise.all([
listScrapsForIngredient(ingredient.id),
listRefsForIngredient(ingredient.id),
+ listMediaForIngredient(ingredient.id),
]);
const { embedding: _embedding, ...rest } = ingredient;
return {
@@ -1150,6 +1301,7 @@ export async function exportSliceForRef(refKind, refId) {
roleForExportedRef: role,
refs,
scraps,
+ media,
};
}));
return {
diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.js
new file mode 100644
index 0000000000..1b10a0ea85
--- /dev/null
+++ b/server/services/catalogDBMedia.test.js
@@ -0,0 +1,152 @@
+/**
+ * Unit tests for the catalog DB layer's media-attachment functions:
+ * - attachMedia upserts a typed (ingredient_id, media_key, kind) row and
+ * revives a soft-deleted row on conflict;
+ * - detachMedia soft-deletes (tombstone) rather than hard-DELETE;
+ * - setPortraitMedia demotes any other live portrait, then attaches;
+ * - getMissingMediaForIngredient reports only keys that don't resolve against
+ * the local media library (the metadata-missing integrity surface);
+ * - upsertMediaFromPeer distinguishes "tombstone fields present" from absent.
+ *
+ * Postgres is mocked — we capture the SQL/params and assert on them, so the
+ * suite runs without a live database. `resolveImageInputPath` is mocked so the
+ * integrity helper's library-resolution branch is deterministic.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const calls = [];
+
+vi.mock('../lib/db.js', () => ({
+ query: vi.fn(async (sql, params) => {
+ calls.push({ sql: sql.replace(/\s+/g, ' ').trim(), params });
+ // Echo a media row back so rowToMedia works for the RETURNING * paths.
+ return {
+ rows: [{
+ ingredient_id: params?.[0] ?? 'i1',
+ media_key: params?.[1] ?? 'k.png',
+ kind: params?.[2] ?? 'portrait',
+ role: null,
+ caption: null,
+ created_at: new Date('2026-01-01T00:00:00Z'),
+ deleted: false,
+ deleted_at: null,
+ sync_sequence: 1,
+ }],
+ };
+ }),
+ withTransaction: vi.fn(),
+ pgvectorToArray: vi.fn(),
+ arrayToPgvector: vi.fn(),
+}));
+
+// resolveImageInputPath: 'present.png' resolves; everything else is missing.
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ resolveImageInputPath: vi.fn((key) => (key === 'present.png' ? `/data/images/${key}` : null)),
+ };
+});
+
+// instances.getInstanceId is pulled in transitively by catalogDB — stub it.
+vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));
+
+const catalogDB = await import('./catalogDB.js');
+
+beforeEach(() => {
+ calls.length = 0;
+ vi.clearAllMocks();
+});
+
+describe('attachMedia', () => {
+ it('upserts the tuple and revives a soft-deleted row on conflict', async () => {
+ await catalogDB.attachMedia('i1', 'hero.png', 'portrait', { role: 'hero', caption: 'cap' });
+ const { sql, params } = calls[0];
+ expect(sql).toMatch(/INSERT INTO catalog_ingredient_media/i);
+ expect(sql).toMatch(/ON CONFLICT \(ingredient_id, media_key, kind\) DO UPDATE/i);
+ expect(sql).toMatch(/deleted = false, deleted_at = NULL/i);
+ expect(params).toEqual(['i1', 'hero.png', 'portrait', 'hero', 'cap']);
+ });
+
+ it('defaults role/caption to null when omitted', async () => {
+ await catalogDB.attachMedia('i1', 'hero.png', 'reference');
+ expect(calls[0].params).toEqual(['i1', 'hero.png', 'reference', null, null]);
+ });
+});
+
+describe('detachMedia', () => {
+ it('soft-deletes (tombstone) — never a hard DELETE', async () => {
+ await catalogDB.detachMedia('i1', 'hero.png', 'portrait');
+ const { sql, params } = calls[0];
+ expect(sql).toMatch(/UPDATE catalog_ingredient_media SET deleted = true/i);
+ expect(sql).not.toMatch(/DELETE FROM/i);
+ expect(sql).toMatch(/AND deleted = false/i); // re-detach stays a no-op
+ expect(params).toEqual(['i1', 'hero.png', 'portrait']);
+ });
+});
+
+describe('setPortraitMedia', () => {
+ it('demotes other live portraits then attaches the new one', async () => {
+ await catalogDB.setPortraitMedia('i1', 'new.png', { caption: 'now' });
+ // First statement: demote other portraits.
+ expect(calls[0].sql).toMatch(/UPDATE catalog_ingredient_media SET deleted = true/i);
+ expect(calls[0].sql).toMatch(/kind = 'portrait'/i);
+ expect(calls[0].sql).toMatch(/media_key <> \$2/);
+ expect(calls[0].params).toEqual(['i1', 'new.png']);
+ // Second statement: attach as portrait.
+ expect(calls[1].sql).toMatch(/INSERT INTO catalog_ingredient_media/i);
+ expect(calls[1].params).toEqual(['i1', 'new.png', 'portrait', null, 'now']);
+ });
+});
+
+describe('getMissingMediaForIngredient', () => {
+ it('returns only the IMAGE keys that do not resolve against the local library', async () => {
+ // listMediaForIngredient runs the SELECT; override the mock to return a mix.
+ const db = await import('../lib/db.js');
+ db.query.mockResolvedValueOnce({
+ rows: [
+ { ingredient_id: 'i1', media_key: 'present.png', kind: 'portrait', role: null, caption: null, created_at: new Date(), deleted: false, deleted_at: null, sync_sequence: 1 },
+ { ingredient_id: 'i1', media_key: 'gone.png', kind: 'reference', role: null, caption: null, created_at: new Date(), deleted: false, deleted_at: null, sync_sequence: 2 },
+ // A non-image kind never has a library resolver yet — it must NOT be
+ // reported missing just because resolveImageInputPath returns null.
+ { ingredient_id: 'i1', media_key: 'memo.wav', kind: 'audio', role: null, caption: null, created_at: new Date(), deleted: false, deleted_at: null, sync_sequence: 3 },
+ ],
+ });
+ const missing = await catalogDB.getMissingMediaForIngredient('i1');
+ expect(missing).toEqual([{ mediaKey: 'gone.png', kind: 'reference' }]);
+ });
+});
+
+describe('upsertMediaFromPeer', () => {
+ it('uses the tombstone-aware INSERT when deleted/deletedAt are present', async () => {
+ await catalogDB.upsertMediaFromPeer({
+ ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait',
+ role: 'r', caption: 'c', createdAt: 't', deleted: true, deletedAt: 't2',
+ });
+ const { sql, params } = calls[0];
+ expect(sql).toMatch(/deleted, deleted_at/i);
+ expect(sql).toMatch(/SET role = EXCLUDED.role, caption = EXCLUDED.caption, deleted = EXCLUDED.deleted/i);
+ expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', true, 't2']);
+ });
+
+ it('uses the tombstone-less INSERT (preserve local state) when the keys are absent', async () => {
+ await catalogDB.upsertMediaFromPeer({
+ ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait', createdAt: 't',
+ });
+ const { sql, params } = calls[0];
+ expect(sql).not.toMatch(/deleted = EXCLUDED.deleted/i);
+ expect(sql).toMatch(/SET role = EXCLUDED.role, caption = EXCLUDED.caption/i);
+ expect(params).toEqual(['i1', 'a.png', 'portrait', null, null, 't']);
+ });
+});
+
+describe('getMaxSequences includes the media cursor', () => {
+ it('selects MAX(sync_sequence) from catalog_ingredient_media AS media', async () => {
+ const db = await import('../lib/db.js');
+ db.query.mockResolvedValueOnce({ rows: [{ media: '0' }] });
+ await catalogDB.getMaxSequences();
+ const sql = db.query.mock.calls.at(-1)[0].replace(/\s+/g, ' ');
+ expect(sql).toMatch(/catalog_ingredient_media\), 0\)::text AS media/i);
+ });
+});
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 2706892e7b..a9da103d66 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -2,13 +2,16 @@
* Catalog Federation Sync Service
*
* Peer-to-peer sync for the Creative Ingredients Catalog. Mirrors
- * server/services/memorySync.js but the envelope carries six kinds
- * (scraps, ingredients, sources, refs, relations, tags) because the catalog is
- * a multi-table relational store, not a single flat row set.
+ * server/services/memorySync.js but the envelope carries seven kinds
+ * (scraps, ingredients, sources, refs, relations, tags, media) because the
+ * catalog is a multi-table relational store, not a single flat row set. The
+ * `media` rows carry a `media_key` REFERENCE into the receiver's own library
+ * (never the bytes); an unresolved key surfaces via the metadata-missing
+ * integrity endpoint rather than failing the apply.
*
* Pull protocol:
- * GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&...&since[tags]=F&limit=100
- * → { scraps[], ingredients[], sources[], refs[], relations[], tags[], maxSequences, hasMore }
+ * GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&...&since[media]=G&limit=100
+ * → { scraps[], ingredients[], sources[], refs[], relations[], tags[], media[], maxSequences, hasMore }
*
* The BIGSERIAL `sync_sequence` columns are INDEPENDENT — a row at
* sources.sync_sequence=50 isn't comparable to ingredients.sync_sequence=50.
@@ -32,6 +35,7 @@ import {
getRefChangesSince,
getRelationChangesSince,
getTagChangesSince,
+ getMediaChangesSince,
getMaxSequences,
upsertScrapFromPeer,
upsertIngredientFromPeer,
@@ -39,10 +43,11 @@ import {
upsertRefFromPeer,
upsertRelationFromPeer,
upsertTagFromPeer,
+ upsertMediaFromPeer,
} from './catalogDB.js';
import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
-const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags'];
+const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];
// Normalize `since` (scalar string OR per-kind object) into a `{ scraps,
// ingredients, sources, refs }` cursor map. Scalar form is uniform across
@@ -62,18 +67,19 @@ function normalizeCursors(since) {
export async function getChangesSince(since = '0', limit = 100) {
const cursors = normalizeCursors(since);
- const [scraps, ingredients, sources, refs, relations, tags] = await Promise.all([
+ const [scraps, ingredients, sources, refs, relations, tags, media] = await Promise.all([
getScrapChangesSince(cursors.scraps, limit),
getIngredientChangesSince(cursors.ingredients, limit),
getSourceChangesSince(cursors.sources, limit),
getRefChangesSince(cursors.refs, limit),
getRelationChangesSince(cursors.relations, limit),
getTagChangesSince(cursors.tags, limit),
+ getMediaChangesSince(cursors.media, limit),
]);
const hasMore =
scraps.hasMore || ingredients.hasMore || sources.hasMore || refs.hasMore ||
- relations.hasMore || tags.hasMore;
+ relations.hasMore || tags.hasMore || media.hasMore;
// Per-kind cursor advance — fall back to the inbound cursor so the next pull
// doesn't move backward on a quiet kind.
@@ -87,6 +93,7 @@ export async function getChangesSince(since = '0', limit = 100) {
refs: refs.items,
relations: relations.items,
tags: tags.items,
+ media: media.items,
maxSequences: {
scraps: maxOf(scraps.items, cursors.scraps),
ingredients: maxOf(ingredients.items, cursors.ingredients),
@@ -94,6 +101,7 @@ export async function getChangesSince(since = '0', limit = 100) {
refs: maxOf(refs.items, cursors.refs),
relations: maxOf(relations.items, cursors.relations),
tags: maxOf(tags.items, cursors.tags),
+ media: maxOf(media.items, cursors.media),
},
hasMore,
};
@@ -127,6 +135,7 @@ export async function applyRemoteChanges(envelope = {}) {
refs: { applied: 0, failed: 0 },
relations: { applied: 0, failed: 0 },
tags: { inserted: 0, updated: 0, skipped: 0, failed: 0 },
+ media: { applied: 0, failed: 0 },
errors: [],
};
@@ -211,6 +220,22 @@ export async function applyRemoteChanges(envelope = {}) {
}
}
+ // Media rows FK ingredient_id to catalog_ingredients, so they land after the
+ // ingredient upserts. The `media_key` is a REFERENCE into the receiver's own
+ // library — we store the key regardless of whether the asset is present
+ // locally; a missing asset surfaces later via the metadata-missing integrity
+ // endpoint, NOT as an apply failure (otherwise a slow asset transfer would
+ // drop the attachment metadata entirely).
+ for (const media of envelope.media || []) {
+ try {
+ await upsertMediaFromPeer(media);
+ stats.media.applied++;
+ } catch (err) {
+ stats.media.failed++;
+ recordFailure('media', `${media?.ingredientId}/${media?.kind}/${media?.mediaKey}`, err);
+ }
+ }
+
return stats;
}
diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.js
index ffa4b5f5ec..2d244d12fb 100644
--- a/server/services/catalogSync.test.js
+++ b/server/services/catalogSync.test.js
@@ -19,6 +19,7 @@ vi.mock('./catalogDB.js', () => ({
getRefChangesSince: vi.fn(),
getRelationChangesSince: vi.fn(),
getTagChangesSince: vi.fn(),
+ getMediaChangesSince: vi.fn(),
getMaxSequences: vi.fn(),
upsertScrapFromPeer: vi.fn(),
upsertIngredientFromPeer: vi.fn(),
@@ -26,6 +27,7 @@ vi.mock('./catalogDB.js', () => ({
upsertRefFromPeer: vi.fn(),
upsertRelationFromPeer: vi.fn(),
upsertTagFromPeer: vi.fn(),
+ upsertMediaFromPeer: vi.fn(),
}));
vi.mock('../lib/schemaVersions.js', async () => {
@@ -54,6 +56,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {
catalogDB.upsertRefFromPeer.mockResolvedValueOnce(undefined);
catalogDB.upsertRelationFromPeer.mockResolvedValueOnce(undefined);
catalogDB.upsertTagFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ catalogDB.upsertMediaFromPeer.mockResolvedValueOnce(undefined);
const stats = await applyRemoteChanges({
scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],
@@ -65,6 +68,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {
refs: [{ ingredientId: 'i1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: 't' }],
relations: [{ fromId: 'i1', toId: 'i2', kind: 'lives-in', createdAt: 't' }],
tags: [{ id: 'cat-tag-noir', label: 'Noir', createdAt: 't', updatedAt: 't' }],
+ media: [{ ingredientId: 'i1', mediaKey: 'hero.png', kind: 'portrait', createdAt: 't' }],
});
expect(stats.scraps.inserted).toBe(1);
@@ -74,6 +78,10 @@ describe('applyRemoteChanges — dispatch + stats', () => {
expect(stats.refs.applied).toBe(1);
expect(stats.relations.applied).toBe(1);
expect(stats.tags.inserted).toBe(1);
+ expect(stats.media.applied).toBe(1);
+ expect(catalogDB.upsertMediaFromPeer).toHaveBeenCalledWith(
+ expect.objectContaining({ ingredientId: 'i1', mediaKey: 'hero.png', kind: 'portrait' }),
+ );
expect(stats.errors).toHaveLength(0);
});
@@ -209,9 +217,10 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {
catalogDB.getRefChangesSince.mockResolvedValue({ items: [], hasMore: false });
catalogDB.getRelationChangesSince.mockResolvedValue({ items: [], hasMore: false });
catalogDB.getTagChangesSince.mockResolvedValue({ items: [], hasMore: false });
+ catalogDB.getMediaChangesSince.mockResolvedValue({ items: [], hasMore: false });
});
- it('accepts a scalar since and applies it uniformly to all six kinds', async () => {
+ it('accepts a scalar since and applies it uniformly to all seven kinds', async () => {
await getChangesSince('42', 100);
expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('42', 100);
expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('42', 100);
@@ -219,26 +228,29 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {
expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('42', 100);
expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('42', 100);
expect(catalogDB.getTagChangesSince).toHaveBeenCalledWith('42', 100);
+ expect(catalogDB.getMediaChangesSince).toHaveBeenCalledWith('42', 100);
});
it('accepts a per-kind cursor object', async () => {
- await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20', relations: '25', tags: '30' }, 100);
+ await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20', relations: '25', tags: '30', media: '35' }, 100);
expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('5', 100);
expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('10', 100);
expect(catalogDB.getSourceChangesSince).toHaveBeenCalledWith('15', 100);
expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('20', 100);
expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('25', 100);
expect(catalogDB.getTagChangesSince).toHaveBeenCalledWith('30', 100);
+ expect(catalogDB.getMediaChangesSince).toHaveBeenCalledWith('35', 100);
});
it('rejects non-numeric cursor values, falling back to "0"', async () => {
- await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined, relations: 'x', tags: 'y' }, 100);
+ await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined, relations: 'x', tags: 'y', media: 'z' }, 100);
expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('5', 100);
expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('0', 100);
expect(catalogDB.getSourceChangesSince).toHaveBeenCalledWith('0', 100);
expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('0', 100);
expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('0', 100);
expect(catalogDB.getTagChangesSince).toHaveBeenCalledWith('0', 100);
+ expect(catalogDB.getMediaChangesSince).toHaveBeenCalledWith('0', 100);
});
it('per-kind maxSequence falls back to the inbound cursor on quiet kinds', async () => {
@@ -248,7 +260,7 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {
});
catalogDB.getIngredientChangesSince.mockResolvedValue({ items: [], hasMore: false });
- const res = await getChangesSince({ scraps: '50', ingredients: '99', sources: '88', refs: '77', relations: '66', tags: '55' }, 100);
+ const res = await getChangesSince({ scraps: '50', ingredients: '99', sources: '88', refs: '77', relations: '66', tags: '55', media: '44' }, 100);
// Quiet kinds reflect the inbound cursor — NOT 0 — so the next pull
// doesn't move backward.
@@ -258,6 +270,21 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {
expect(res.maxSequences.refs).toBe('77');
expect(res.maxSequences.relations).toBe('66');
expect(res.maxSequences.tags).toBe('55');
+ expect(res.maxSequences.media).toBe('44');
+ });
+
+ it('advances the media cursor to the last media row + hasMore when only media reports more', async () => {
+ catalogDB.getMediaChangesSince.mockResolvedValue({
+ items: [
+ { ingredientId: 'i1', mediaKey: 'a.png', kind: 'portrait', syncSequence: '3' },
+ { ingredientId: 'i1', mediaKey: 'b.png', kind: 'reference', syncSequence: '4' },
+ ],
+ hasMore: true,
+ });
+ const res = await getChangesSince({ scraps: '0', ingredients: '0', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' }, 100);
+ expect(res.media).toHaveLength(2);
+ expect(res.maxSequences.media).toBe('4');
+ expect(res.hasMore).toBe(true);
});
it('advances the tags cursor to the last tag row + hasMore when only tags report more', async () => {