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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add catalog_ingredient_relations table for ingredient↔ingredient graph edges
[._.]/ Adam Eivy2fb1079d0027
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cb9ad5639a..16a88bb2c6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@## Added+- **[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.- **[catalog-pipeline-series-cast] "Cast (from Catalog)" panel on Series, Issue, and Writers Room pages.** A new reusable panel surfaces every catalog ingredient linked to the active series / issue / work bible — drawn from the existing `catalog_ingredient_refs` table — and lets you attach more via the existing Ingredient Picker or unlink with a click. Series records carry no embedded `characters[]` array, so the cast is purely additive and replicates through the existing catalog sync. The panel lives in the Series bible sidebar above "Canon", at the top of the active stage scroll on Issue (visible across every stage tab), and above the work editor in Writers Room when a work is selected.- **[catalog-bulk-import] Bulk-ingest endpoint for the Catalog.** A new "Bulk Import" panel on `/catalog/ingest` accepts JSON, CSV (`type,name,description,tags` header), or simple markdown (`## <Type>: <Name>` headings with paragraph body and optional `tags:` line) and creates ingredients directly — no per-row review screen. Each row is re-validated against the same Zod schema the single-create endpoint uses, so one bad row rolls back the entire batch; vector embeddings run in parallel before the transaction (same as the scrap-commit path), so bulk-imported rows are search-ready immediately rather than waiting for the embeddings backfill. `POST /api/catalog/bulk-import` is Zod-validated (2 MB payload cap), stamps optional `defaults.tags` plus an optional `universe`/`series`/`work`/`issue` ref onto every row in the same transaction, and surfaces parser warnings (e.g. `## Plce: …` typos in markdown that don't match a known type) in the response so users notice typos that would otherwise be silently skipped.- **[catalog-export-bundle] Export a catalog slice as a portable bundle.** `GET /api/catalog/export?refKind=universe|series|issue|work&refId=…&format=json|markdown|yaml` walks the ref table for the target, hydrates each ingredient + its scraps + ref-links, and returns an `attachment` bundle. Pairs with bulk import for round-trip portability (export → edit → re-import) — useful for sharing a universe's cast outside peer-sync or seeding a fresh install from a community pack. Relations and media-ref hydration ship with their own PLAN items.diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.jsindex 46cc9a45fc..6e796e2584 100644--- a/client/src/lib/catalogTypes.js+++ b/client/src/lib/catalogTypes.js@@ -101,6 +101,32 @@ export const CATALOG_TYPES = Object.freeze([},]);+/**+ * Catalog ingredient↔ingredient RELATION kinds — client mirror of+ * `server/lib/catalogTypes.js` RELATION_KINDS. Drives the "Relations" panel+ * picker on the ingredient detail page. `label` is the from→to direction;+ * `inverseLabel` renders the same stored edge from the `to` side.+ *+ * Drift is asserted by `client/src/lib/catalogTypes.test.js` against the server+ * registry — change one side, change the other.+ */+export const RELATION_KINDS = Object.freeze([+ { id: 'appears-in', label: 'Appears in', inverseLabel: 'Features' },+ { id: 'lives-in', label: 'Lives in', inverseLabel: 'Home of' },+ { id: 'created-by', label: 'Created by', inverseLabel: 'Creator of' },+ { id: 'parent-of', label: 'Parent of', inverseLabel: 'Child of' },+ { id: 'variant-of', label: 'Variant of', inverseLabel: 'Has variant' },+ { id: 'references', label: 'References', inverseLabel: 'Referenced by' },+ { id: 'related-to', label: 'Related to', inverseLabel: 'Related to' },+]);++const RELATION_BY_ID = Object.freeze(Object.fromEntries(RELATION_KINDS.map((r) => [r.id, r])));++/** Look up a relation-kind entry by id. Returns `undefined` for unknown ids. */+export function getRelationKind(id) {+ return RELATION_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.jsxindex 287024d017..c1bd53e2c9 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -7,14 +7,18 @@import { useEffect, useState } from 'react';import { useNavigate, useParams, Link } from 'react-router-dom';-import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink } from 'lucide-react';+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X } from 'lucide-react';import toast from '../components/ui/Toast';import {getCatalogIngredient,updateCatalogIngredient,deleteCatalogIngredient,+ listCatalogIngredientRelations,+ linkCatalogIngredientRelation,+ unlinkCatalogIngredientRelation,} from '../services/apiCatalog';-import { getCatalogType, CATALOG_BADGE_BY_ID } from '../lib/catalogTypes';+import IngredientPicker from '../components/IngredientPicker';+import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';// Per-type editor field list + badge color now come from the shared registry// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`@@ -52,6 +56,10 @@ export default function CatalogIngredient() {const [payload, setPayload] = useState({});const [saving, setSaving] = useState(false);const [armedDelete, setArmedDelete] = useState(false);+ // { outbound: [...], inbound: [...] } — relations are loaded separately from+ // the ingredient record so the panel can refresh independently after add/+ // remove without re-fetching the whole detail payload.+ const [relations, setRelations] = useState({ outbound: [], inbound: [] });useEffect(() => {let cancelled = false;@@ -78,6 +86,58 @@ export default function CatalogIngredient() {return () => { cancelled = true; };}, [id, navigate]);+ useEffect(() => {+ let cancelled = false;+ listCatalogIngredientRelations(id, { silent: true })+ .then((data) => {+ if (cancelled) return;+ setRelations({+ outbound: Array.isArray(data?.outbound) ? data.outbound : [],+ inbound: Array.isArray(data?.inbound) ? data.inbound : [],+ });+ })+ .catch(() => { if (!cancelled) setRelations({ outbound: [], inbound: [] }); });+ return () => { cancelled = true; };+ }, [id]);++ // Add an outbound edge (this ingredient → picked target). Optimistically+ // appends to local state so the panel updates without a refetch.+ const handleAddRelation = async (target, kind) => {+ if (!record || !target?.id) return;+ if (target.id === record.id) { toast.error('Cannot relate an ingredient to itself'); return; }+ const ok = await linkCatalogIngredientRelation(record.id, { toId: target.id, kind }, { silent: true })+ .then(() => true)+ .catch((err) => { toast.error(err?.message || 'Failed to add relation'); return false; });+ if (!ok) return;+ setRelations((prev) => {+ const exists = prev.outbound.some((r) => r.toId === target.id && r.kind === kind);+ if (exists) return prev;+ return {+ ...prev,+ outbound: [...prev.outbound, {+ fromId: record.id, toId: target.id, kind,+ createdAt: new Date().toISOString(),+ other: { id: target.id, name: target.name, type: target.type },+ }],+ };+ });+ toast.success('Relation added');+ };++ // Remove an outbound edge. Inbound edges are owned by the OTHER ingredient,+ // so the panel only deletes outbound ones (filter is by toId + kind).+ const handleRemoveRelation = async (toId, kind) => {+ if (!record) return;+ const ok = await unlinkCatalogIngredientRelation(record.id, { toId, kind }, { silent: true })+ .then(() => true)+ .catch((err) => { toast.error(err?.message || 'Failed to remove relation'); return false; });+ if (!ok) return;+ setRelations((prev) => ({+ ...prev,+ outbound: prev.outbound.filter((r) => !(r.toId === toId && r.kind === kind)),+ }));+ };+const handleSave = async () => {if (!record) return;const trimmedName = name.trim();@@ -218,11 +278,107 @@ export default function CatalogIngredient() {<SourcesPanel sources={record.sources} /><RefsPanel refsByKind={refsByKind} /></div>++ <RelationsPanel+ record={record}+ relations={relations}+ onAdd={handleAddRelation}+ onRemove={handleRemoveRelation}+ /></div></section>);}+// "Relations" panel — ingredient↔ingredient edges. Outbound edges (this+// ingredient → other) are user-editable here; inbound edges (other → this+// ingredient) are read-only because the owning ingredient is the other end.+function RelationsPanel({ record, relations, onAdd, onRemove }) {+ const [pickerOpen, setPickerOpen] = useState(false);+ const [kind, setKind] = useState(RELATION_KINDS[0].id);+ const outbound = Array.isArray(relations.outbound) ? relations.outbound : [];+ const inbound = Array.isArray(relations.inbound) ? relations.inbound : [];++ // Hide the current record + everything already linked outbound from the+ // picker so the user can't double-link or self-link.+ const excludeIds = [record.id, ...outbound.map((r) => r.toId)];++ const chip = (other) => {+ const badge = CATALOG_BADGE_BY_ID[other?.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';+ return (+ <Link to={`/catalog/${encodeURIComponent(other?.type || 'idea')}/${encodeURIComponent(other?.id)}`}+ className="inline-flex items-center gap-1.5 text-xs px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-200 hover:opacity-80">+ <span className="truncate max-w-[16rem]">{other?.name || other?.id || '(unnamed)'}</span>+ <span className={`text-[9px] uppercase tracking-wider px-1 py-0.5 rounded border ${badge}`}>{other?.type}</span>+ </Link>+ );+ };++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between gap-2 mb-3 flex-wrap">+ <h2 className="text-sm font-semibold text-white">Relations</h2>+ <div className="flex items-center gap-2">+ <label htmlFor="relation-kind" className="sr-only">Relation kind</label>+ <select id="relation-kind" value={kind} onChange={(e) => setKind(e.target.value)}+ className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-xs text-white focus:outline-none focus:border-port-accent">+ {RELATION_KINDS.map((r) => <option key={r.id} value={r.id}>{r.label}</option>)}+ </select>+ <button type="button" onClick={() => setPickerOpen(true)}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 text-white text-xs font-medium">+ <Plus size={12} aria-hidden="true" /> Add relation+ </button>+ </div>+ </div>++ {outbound.length === 0 && inbound.length === 0 ? (+ <p className="text-xs text-gray-500">No relations yet. Link this ingredient to another (a character to the place they live, a scene to its cast, …).</p>+ ) : (+ <div className="space-y-3">+ {outbound.length > 0 && (+ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">Outbound</div>+ <ul className="space-y-1.5">+ {outbound.map((r) => (+ <li key={`${r.toId}-${r.kind}`} className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-gray-400">{getRelationKind(r.kind)?.label || r.kind}</span>+ {chip(r.other)}+ <button type="button" onClick={() => onRemove(r.toId, r.kind)}+ aria-label={`Remove relation to ${r.other?.name || r.toId}`}+ className="text-gray-500 hover:text-port-error">+ <X size={12} aria-hidden="true" />+ </button>+ </li>+ ))}+ </ul>+ </div>+ )}+ {inbound.length > 0 && (+ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">Inbound</div>+ <ul className="space-y-1.5">+ {inbound.map((r) => (+ <li key={`${r.fromId}-${r.kind}`} className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-gray-400">{getRelationKind(r.kind)?.inverseLabel || r.kind}</span>+ {chip(r.other)}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ )}++ <IngredientPicker+ open={pickerOpen}+ onClose={() => setPickerOpen(false)}+ onSelect={(picked) => onAdd(picked, kind)}+ excludeIds={excludeIds}+ />+ </section>+ );+}+function SourcesPanel({ sources }) {const list = Array.isArray(sources) ? sources : [];return (diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex 2d27f79985..b182b1e21e 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -73,6 +73,17 @@ export const unlinkCatalogIngredient = (id, body, options) =>export const listCatalogIngredientsForRef = (refKind, refId, options) =>request(`/catalog/refs/${enc(refKind)}/${enc(refId)}/ingredients`, options);+// --- Relations (ingredient ↔ ingredient) --------------------------------++export const listCatalogIngredientRelations = (id, options) =>+ request(`/catalog/ingredients/${enc(id)}/relations`, options);++export const linkCatalogIngredientRelation = (id, body, options) =>+ request(`/catalog/ingredients/${enc(id)}/relations`, { method: 'POST', body: JSON.stringify(body), ...options });++export const unlinkCatalogIngredientRelation = (id, body, options) =>+ request(`/catalog/ingredients/${enc(id)}/relations`, { method: 'DELETE', body: JSON.stringify(body), ...options });+// --- Bulk import / export ----------------------------------------------export const bulkImportCatalogIngredients = (body, options) =>diff --git a/scripts/migrations/050-catalog-ingredient-relations.js b/scripts/migrations/050-catalog-ingredient-relations.jsnew file mode 100644index 0000000000..aef5103ba1--- /dev/null+++ b/scripts/migrations/050-catalog-ingredient-relations.js@@ -0,0 +1,25 @@+/**+ * Registration stub for the catalog_ingredient_relations table.+ *+ * The actual DDL — `CREATE TABLE IF NOT EXISTS catalog_ingredient_relations`+ * plus its indexes and the `trg_catalog_relation_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 are boot-time + stub-registered.+ *+ * This stub exists so the relations table change is *registered the standard+ * way*: it lands in `data/migrations.applied.json` so the migration ledger and+ * `git log` show when the catalog graph seam was introduced. The table itself+ * is additive (a brand-new table — no existing rows to walk), so there is no+ * data backfill to perform.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🔗 catalog_ingredient_relations: 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.jsindex 7128aa6e05..4eb07488a8 100644--- a/server/lib/catalogTypes.js+++ b/server/lib/catalogTypes.js@@ -193,6 +193,53 @@ export function currentPayloadSchemaVersion(id) {return BY_ID[id]?.payloadSchemaVersion ?? 1;}+/**+ * Catalog ingredient↔ingredient RELATION kinds.+ *+ * Drives the `catalog_ingredient_relations.kind` column (an app-layer enum, not+ * a DB CHECK — same loosening rationale as the type CHECK discussion above) and+ * the "Relations" panel on the ingredient detail page. Mirrored on the client+ * at `client/src/lib/catalogTypes.js` (drift asserted by the client test).+ *+ * Each entry:+ * id — the stored `kind` discriminator.+ * label — human label for the relation chip / picker option (the active+ * "from → to" direction).+ * inverseLabel — label shown when the relation is viewed from the `to` side+ * (the inbound direction), so a single stored edge reads correctly+ * from both ingredients' detail pages.+ */+const RELATION_REGISTRY = [+ { id: 'appears-in', label: 'Appears in', inverseLabel: 'Features' },+ { id: 'lives-in', label: 'Lives in', inverseLabel: 'Home of' },+ { id: 'created-by', label: 'Created by', inverseLabel: 'Creator of' },+ { id: 'parent-of', label: 'Parent of', inverseLabel: 'Child of' },+ { id: 'variant-of', label: 'Variant of', inverseLabel: 'Has variant' },+ { id: 'references', label: 'References', inverseLabel: 'Referenced by' },+ { id: 'related-to', label: 'Related to', inverseLabel: 'Related to' },+];++// Fail-fast at module load — duplicate / malformed relation kinds block boot.+const seenRelationIds = new Set();+for (const r of RELATION_REGISTRY) {+ if (!r.id || typeof r.id !== 'string') throw new Error('catalogTypes: relation entry missing id');+ if (seenRelationIds.has(r.id)) throw new Error(`catalogTypes: duplicate relation kind "${r.id}"`);+ seenRelationIds.add(r.id);+ if (!r.label) throw new Error(`catalogTypes: relation "${r.id}" missing label`);+}++export const RELATION_KINDS = Object.freeze(RELATION_REGISTRY.map((r) => Object.freeze({ ...r })));++/** Frozen ordered list of relation kind ids — the canonical enum source. */+export const RELATION_KIND_IDS = Object.freeze(RELATION_KINDS.map((r) => r.id));++const RELATION_BY_ID = Object.freeze(Object.fromEntries(RELATION_KINDS.map((r) => [r.id, r])));++/** Look up a relation-kind entry by id. Returns `undefined` for unknown ids. */+export function getRelationKind(id) {+ return RELATION_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 upgradeddiff --git a/server/lib/catalogTypes.test.js b/server/lib/catalogTypes.test.jsindex b5019738bb..5b09f6039f 100644--- a/server/lib/catalogTypes.test.js+++ b/server/lib/catalogTypes.test.js@@ -24,6 +24,9 @@ import {ingredientIdPrefix,currentPayloadSchemaVersion,upgradePayload,+ RELATION_KINDS,+ RELATION_KIND_IDS,+ getRelationKind,} from './catalogTypes.js';import { INGREDIENT_TYPES } from './catalogValidation.js';@@ -172,3 +175,26 @@ describe('catalogTypes — payload schemaVersion', () => {expect(out.x).toBe(1);});});++describe('catalogTypes — relation kinds', () => {+ it('exposes the documented relation kinds, frozen + unique', () => {+ expect(Object.isFrozen(RELATION_KINDS)).toBe(true);+ for (const k of ['appears-in', 'lives-in', 'created-by', 'parent-of', 'variant-of', 'references']) {+ expect(RELATION_KIND_IDS).toContain(k);+ }+ expect(new Set(RELATION_KIND_IDS).size).toBe(RELATION_KIND_IDS.length);+ });++ it('every relation kind has a label and inverseLabel', () => {+ for (const r of RELATION_KINDS) {+ expect(typeof r.label).toBe('string');+ expect(r.label.length).toBeGreaterThan(0);+ expect(typeof r.inverseLabel).toBe('string');+ }+ });++ it('getRelationKind resolves a known id and returns undefined for unknown', () => {+ expect(getRelationKind('lives-in')?.label).toBe('Lives in');+ expect(getRelationKind('nemesis-of')).toBeUndefined();+ });+});diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 060a4632a5..bbde775fe4 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 } from './catalogTypes.js';+import { INGREDIENT_TYPE_IDS, RELATION_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@@ -27,6 +27,10 @@ export const REF_KINDS = Object.freeze(['creative-director',]);+// Relation kinds derived from the shared registry (`catalogTypes.js`) — adding+// a kind there flows through to the Zod enum below.+export const RELATION_KINDS = RELATION_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();@@ -77,6 +81,16 @@ export const catalogIngredientLinkSchema = z.object({role: z.string().trim().min(1).max(64),}).strict();+// Ingredient↔ingredient relation link/unlink body. `toId` is the OTHER end of+// the directed edge (the route's `:id` is the `fromId`). `kind` is gated to the+// shared relation registry. The route rejects self-edges (`fromId === toId`) at+// the DB layer; the schema can't see the path param, so that check stays+// server-side in `linkIngredientRelation`.+export const catalogRelationLinkSchema = z.object({+ toId: z.string().trim().min(1).max(80),+ kind: z.enum(RELATION_KINDS),+}).strict();+export const catalogScrapCommitSchema = z.object({accepted: z.array(catalogIngredientCreateSchema.extend({// Optional source-span hint (server forwards as-is to linkIngredientToSource).@@ -209,6 +223,21 @@ export const catalogSyncRefSchema = z.object({syncSequence: z.string().optional(),}).passthrough();+// Relation rows carry tombstone fields (soft-delete from day one). `kind` is a+// freeform string on the wire (not the strict enum) so a peer running a newer+// PortOS with an additional relation kind doesn't get its whole envelope+// rejected by an older receiver — the version gate already covers true+// shape skew, and an unknown-kind row stores harmlessly.+export const catalogSyncRelationSchema = z.object({+ fromId: z.string().max(80),+ toId: z.string().max(80),+ kind: z.string().max(32),+ createdAt: isoDate,+ deleted: z.boolean().optional(),+ deletedAt: z.string().nullable().optional(),+ syncSequence: z.string().optional(),+}).passthrough();+// Receiver may receive `portosMeta.schemaVersions.catalog` for the version// gate; the rest of portosMeta is informational. We accept arbitrary keys// inside portosMeta with passthrough but cap its size at 4KB to deny a peer@@ -226,5 +255,6 @@ export const catalogSyncEnvelopeSchema = z.object({ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),sources: z.array(catalogSyncSourceSchema).max(20_000).optional(),refs: z.array(catalogSyncRefSchema).max(20_000).optional(),+ relations: z.array(catalogSyncRelationSchema).max(20_000).optional(),portosMeta,}).passthrough();diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.jsindex c4bd191502..cdf0ec6f46 100644--- a/server/lib/catalogValidation.test.js+++ b/server/lib/catalogValidation.test.js@@ -21,6 +21,8 @@ import {catalogSyncEnvelopeSchema,catalogBulkImportSchema,catalogExportQuerySchema,+ catalogRelationLinkSchema,+ RELATION_KINDS,} from './catalogValidation.js';describe('catalogValidation — ingredient types & ref kinds', () => {@@ -318,3 +320,66 @@ describe('catalogValidation — catalogExportQuerySchema', () => {expect(() => catalogExportQuerySchema.parse({ refKind: 'universe', refId: 'a'.repeat(200) })).toThrow();});});++describe('catalogValidation — relation kinds & catalogRelationLinkSchema', () => {+ it('exposes the relation kinds as a frozen list including the documented set', () => {+ expect(Object.isFrozen(RELATION_KINDS)).toBe(true);+ for (const k of ['appears-in', 'lives-in', 'created-by', 'parent-of', 'variant-of', 'references']) {+ expect(RELATION_KINDS).toContain(k);+ }+ });++ it('accepts a valid relation link body', () => {+ const out = catalogRelationLinkSchema.parse({ toId: 'cat-chr-abc', kind: 'lives-in' });+ expect(out).toEqual({ toId: 'cat-chr-abc', kind: 'lives-in' });+ });++ it('accepts every registered relation kind', () => {+ for (const k of RELATION_KINDS) {+ expect(() => catalogRelationLinkSchema.parse({ toId: 'x', kind: k })).not.toThrow();+ }+ });++ it('rejects an unknown relation kind', () => {+ expect(() => catalogRelationLinkSchema.parse({ toId: 'x', kind: 'nemesis-of' })).toThrow();+ });++ it('rejects a missing or empty toId', () => {+ expect(() => catalogRelationLinkSchema.parse({ kind: 'lives-in' })).toThrow();+ expect(() => catalogRelationLinkSchema.parse({ toId: '', kind: 'lives-in' })).toThrow();+ });++ it('rejects unknown keys (strict)', () => {+ expect(() => catalogRelationLinkSchema.parse({ toId: 'x', kind: 'lives-in', fromId: 'y' })).toThrow();+ });++ it('caps toId at 80 chars', () => {+ expect(() => catalogRelationLinkSchema.parse({ toId: 'a'.repeat(81), kind: 'lives-in' })).toThrow();+ });+});++describe('catalogValidation — catalogSyncEnvelopeSchema relations block', () => {+ it('accepts an envelope carrying a relations array with tombstone fields', () => {+ const out = catalogSyncEnvelopeSchema.parse({+ relations: [+ { fromId: 'a', toId: 'b', kind: 'lives-in', createdAt: '2026-01-01T00:00:00Z' },+ { fromId: 'a', toId: 'c', kind: 'references', createdAt: '2026-01-01T00:00:00Z', deleted: true, deletedAt: '2026-01-02T00:00:00Z' },+ ],+ });+ expect(out.relations).toHaveLength(2);+ });++ it('tolerates a forward (unknown) relation kind on the wire', () => {+ // The sync schema intentionally accepts freeform `kind` (not the enum) so a+ // newer peer's extra relation kind doesn't get the whole envelope rejected.+ expect(() => catalogSyncEnvelopeSchema.parse({+ relations: [{ fromId: 'a', toId: 'b', kind: 'future-kind', createdAt: '2026-01-01T00:00:00Z' }],+ })).not.toThrow();+ });++ it('requires createdAt on a relation row', () => {+ expect(() => catalogSyncEnvelopeSchema.parse({+ relations: [{ fromId: 'a', toId: 'b', kind: 'lives-in' }],+ })).toThrow();+ });+});diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex ba08336fd5..21a6996906 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -28,6 +28,7 @@ const CATALOG_TABLES = ['catalog_ingredients','catalog_ingredient_sources','catalog_ingredient_refs',+ 'catalog_ingredient_relations',];// Strip line comments + collapse whitespace so column lists compare cleanly.diff --git a/server/lib/db.js b/server/lib/db.jsindex 8250b0608d..f90ce3fe68 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -236,6 +236,23 @@ export async function ensureSchema() {`CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_target ON catalog_ingredient_refs (ref_kind, ref_id)`,`CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_sync_seq ON catalog_ingredient_refs (sync_sequence)`,+ // Ingredient↔ingredient edges (the catalog graph seam). `kind` is an+ // app-layer enum (RELATION_KINDS in catalogTypes.js), not a DB CHECK.+ // Both ids CASCADE on ingredient hard-delete; soft-delete columns from day+ // one so unlinks tombstone + propagate to peers.+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_relations (+ from_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,+ to_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,+ kind VARCHAR(32) NOT NULL,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ,+ sync_sequence BIGSERIAL,+ PRIMARY KEY (from_id, to_id, kind)+ )`,+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id)`,+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (sync_sequence)`,+`CREATE OR REPLACE FUNCTION update_catalog_ingredient_timestamp()RETURNS TRIGGER AS $$DECLARE@@ -332,6 +349,25 @@ export async function ensureSchema() {BEFORE UPDATE ON catalog_ingredient_refsFOR EACH ROWEXECUTE FUNCTION update_catalog_ref_sync_seq()`,++ // Relation UPDATE bumps sync_sequence on soft-delete / revival so a peer+ // sees the tombstone (or un-delete) on its next pull — mirrors the ref+ // trigger above.+ `CREATE OR REPLACE FUNCTION update_catalog_relation_sync_seq()+ RETURNS TRIGGER AS $$+ BEGIN+ IF NEW.deleted IS DISTINCT FROM OLD.deleted+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_relations', 'sync_sequence'));+ END IF;+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql`,+ `DROP TRIGGER IF EXISTS trg_catalog_relation_sync_seq ON catalog_ingredient_relations`,+ `CREATE TRIGGER trg_catalog_relation_sync_seq+ BEFORE UPDATE ON catalog_ingredient_relations+ FOR EACH ROW+ EXECUTE FUNCTION update_catalog_relation_sync_seq()`,];for (const sql of catalogDDL) {await pool.query(sql);diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 8dfc112a8f..c4f178c029 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -76,7 +76,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// registry `payloadSchemaVersion` to 2 with a genuine shape change (a peer// ≤ that version would round-trip the new shape through an unaware// sanitizer) MUST bump `catalog` here in lockstep.- catalog: 3,+ //+ // v4 = `catalog_ingredient_relations` table (ingredient↔ingredient edges)+ // + a new `relations: [...]` block in the catalog sync envelope. An older+ // (≤v3) receiver doesn't understand the relations block, so a v4 sender+ // pushing to it is sender-ahead on `catalog` and gets a 412 — correct,+ // since the older peer would silently drop every relation edge. v4 receivers+ // still accept ≤v3 senders (sender-behind): those envelopes simply carry no+ // `relations` block and the receiver applies the other four kinds as before.+ catalog: 4,// 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 woulddiff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex 308c98c94f..bff57f0b46 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -13,6 +13,7 @@ import {catalogIngredientCreateSchema,catalogIngredientPatchSchema,catalogIngredientLinkSchema,+ catalogRelationLinkSchema,catalogIngredientQuerySchema,catalogScrapCommitSchema,catalogSyncEnvelopeSchema,@@ -208,6 +209,37 @@ router.get('/refs/:refKind/:refId/ingredients', asyncHandler(async (req, res) =>res.json(await catalogDB.listIngredientsForRef(req.params.refKind, req.params.refId));}));+// --- Ingredient↔ingredient relations -----------------------------------++router.get('/ingredients/:id/relations', 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.listRelationsForIngredient(req.params.id));+}));++router.post('/ingredients/:id/relations', asyncHandler(async (req, res) => {+ validateRequest(catalogRelationLinkSchema, req.body);+ if (req.params.id === req.body.toId) {+ throw new ServerError('Cannot relate an ingredient to itself', { status: 400 });+ }+ // Both ends must exist — FK would reject anyway, but a 404 reads cleaner+ // than a raw FK violation and matches the link route's failure surface.+ const [from, to] = await Promise.all([+ catalogDB.getIngredient(req.params.id),+ catalogDB.getIngredient(req.body.toId),+ ]);+ if (!from) throw new ServerError('Ingredient not found', { status: 404 });+ if (!to) throw new ServerError('Related ingredient not found', { status: 404 });+ await catalogDB.linkIngredientRelation(req.params.id, req.body.toId, req.body.kind);+ res.status(201).json({ success: true });+}));++router.delete('/ingredients/:id/relations', asyncHandler(async (req, res) => {+ validateRequest(catalogRelationLinkSchema, req.body);+ await catalogDB.unlinkIngredientRelation(req.params.id, req.body.toId, 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 catalogdiff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 08185d7e4b..f55275108b 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -251,6 +251,28 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_refs (CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_target ON catalog_ingredient_refs (ref_kind, ref_id);CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_sync_seq ON catalog_ingredient_refs (sync_sequence);+-- Ingredient↔ingredient edges — the seam that makes the catalog a graph+-- instead of a flat list. `kind` is an app-layer enum (RELATION_KINDS in+-- server/lib/catalogTypes.js): 'appears-in'|'lives-in'|'created-by'|+-- 'parent-of'|'variant-of'|'references'|'related-to'. Both ids FK to+-- catalog_ingredients(id) ON DELETE CASCADE so deleting an ingredient+-- (hard-delete) cleans up its edges. Soft-delete (deleted/deleted_at) from day+-- one so unlinks propagate to peers as tombstones — same lesson as the refs+-- table. Directed edge: from_id → to_id (the inverse direction is rendered in+-- the UI from the same row, not stored twice).+CREATE TABLE IF NOT EXISTS catalog_ingredient_relations (+ from_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,+ to_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,+ kind VARCHAR(32) NOT NULL, -- relation kind from RELATION_KINDS+ created_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so unlinks propagate to peers+ deleted_at TIMESTAMPTZ,+ sync_sequence BIGSERIAL,+ PRIMARY KEY (from_id, to_id, kind)+);+CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id);+CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (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@@ -363,3 +385,23 @@ CREATE TRIGGER trg_catalog_ref_sync_seqBEFORE UPDATE ON catalog_ingredient_refsFOR EACH ROWEXECUTE FUNCTION update_catalog_ref_sync_seq();++-- Relation UPDATE bumps sync_sequence on soft-delete or revival so peers pick+-- up the tombstone (or the un-delete) on their next pull — same rationale as+-- the ref trigger above.+CREATE OR REPLACE FUNCTION update_catalog_relation_sync_seq()+RETURNS TRIGGER AS $$+BEGIN+ IF NEW.deleted IS DISTINCT FROM OLD.deleted+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_relations', 'sync_sequence'));+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trg_catalog_relation_sync_seq ON catalog_ingredient_relations;+CREATE TRIGGER trg_catalog_relation_sync_seq+ BEFORE UPDATE ON catalog_ingredient_relations+ FOR EACH ROW+ EXECUTE FUNCTION update_catalog_relation_sync_seq();diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 0ab2d5c339..3d345dd2aa 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -79,6 +79,19 @@ function rowToRef(row) {};}+function rowToRelation(row) {+ if (!row) return null;+ return {+ fromId: row.from_id,+ toId: row.to_id,+ kind: row.kind,+ 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 {@@ -488,13 +501,123 @@ export async function listIngredientsForRef(refKind, refId) {}+// --- Ingredient↔ingredient relations -----------------------------------+// Directed edges (from_id → to_id, kind). Soft-deleted on unlink so peers+// receive the tombstone. ON CONFLICT DO UPDATE revives a soft-deleted edge+// (the trg_catalog_relation_sync_seq trigger bumps sync_sequence only when+// deleted/deleted_at actually change, so a link-on-active-row stays a no-op).++export async function linkIngredientRelation(fromId, toId, kind) {+ if (fromId === toId) throw new Error('cannot relate an ingredient to itself');+ await query(+ `INSERT INTO catalog_ingredient_relations (from_id, to_id, kind)+ VALUES ($1, $2, $3)+ ON CONFLICT (from_id, to_id, kind) DO UPDATE+ SET deleted = false, deleted_at = NULL`,+ [fromId, toId, kind],+ );+}++export async function unlinkIngredientRelation(fromId, toId, kind) {+ // Soft-delete (mirrors unlinkIngredientFromRef): keep the row as a tombstone+ // so the sync_sequence bump propagates the unlink to peers. `AND deleted =+ // false` keeps a re-unlink from re-bumping the sequence needlessly.+ await query(+ `UPDATE catalog_ingredient_relations+ SET deleted = true, deleted_at = NOW()+ WHERE from_id = $1 AND to_id = $2 AND kind = $3+ AND deleted = false`,+ [fromId, toId, kind],+ );+}++// Both directions for one ingredient's detail "Relations" panel. Outbound+// (from_id = id) and inbound (to_id = id) are returned separately so the UI+// can render each with the correct directional label. Joins the OTHER end's+// ingredient name/type so the chip reads without a second fetch. Live edges+// only (deleted = false on both the edge and the joined ingredient).+export async function listRelationsForIngredient(id) {+ const [outbound, inbound] = await Promise.all([+ query(+ `SELECT r.from_id, r.to_id, r.kind, r.created_at,+ i.name AS other_name, i.type AS other_type+ FROM catalog_ingredient_relations r+ JOIN catalog_ingredients i ON i.id = r.to_id+ WHERE r.from_id = $1 AND r.deleted = false AND i.deleted = false+ ORDER BY r.created_at ASC`,+ [id],+ ),+ query(+ `SELECT r.from_id, r.to_id, r.kind, r.created_at,+ i.name AS other_name, i.type AS other_type+ FROM catalog_ingredient_relations r+ JOIN catalog_ingredients i ON i.id = r.from_id+ WHERE r.to_id = $1 AND r.deleted = false AND i.deleted = false+ ORDER BY r.created_at ASC`,+ [id],+ ),+ ]);+ const mapRow = (row, otherId) => ({+ fromId: row.from_id,+ toId: row.to_id,+ kind: row.kind,+ createdAt: row.created_at.toISOString(),+ other: { id: otherId, name: row.other_name, type: row.other_type },+ });+ return {+ outbound: outbound.rows.map((row) => mapRow(row, row.to_id)),+ inbound: inbound.rows.map((row) => mapRow(row, row.from_id)),+ };+}++export async function getRelationChangesSince(since = '0', limit = 100) {+ const result = await query(+ `SELECT * FROM catalog_ingredient_relations 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(rowToRelation), hasMore };+}++export async function upsertRelationFromPeer(rel) {+ // Mirrors upsertRefFromPeer's mixed-version handling: a peer that predates+ // the relations feature never emits these rows, so there's no v1-without-+ // tombstone shape to defend against here. But we still treat "key absent"+ // as "no opinion" symmetrically in case a forked peer omits the tombstone+ // fields — preserve local state on conflict rather than coercing to false.+ const hasTombstoneFields =+ Object.prototype.hasOwnProperty.call(rel, 'deleted') ||+ Object.prototype.hasOwnProperty.call(rel, 'deletedAt');+ if (hasTombstoneFields) {+ await query(+ `INSERT INTO catalog_ingredient_relations+ (from_id, to_id, kind, created_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (from_id, to_id, kind) DO UPDATE+ SET deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [rel.fromId, rel.toId, rel.kind, rel.createdAt, !!rel.deleted, rel.deletedAt || null],+ );+ } else {+ await query(+ `INSERT INTO catalog_ingredient_relations (from_id, to_id, kind, created_at)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (from_id, to_id, kind) DO NOTHING`,+ [rel.fromId, rel.toId, rel.kind, rel.createdAt],+ );+ }+}++export async function getMaxSequences() {const result = await query(`SELECTCOALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredients), 0)::text AS ingredients,COALESCE((SELECT MAX(sync_sequence) FROM catalog_scraps), 0)::text AS scraps,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_refs), 0)::text AS refs,+ COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_relations), 0)::text AS relations`);return result.rows[0];}diff --git a/server/services/catalogSync.js b/server/services/catalogSync.jsindex 66d1c0c044..9a8f662b0f 100644--- a/server/services/catalogSync.js+++ b/server/services/catalogSync.js@@ -2,18 +2,18 @@* Catalog Federation Sync Service** Peer-to-peer sync for the Creative Ingredients Catalog. Mirrors- * server/services/memorySync.js but the envelope carries four kinds- * (scraps, ingredients, sources, refs) because the catalog is a- * three-table relational store, not a single flat row set.+ * server/services/memorySync.js but the envelope carries five kinds+ * (scraps, ingredients, sources, refs, relations) because the catalog is a+ * multi-table relational store, not a single flat row set.** Pull protocol:- * GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&since[sources]=C&since[refs]=D&limit=100- * → { scraps[], ingredients[], sources[], refs[], maxSequences, hasMore }+ * GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&...&since[relations]=E&limit=100+ * → { scraps[], ingredients[], sources[], refs[], relations[], maxSequences, hasMore }*- * The four BIGSERIAL `sync_sequence` columns are INDEPENDENT — a row at+ * The BIGSERIAL `sync_sequence` columns are INDEPENDENT — a row at* sources.sync_sequence=50 isn't comparable to ingredients.sync_sequence=50.- * The receiver therefore tracks four cursors and `since` is `{ scraps,- * ingredients, sources, refs }`. A scalar `?since=N` is still accepted for+ * The receiver therefore tracks one cursor per kind and `since` is `{ scraps,+ * ingredients, sources, refs, relations }`. A scalar `?since=N` is still accepted for* back-compat / one-shot pulls and is applied uniformly to all four kinds.* `hasMore` is true when ANY of the four tables had more than `limit` rows* past its respective cursor — drain by re-pulling with the maxSequences from@@ -30,15 +30,17 @@ import {getIngredientChangesSince,getSourceChangesSince,getRefChangesSince,+ getRelationChangesSince,getMaxSequences,upsertScrapFromPeer,upsertIngredientFromPeer,upsertSourceFromPeer,upsertRefFromPeer,+ upsertRelationFromPeer,} from './catalogDB.js';import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';-const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs'];+const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations'];// Normalize `since` (scalar string OR per-kind object) into a `{ scraps,// ingredients, sources, refs }` cursor map. Scalar form is uniform across@@ -58,15 +60,16 @@ function normalizeCursors(since) {export async function getChangesSince(since = '0', limit = 100) {const cursors = normalizeCursors(since);- const [scraps, ingredients, sources, refs] = await Promise.all([+ const [scraps, ingredients, sources, refs, relations] = await Promise.all([getScrapChangesSince(cursors.scraps, limit),getIngredientChangesSince(cursors.ingredients, limit),getSourceChangesSince(cursors.sources, limit),getRefChangesSince(cursors.refs, limit),+ getRelationChangesSince(cursors.relations, limit),]);const hasMore =- scraps.hasMore || ingredients.hasMore || sources.hasMore || refs.hasMore;+ scraps.hasMore || ingredients.hasMore || sources.hasMore || refs.hasMore || relations.hasMore;// Per-kind cursor advance — fall back to the inbound cursor so the next pull// doesn't move backward on a quiet kind.@@ -78,11 +81,13 @@ export async function getChangesSince(since = '0', limit = 100) {ingredients: ingredients.items,sources: sources.items,refs: refs.items,+ relations: relations.items,maxSequences: {scraps: maxOf(scraps.items, cursors.scraps),ingredients: maxOf(ingredients.items, cursors.ingredients),sources: maxOf(sources.items, cursors.sources),refs: maxOf(refs.items, cursors.refs),+ relations: maxOf(relations.items, cursors.relations),},hasMore,};@@ -114,6 +119,7 @@ export async function applyRemoteChanges(envelope = {}) {ingredients: { inserted: 0, updated: 0, skipped: 0, failed: 0 },sources: { applied: 0, failed: 0 },refs: { applied: 0, failed: 0 },+ relations: { applied: 0, failed: 0 },errors: [],};@@ -169,6 +175,18 @@ export async function applyRemoteChanges(envelope = {}) {}}+ // Relations FK BOTH ids to catalog_ingredients, so they land after the+ // ingredient upserts above (same envelope ordering rationale as sources).+ for (const rel of envelope.relations || []) {+ try {+ await upsertRelationFromPeer(rel);+ stats.relations.applied++;+ } catch (err) {+ stats.relations.failed++;+ recordFailure('relation', `${rel?.fromId}/${rel?.kind}/${rel?.toId}`, err);+ }+ }+return stats;}diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.jsindex 1f34626e4b..4a645daf97 100644--- a/server/services/catalogSync.test.js+++ b/server/services/catalogSync.test.js@@ -17,11 +17,13 @@ vi.mock('./catalogDB.js', () => ({getIngredientChangesSince: vi.fn(),getSourceChangesSince: vi.fn(),getRefChangesSince: vi.fn(),+ getRelationChangesSince: vi.fn(),getMaxSequences: vi.fn(),upsertScrapFromPeer: vi.fn(),upsertIngredientFromPeer: vi.fn(),upsertSourceFromPeer: vi.fn(),upsertRefFromPeer: vi.fn(),+ upsertRelationFromPeer: vi.fn(),}));vi.mock('../lib/schemaVersions.js', async () => {@@ -48,6 +50,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: false }); // LWW skipcatalogDB.upsertSourceFromPeer.mockResolvedValueOnce(undefined);catalogDB.upsertRefFromPeer.mockResolvedValueOnce(undefined);+ catalogDB.upsertRelationFromPeer.mockResolvedValueOnce(undefined);const stats = await applyRemoteChanges({scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],@@ -57,6 +60,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {],sources: [{ ingredientId: 'i1', scrapId: 's1', extractedAt: 't' }],refs: [{ ingredientId: 'i1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: 't' }],+ relations: [{ fromId: 'i1', toId: 'i2', kind: 'lives-in', createdAt: 't' }],});expect(stats.scraps.inserted).toBe(1);@@ -64,9 +68,19 @@ describe('applyRemoteChanges — dispatch + stats', () => {expect(stats.ingredients.skipped).toBe(1);expect(stats.sources.applied).toBe(1);expect(stats.refs.applied).toBe(1);+ expect(stats.relations.applied).toBe(1);expect(stats.errors).toHaveLength(0);});+ it('isolates a failing relation row and records it', async () => {+ catalogDB.upsertRelationFromPeer.mockRejectedValueOnce(new Error('fk violation'));+ const stats = await applyRemoteChanges({+ relations: [{ fromId: 'i1', toId: 'gone', kind: 'references', createdAt: 't' }],+ });+ expect(stats.relations.failed).toBe(1);+ expect(stats.errors[0]).toMatchObject({ kind: 'relation', message: 'fk violation' });+ });+it('isolates per-row failures — one bad row does not abort the rest', async () => {catalogDB.upsertScrapFromPeer.mockRejectedValueOnce(new Error('boom'));catalogDB.upsertScrapFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });@@ -100,15 +114,21 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertRefFromPeer.mockImplementation(async () => {order.push('ref');});+ catalogDB.upsertRelationFromPeer.mockImplementation(async () => {+ order.push('relation');+ });await applyRemoteChanges({+ relations: [{ fromId: 'i1', toId: 'i2', kind: 'lives-in', createdAt: 't' }],refs: [{ ingredientId: 'i1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: 't' }],sources: [{ ingredientId: 'i1', scrapId: 's1', extractedAt: 't' }],ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' }],scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],});- expect(order).toEqual(['scrap', 'ingredient', 'source', 'ref']);+ // Relations land last so both FK ends are present from the ingredient+ // upserts.+ expect(order).toEqual(['scrap', 'ingredient', 'source', 'ref', 'relation']);});});@@ -157,30 +177,34 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {catalogDB.getIngredientChangesSince.mockResolvedValue({ items: [], hasMore: false });catalogDB.getSourceChangesSince.mockResolvedValue({ items: [], hasMore: false });catalogDB.getRefChangesSince.mockResolvedValue({ items: [], hasMore: false });+ catalogDB.getRelationChangesSince.mockResolvedValue({ items: [], hasMore: false });});- it('accepts a scalar since and applies it uniformly to all four kinds', async () => {+ it('accepts a scalar since and applies it uniformly to all five kinds', async () => {await getChangesSince('42', 100);expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getSourceChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('42', 100);+ expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('42', 100);});it('accepts a per-kind cursor object', async () => {- await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20' }, 100);+ await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20', relations: '25' }, 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);});it('rejects non-numeric cursor values, falling back to "0"', async () => {- await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined }, 100);+ await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined, relations: 'x' }, 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);});it('per-kind maxSequence falls back to the inbound cursor on quiet kinds', async () => {@@ -190,7 +214,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' }, 100);+ const res = await getChangesSince({ scraps: '50', ingredients: '99', sources: '88', refs: '77', relations: '66' }, 100);// Quiet kinds reflect the inbound cursor — NOT 0 — so the next pull// doesn't move backward.@@ -198,6 +222,26 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {expect(res.maxSequences.ingredients).toBe('99');expect(res.maxSequences.sources).toBe('88');expect(res.maxSequences.refs).toBe('77');+ expect(res.maxSequences.relations).toBe('66');+ });++ it('advances the relations cursor to the last relation row', async () => {+ catalogDB.getRelationChangesSince.mockResolvedValue({+ items: [+ { fromId: 'a', toId: 'b', kind: 'lives-in', syncSequence: '10' },+ { fromId: 'a', toId: 'c', kind: 'references', syncSequence: '11' },+ ],+ hasMore: false,+ });+ const res = await getChangesSince({ scraps: '0', ingredients: '0', sources: '0', refs: '0', relations: '0' }, 100);+ expect(res.relations).toHaveLength(2);+ expect(res.maxSequences.relations).toBe('11');+ });++ it('hasMore is true when ONLY relations reports more', async () => {+ catalogDB.getRelationChangesSince.mockResolvedValue({ items: [], hasMore: true });+ const res = await getChangesSince('0', 100);+ expect(res.hasMore).toBe(true);});it('hasMore is true when ANY kind reports more', async () => {