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

federate the creative catalog: orchestrator-driven sync + bundle on universe push

[._.]/ Adam Eivya6eedd9ade80
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 39851ad81a..595fc52b8a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,9 @@
## Added
+- **[catalog-federation-orchestrator] The creative catalog now auto-replicates between peers.** The catalog sync routes existed but nothing pulled from peers — orphan ingredients (ideas / scenes / concepts not attached to a universe) and the universe→ingredient ref links stayed local. The sync orchestrator now runs `catalog` as a delta-based PostgreSQL category alongside Memory: on every peer-online event and on the background interval it pulls `GET /api/catalog/sync` (the seven independent per-kind BIGSERIAL cursors: scraps / ingredients / sources / refs / relations / tags / media) and applies each batch locally with the same last-writer-wins + per-row isolation + schema-version gate as direct sync. A peer ahead on the `catalog` schema records a gap on the Instances page (the existing SchemaGapBadge) and pauses draining instead of looping. Toggle it per peer under Instances → Sync Categories → "Catalog"; Postgres-only (a non-Postgres peer simply never enables it).
+- **[catalog-bundled-universe-push] Universe peer-pushes now carry their catalog enrichments.** When peer A pushes a universe to peer B, the push bundles the `catalog_ingredients` rows referenced by that universe's canon plus the universe→ingredient ref links. Previously only the embedded canon replicated, so the receiver re-derived a strictly-lossy view on first backfill — the `tags`, vector `embedding`, and `payload.summary`-style enrichments that live only in the catalog row were dropped. The bundle ships the full enriched rows (including tombstoned ref rows so unlinks propagate), applied through the same catalog-sync path; it rides only universe pushes (never series / mediaCollection), skips tombstone pushes, and is gated by `PORTOS_SCHEMA_VERSIONS.catalog` so a receiver on an older catalog schema rejects a forward-shaped bundle with a clean 409 rather than corrupting local rows. Postgres-only and best-effort — a bundle failure never fails the universe push.
+
- **[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.
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 53711f3a58..ecc19fdbae 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -7,7 +7,7 @@ import {
Database, Brain, CheckCircle2, AlertCircle, Clock,
RefreshCcw, Timer,
Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,
- Lock, Globe, Info, Sparkles, Film, Images
+ Lock, Globe, Info, Sparkles, Film, Images, Library
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Pill from '../components/ui/Pill';
@@ -457,11 +457,12 @@ const SYNC_CATEGORY_META = [
{ key: 'universe', label: 'Universe', icon: Sparkles, description: 'Universe Builder canon: characters, places, objects' },
{ key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' },
{ key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },
- { key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' }
+ { key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },
+ { key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }
];
-// Snapshot categories (excludes delta-based brain/memory)
-const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => m.key !== 'brain' && m.key !== 'memory');
+// Snapshot categories (excludes delta-based brain/memory/catalog)
+const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => m.key !== 'brain' && m.key !== 'memory' && m.key !== 'catalog');
function SyncCategoriesPanel({ peer, onRefresh }) {
const [expanded, setExpanded] = useState(false);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 78218e0355..9b064e04b5 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -6,6 +6,7 @@ import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
import { BIBLE_LIMITS } from './storyBible.js';
import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
import { STEP_IDS as STORY_STEP_IDS } from './storyBuilderSteps.js';
+import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogValidation.js';
import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
@@ -1446,10 +1447,24 @@ const peerSyncPushBase = {
// therefore rejects it. See peerSync.js buildPushPayload (never sets it for the
// mediaCollection kind) and applyIncomingPush.
const linkedCollectionField = { linkedCollection: peerWireRecordSchema.optional() };
+// Optional bundled catalog rows — a universe push carries the catalog
+// ingredients + universe→ingredient ref links referenced by its embedded
+// canon, so the receiver gets the enriched catalog row (tags, embedding,
+// payload.summary) instead of re-deriving a lossy view. Same wire shapes as
+// the direct catalog-sync envelope. ONLY valid on universe pushes (series /
+// mediaCollection .strict() reject it) — series catalog refs ride their own
+// catalog-sync category; smuggling them here would be a side-channel.
+const catalogBundleField = {
+ catalogBundle: z.object({
+ ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),
+ refs: z.array(catalogSyncRefSchema).max(20_000).optional(),
+ }).strict().optional(),
+};
const universePushSchema = z.object({
kind: z.literal('universe'),
...peerSyncPushBase,
...linkedCollectionField,
+ ...catalogBundleField,
}).strict();
const seriesPushSchema = z.object({
kind: z.literal('series'),
diff --git a/server/routes/instances.js b/server/routes/instances.js
index a852b33aed..697071da18 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -54,7 +54,8 @@ const syncCategoriesSchema = z.object({
// no-op for the missing category. Same regression class as the
// universe + pipeline omission tracked in .changelog/NEXT.md.
mediaCollections: z.boolean().optional(),
- videoHistory: z.boolean().optional()
+ videoHistory: z.boolean().optional(),
+ catalog: z.boolean().optional()
}).optional();
const updatePeerSchema = z.object({
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 858eb2bb59..45b2085d5d 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -1312,6 +1312,46 @@ export async function exportSliceForRef(refKind, refId) {
};
}
+/**
+ * Wire-shaped catalog bundle for one external ref (universe/series/issue/work),
+ * for piggy-backing on a peer RECORD push (e.g. a universe push carries the
+ * catalog rows referenced by its embedded canon). Unlike `exportSliceForRef`
+ * (a user-facing export that strips embeddings + tombstones) this is a SYNC
+ * payload:
+ *
+ * - `ingredients` carry their `embedding` + tombstone fields, so the
+ * receiver gets the full enriched row (tags, embedding, payload.summary)
+ * rather than re-deriving a strictly-lossy view from the embedded canon.
+ * - `refs` include TOMBSTONED rows (deleted = true) so an unlink propagates
+ * with the push — the "Appears in" panel converges across peers.
+ *
+ * Shapes match `catalogSyncIngredientSchema` / `catalogSyncRefSchema`, so the
+ * receiver applies them straight through `catalogSync.applyRemoteChanges`.
+ */
+export async function getCatalogBundleForRef(refKind, refId) {
+ // Every ref row for this target — live AND tombstoned (no `deleted = false`
+ // filter, unlike listRefsForIngredient) so unlinks ride the bundle.
+ const refResult = await query(
+ `SELECT * FROM catalog_ingredient_refs WHERE ref_kind = $1 AND ref_id = $2`,
+ [refKind, refId],
+ );
+ const refs = refResult.rows.map(rowToRef);
+
+ // Hydrate each referenced ingredient WITH embedding + tombstone state. A
+ // tombstoned ref still names a (possibly live) ingredient — include it so
+ // the receiver has the enriched row even if its own ref is being removed.
+ const ingredientIds = [...new Set(refs.map((r) => r.ingredientId))];
+ let ingredients = [];
+ if (ingredientIds.length > 0) {
+ const ingResult = await query(
+ `SELECT * FROM catalog_ingredients WHERE id = ANY($1)`,
+ [ingredientIds],
+ );
+ ingredients = ingResult.rows.map(rowToIngredient);
+ }
+ return { ingredients, refs };
+}
+
export async function getCatalogStats() {
const [byTypeResult, scrapResult, withEmb] = await Promise.all([
query(`SELECT type, COUNT(*) AS count FROM catalog_ingredients WHERE deleted = false GROUP BY type`),
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index a9da103d66..9e0f6d2494 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -239,6 +239,21 @@ export async function applyRemoteChanges(envelope = {}) {
return stats;
}
+// Total rows actually applied (inserted + updated for LWW kinds, applied for
+// tuple-unique kinds) across an `applyRemoteChanges` stats object. Lives here —
+// not in the federation orchestrator — so the per-kind stats SHAPE has a single
+// owner; a future envelope kind only needs adding here, not in every caller.
+export function countAppliedFromStats(stats = {}) {
+ return (
+ (stats.scraps?.inserted || 0) + (stats.scraps?.updated || 0) +
+ (stats.ingredients?.inserted || 0) + (stats.ingredients?.updated || 0) +
+ (stats.sources?.applied || 0) + (stats.refs?.applied || 0) +
+ (stats.relations?.applied || 0) +
+ (stats.tags?.inserted || 0) + (stats.tags?.updated || 0) +
+ (stats.media?.applied || 0)
+ );
+}
+
// Per-kind cursor view for the federation orchestrator. The previous scalar
// `getMaxSequence` collapsed the four BIGSERIALs into one max — that lied
// about the protocol (one cursor can't represent four independent sequences).
diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.js
index 2d244d12fb..60d626b5bb 100644
--- a/server/services/catalogSync.test.js
+++ b/server/services/catalogSync.test.js
@@ -39,6 +39,7 @@ const catalogDB = await import('./catalogDB.js');
const {
applyRemoteChanges,
getChangesSince,
+ countAppliedFromStats,
CatalogSyncVersionMismatchError,
} = await import('./catalogSync.js');
const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
@@ -326,3 +327,30 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {
expect(res.hasMore).toBe(true);
});
});
+
+describe('countAppliedFromStats', () => {
+ it('sums inserts/updates (LWW kinds) + applied (tuple kinds) across every kind', () => {
+ const total = countAppliedFromStats({
+ scraps: { inserted: 1, updated: 2 },
+ ingredients: { inserted: 3, updated: 4 },
+ sources: { applied: 5 },
+ refs: { applied: 6 },
+ relations: { applied: 7 },
+ tags: { inserted: 8, updated: 9 },
+ media: { applied: 10 },
+ });
+ expect(total).toBe(55);
+ });
+
+ it('treats missing kinds / fields as zero and tolerates an empty object', () => {
+ expect(countAppliedFromStats({})).toBe(0);
+ expect(countAppliedFromStats()).toBe(0);
+ expect(countAppliedFromStats({ ingredients: { inserted: 2 } })).toBe(2);
+ });
+
+ it('does NOT count skipped / failed rows', () => {
+ expect(countAppliedFromStats({
+ ingredients: { inserted: 1, updated: 0, skipped: 9, failed: 4 },
+ })).toBe(1);
+ });
+});
diff --git a/server/services/instances.js b/server/services/instances.js
index ad10681583..846d5e57f0 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -167,7 +167,8 @@ const DEFAULT_SYNC_CATEGORIES = {
universe: false,
pipeline: false,
mediaCollections: false,
- videoHistory: false
+ videoHistory: false,
+ catalog: false
};
export { DEFAULT_SYNC_CATEGORIES };
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index be4146c5a0..e1963a033e 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -1055,6 +1055,16 @@ async function buildPushPayload(sub, sourceInstanceId) {
const assetManifest = record.deleted === true
? []
: await buildAssetManifestWithCollection(record, linkedCollection);
+ // Bundle the catalog rows referenced by this universe (ingredients + the
+ // universe→ingredient ref links). The embedded canon already replicates
+ // via the universe record, but the catalog row's enrichments (tags,
+ // embedding, payload.summary) live ONLY in Postgres — without this bundle
+ // the receiver re-derives a strictly-lossy view on its first backfill.
+ // Skip for tombstone pushes (the universe is being deleted; its ref rows
+ // tombstone locally and ride a later catalog-sync cycle if needed).
+ const catalogBundle = record.deleted === true
+ ? null
+ : await buildCatalogBundleForRef('universe', sub.recordId);
return {
kind: 'universe',
record: sanitized,
@@ -1062,6 +1072,7 @@ async function buildPushPayload(sub, sourceInstanceId) {
sourceInstanceId,
portosMeta,
...(linkedCollection ? { linkedCollection } : {}),
+ ...(catalogBundle ? { catalogBundle } : {}),
};
}
if (sub.recordKind === 'series') {
@@ -1128,6 +1139,54 @@ async function buildPushPayload(sub, sourceInstanceId) {
return null;
}
+/**
+ * Build the catalog bundle (`{ ingredients, refs }`) that piggy-backs on a
+ * universe record push. Catalog data lives in Postgres only — on a non-Postgres
+ * install (or when the catalog tables don't exist yet) there's nothing to
+ * bundle, so we gate on the backend and swallow any read failure: a missing
+ * bundle is non-fatal (the universe record still replicates; the receiver's
+ * backfill re-derives a lossy view, exactly as before this bundle existed).
+ *
+ * Returns `null` (omit the key) when there's nothing to ship — both the
+ * non-Postgres case and the genuinely-empty case (a universe with no catalog
+ * refs yet). Dynamic import keeps catalogDB's pg module graph off peerSync's
+ * load path on installs that never touch Postgres.
+ */
+async function buildCatalogBundleForRef(refKind, refId) {
+ const { getBackendName } = await import('../memoryBackend.js');
+ if (getBackendName() !== 'postgres') return null;
+ const { getCatalogBundleForRef } = await import('../catalogDB.js');
+ const bundle = await getCatalogBundleForRef(refKind, refId).catch((err) => {
+ console.log(`⚠️ peerSync: catalog bundle for ${refKind}/${refId} failed: ${err.message}`);
+ return null;
+ });
+ if (!bundle) return null;
+ const ingredients = Array.isArray(bundle.ingredients) ? bundle.ingredients : [];
+ const refs = Array.isArray(bundle.refs) ? bundle.refs : [];
+ if (ingredients.length === 0 && refs.length === 0) return null;
+ return { ingredients, refs };
+}
+
+/**
+ * Apply a received catalog bundle on the receiver. Reuses
+ * `catalogSync.applyRemoteChanges` so the bundle goes through the exact same
+ * per-row LWW upsert + schema gate + try/catch isolation as direct catalog
+ * sync — we forward `portosMeta` so applyRemoteChanges runs the gate itself
+ * (defense in depth; the push-level gate already ran). Postgres-only; the
+ * applyIncomingPush caller already null-checks `catalogBundle`, but we re-gate
+ * the backend here so a stray call on a non-Postgres install is a clean no-op.
+ */
+async function applyCatalogBundle(catalogBundle, portosMeta) {
+ const { getBackendName } = await import('../memoryBackend.js');
+ if (getBackendName() !== 'postgres') return;
+ const { applyRemoteChanges } = await import('../catalogSync.js');
+ await applyRemoteChanges({
+ ingredients: Array.isArray(catalogBundle.ingredients) ? catalogBundle.ingredients : [],
+ refs: Array.isArray(catalogBundle.refs) ? catalogBundle.refs : [],
+ portosMeta,
+ });
+}
+
async function buildAssetManifestForSeries(series, issues, linkedCollection = null) {
const seriesAssets = await buildAssetManifest(series);
const dedup = new Map(seriesAssets.map((a) => [`${a.kind}:${a.filename}`, a]));
@@ -1244,7 +1303,7 @@ export async function applyIncomingPush(payload) {
if (!isPlainObject(payload)) {
throw makeErr('payload must be an object', ERR_VALIDATION);
}
- const { kind, record, issues, linkedCollection, assetManifest, sourceInstanceId, portosMeta } = payload;
+ const { kind, record, issues, linkedCollection, catalogBundle, assetManifest, sourceInstanceId, portosMeta } = payload;
if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {
throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);
}
@@ -1310,6 +1369,17 @@ export async function applyIncomingPush(payload) {
if (record.deleted !== true && isPlainObject(linkedCollection) && linkedCollection.deleted !== true) {
for (const c of RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection) relevantCategories.add(c);
}
+ // A catalog bundle ships catalog-schema-shaped ingredient rows. Gate the
+ // `catalog` category whenever the bundle carries at least one LIVE ingredient
+ // — a sender ahead on `catalog` would push forward-shaped payload an older
+ // receiver can't interpret. Tombstone-only bundles (all ingredients deleted)
+ // are id+deleted+deletedAt+updatedAt — safe at every version, so they needn't
+ // gate (same reasoning as the tombstone-record exemption above).
+ if (record.deleted !== true && isPlainObject(catalogBundle) &&
+ Array.isArray(catalogBundle.ingredients) &&
+ catalogBundle.ingredients.some((i) => i?.deleted !== true)) {
+ for (const c of (RECORD_KIND_SCHEMA_CATEGORIES['cat-ingredient'] || ['catalog'])) relevantCategories.add(c);
+ }
const fullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);
const versionDiff = scopeVersionDiff(fullDiff, [...relevantCategories]);
if (versionDiff.ahead.length > 0) {
@@ -1395,6 +1465,20 @@ export async function applyIncomingPush(payload) {
});
}
+ // Apply the bundled catalog rows (ingredients + universe→ingredient refs)
+ // through the same LWW upsert path as direct catalog sync. Same guards as the
+ // linkedCollection merge: skip for local-ephemeral records and tombstone
+ // pushes (a deleted universe's catalog refs tombstone locally on the next
+ // catalog-sync cycle; resurrecting them here would be wrong). Postgres-only
+ // and best-effort — a failure doesn't fail the push (the universe record is
+ // already merged; the receiver's backfill still derives a lossy view, and
+ // the next catalog-sync cycle reconciles the enriched rows).
+ if (!localEphemeral && record.deleted !== true && isPlainObject(catalogBundle)) {
+ await applyCatalogBundle(catalogBundle, portosMeta).catch((err) => {
+ console.log(`⚠️ peerSync: catalog bundle apply failed: ${err.message}`);
+ });
+ }
+
// Diff incoming asset manifest against local disk. We (the receiver) are
// the ones that will background-pull `missingAssets` from the sender's
// `/data/{images,image-refs,videos}/<filename>` static mount in Stage 3
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index d86ee80f5e..a279cdd8be 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -52,6 +52,20 @@ vi.mock('../../lib/peerHttpClient.js', async () => ({
peerSocketOptions: {},
}));
+// Catalog bundle deps are dynamic-imported inside the universe push/apply
+// helpers; mock the backend + DB + sync so the bundle path is exercisable
+// without Postgres. Default backend is non-postgres so existing tests see no
+// bundle; the catalog-bundle suite overrides getBackendName per-test.
+vi.mock('../memoryBackend.js', async () => ({
+ getBackendName: vi.fn(() => 'file'),
+}));
+vi.mock('../catalogDB.js', async () => ({
+ getCatalogBundleForRef: vi.fn(),
+}));
+vi.mock('../catalogSync.js', async () => ({
+ applyRemoteChanges: vi.fn(),
+}));
+
import {
PEER_SUBSCRIBABLE_KINDS,
listPeerSubscriptions,
@@ -91,6 +105,9 @@ import {
mergeMediaCollectionsFromSync,
} from '../mediaCollections.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
+import { getBackendName } from '../memoryBackend.js';
+import { getCatalogBundleForRef } from '../catalogDB.js';
+import { applyRemoteChanges as applyCatalogRemoteChanges } from '../catalogSync.js';
import { listCursors, __drainForTests as __drainCursors } from './peerTombstoneCursors.js';
let originalDataPath;
@@ -161,6 +178,11 @@ beforeEach(async () => {
vi.mocked(findCollectionByUniverseId).mockReset().mockResolvedValue(null);
vi.mocked(findCollectionBySeriesId).mockReset().mockResolvedValue(null);
vi.mocked(mergeMediaCollectionsFromSync).mockReset().mockResolvedValue({ applied: false, count: 0 });
+ // Catalog bundle defaults: non-postgres backend (no bundle), empty DB read,
+ // no-op apply. The catalog-bundle suite overrides these per-test.
+ vi.mocked(getBackendName).mockReset().mockReturnValue('file');
+ vi.mocked(getCatalogBundleForRef).mockReset().mockResolvedValue({ ingredients: [], refs: [] });
+ vi.mocked(applyCatalogRemoteChanges).mockReset().mockResolvedValue({ errors: [] });
await __resetForTests();
});
@@ -2000,6 +2022,126 @@ describe('peerSync', () => {
});
});
+ // -------------------------------------------------------------------------
+ // CATALOG BUNDLE — universe push carries referenced catalog ingredients +
+ // refs (catalog-bundled-universe-push). Assembly is gated on Postgres +
+ // non-tombstone + non-empty; the receiver applies via catalogSync.
+ // -------------------------------------------------------------------------
+ describe('catalog bundle (universe push)', () => {
+ const liveUniverse = { id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z', deleted: false, deletedAt: null };
+
+ it('bundles catalog ingredients + refs into a live universe push (Postgres)', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ vi.mocked(getUniverse).mockResolvedValue(liveUniverse);
+ vi.mocked(getCatalogBundleForRef).mockResolvedValue({
+ ingredients: [{ id: 'cat-chr-1', type: 'character', name: 'Hero', updatedAt: '2026-01-02T00:00:00Z' }],
+ refs: [{ ingredientId: 'cat-chr-1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: '2026-01-02T00:00:00Z' }],
+ });
+
+ const payload = await getRecordPayloadForPeer('universe', 'u1');
+
+ expect(getCatalogBundleForRef).toHaveBeenCalledWith('universe', 'u1');
+ expect(payload.catalogBundle).toBeDefined();
+ expect(payload.catalogBundle.ingredients).toHaveLength(1);
+ expect(payload.catalogBundle.ingredients[0].id).toBe('cat-chr-1');
+ expect(payload.catalogBundle.refs[0].refId).toBe('u1');
+ });
+
+ it('omits the bundle on a non-Postgres install (nothing to bundle)', async () => {
+ vi.mocked(getBackendName).mockReturnValue('file');
+ vi.mocked(getUniverse).mockResolvedValue(liveUniverse);
+
+ const payload = await getRecordPayloadForPeer('universe', 'u1');
+
+ expect(getCatalogBundleForRef).not.toHaveBeenCalled();
+ expect(payload.catalogBundle).toBeUndefined();
+ });
+
+ it('omits the bundle on a tombstone (deleted) universe push', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ vi.mocked(getUniverse).mockResolvedValue({ ...liveUniverse, deleted: true, deletedAt: '2026-03-01T00:00:00Z' });
+
+ const payload = await getRecordPayloadForPeer('universe', 'u1');
+
+ expect(getCatalogBundleForRef).not.toHaveBeenCalled();
+ expect(payload.catalogBundle).toBeUndefined();
+ });
+
+ it('omits the bundle key when the universe has no catalog rows', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ vi.mocked(getUniverse).mockResolvedValue(liveUniverse);
+ vi.mocked(getCatalogBundleForRef).mockResolvedValue({ ingredients: [], refs: [] });
+
+ const payload = await getRecordPayloadForPeer('universe', 'u1');
+
+ expect(payload.catalogBundle).toBeUndefined();
+ });
+
+ it('does NOT bundle catalog rows on a series push (only universe)', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Ser', updatedAt: '2026-01-01T00:00:00Z', deleted: false, deletedAt: null });
+ vi.mocked(listIssues).mockResolvedValue([]);
+
+ const payload = await getRecordPayloadForPeer('series', 's1');
+
+ expect(getCatalogBundleForRef).not.toHaveBeenCalled();
+ expect(payload.catalogBundle).toBeUndefined();
+ });
+
+ it('receiver applies a bundled catalog payload via catalogSync', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ const catalogBundle = {
+ ingredients: [{ id: 'cat-chr-1', type: 'character', name: 'Hero', updatedAt: '2026-01-02T00:00:00Z' }],
+ refs: [{ ingredientId: 'cat-chr-1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: '2026-01-02T00:00:00Z' }],
+ };
+ const portosMeta = { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS } };
+
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', name: 'Foo', deleted: false, deletedAt: null },
+ assetManifest: [],
+ catalogBundle,
+ sourceInstanceId: 'peer-a',
+ portosMeta,
+ });
+
+ expect(applyCatalogRemoteChanges).toHaveBeenCalledTimes(1);
+ const arg = vi.mocked(applyCatalogRemoteChanges).mock.calls[0][0];
+ expect(arg.ingredients).toEqual(catalogBundle.ingredients);
+ expect(arg.refs).toEqual(catalogBundle.refs);
+ // portosMeta forwarded so applyRemoteChanges can run its own gate.
+ expect(arg.portosMeta).toEqual(portosMeta);
+ });
+
+ it('receiver skips the bundle on a tombstone universe push', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', name: 'Foo', deleted: true, deletedAt: '2026-03-01T00:00:00Z' },
+ assetManifest: [],
+ catalogBundle: { ingredients: [{ id: 'cat-chr-1', type: 'character', name: 'Hero', updatedAt: '2026-01-02T00:00:00Z' }], refs: [] },
+ sourceInstanceId: 'peer-a',
+ portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS } },
+ });
+
+ expect(applyCatalogRemoteChanges).not.toHaveBeenCalled();
+ });
+
+ it('receiver rejects a universe push whose bundle ingredient is schema-ahead on catalog', async () => {
+ vi.mocked(getBackendName).mockReturnValue('postgres');
+ await expect(applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', name: 'Foo', deleted: false, deletedAt: null },
+ assetManifest: [],
+ catalogBundle: { ingredients: [{ id: 'cat-chr-1', type: 'character', name: 'Hero', updatedAt: '2026-01-02T00:00:00Z' }], refs: [] },
+ sourceInstanceId: 'peer-a',
+ portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS, catalog: PORTOS_SCHEMA_VERSIONS.catalog + 1 }, portosVersion: '99.0.0' },
+ })).rejects.toThrow(/schema is ahead/);
+ // Gated before merge — bundle apply never runs.
+ expect(applyCatalogRemoteChanges).not.toHaveBeenCalled();
+ });
+ });
+
// -------------------------------------------------------------------------
// SCHEMA-VERSION GATING — sender side (handle 409 / cooldown / clear)
// + receiver side (reject when sender ahead / pass through legacy + behind)
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index e5f3e3d772..160a1f2946 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -16,6 +16,7 @@ import { peerBaseUrl } from '../lib/peerUrl.js';
import * as brainSync from './brainSync.js';
import * as brainSyncLog from './brainSyncLog.js';
import * as memorySync from './memorySync.js';
+import * as catalogSync from './catalogSync.js';
import * as dataSync from './dataSync.js';
import { getBackendName } from './memoryBackend.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
@@ -106,13 +107,14 @@ async function syncImageFromPeer(peer, avatarPath) {
export async function getSyncStatus({ includeChecksums = false } = {}) {
const isPostgres = getBackendName() === 'postgres';
const snapshotCategories = includeChecksums ? dataSync.getSupportedCategories() : [];
- const [brainSeq, memorySeq, cursors, ...checksumResults] = await Promise.all([
+ const [brainSeq, memorySeq, catalogSeqs, cursors, ...checksumResults] = await Promise.all([
Promise.resolve(brainSyncLog.getCurrentSeq()),
isPostgres ? memorySync.getMaxSequence() : Promise.resolve(null),
+ isPostgres ? catalogSync.getMaxSequences().catch(() => null) : Promise.resolve(null),
loadCursors(),
...snapshotCategories.map(cat => dataSync.getChecksum(cat).catch(() => null))
]);
- const local = { brainSeq, memorySeq };
+ const local = { brainSeq, memorySeq, catalogSeqs };
if (includeChecksums) {
local.checksums = {};
for (let i = 0; i < snapshotCategories.length; i++) {
@@ -167,6 +169,95 @@ async function syncMemoryFromPeer(peer, cursor) {
return { memorySeq, totalApplied };
}
+// The seven INDEPENDENT BIGSERIAL cursors the catalog sync envelope tracks.
+// Each table advances its own sequence, so the receiver carries seven cursors
+// (not one) — see catalogSync.js for the protocol rationale.
+const CATALOG_CURSOR_KINDS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];
+
+// Build the `?since[scraps]=A&since[ingredients]=B&...` query string the
+// catalog `/sync` route parses back into per-kind cursors. A missing kind
+// defaults to '0' server-side, so a legacy cursor (pre-relations/tags/media)
+// still pulls the newer kinds from scratch on first run.
+function catalogSinceQuery(catalogSeqs) {
+ const parts = CATALOG_CURSOR_KINDS.map((kind) => {
+ const v = catalogSeqs?.[kind];
+ const safe = typeof v === 'string' && /^\d+$/.test(v) ? v : '0';
+ return `since[${kind}]=${encodeURIComponent(safe)}`;
+ });
+ return parts.join('&');
+}
+
+/**
+ * Sync the creative-ingredients catalog from a peer (pull all changes since
+ * cursor, apply locally). Delta-based + PostgreSQL-only, mirroring memory sync
+ * — but the catalog is a multi-table relational store, so the cursor is the
+ * per-kind `maxSequences` object the peer returns, not a single scalar.
+ *
+ * A schema-version-ahead peer (newer `catalog` schema) makes applyRemoteChanges
+ * throw CatalogSyncVersionMismatchError; we record the gap on the peer record
+ * (same surfacing as the snapshot categories) and stop draining so we don't
+ * loop on a payload we can't safely apply.
+ */
+async function syncCatalogFromPeer(peer, peerId, cursor) {
+ let catalogSeqs = isPlainObjectShallow(cursor.catalogSeqs) ? { ...cursor.catalogSeqs } : {};
+ let totalApplied = 0;
+ let blockedBySchema = null;
+
+ let hasMore = true;
+ while (hasMore) {
+ const data = await fetchPeer(peer, `/api/catalog/sync?${catalogSinceQuery(catalogSeqs)}&limit=100`);
+ if (!data) break;
+
+ // Forward the sender's portosMeta so applyRemoteChanges runs the schema
+ // gate BEFORE merging — a sender ahead on `catalog` throws and we persist
+ // the gap rather than corrupting local state.
+ let stats;
+ try {
+ stats = await catalogSync.applyRemoteChanges({ ...data, portosMeta: data.portosMeta });
+ } catch (err) {
+ if (err?.code === 'CATALOG_SCHEMA_VERSION_AHEAD') {
+ blockedBySchema = err.diff;
+ const ahead = Array.isArray(err.diff?.ahead) ? err.diff.ahead : [];
+ await recordPeerSchemaGap(peerId, 'catalog', {
+ ahead, behind: [], senderPortosVersion: data?.portosMeta?.portosVersion ?? null,
+ }).catch((e) => console.log(`⚠️ syncOrchestrator: persist catalog schema gap failed: ${e.message}`));
+ break;
+ }
+ throw err;
+ }
+
+ // Count every applied row across the seven kinds for the heartbeat log.
+ // catalogSync owns the per-kind stats shape, so it owns the tally.
+ totalApplied += catalogSync.countAppliedFromStats(stats);
+
+ // Advance every cursor the peer reported. The peer falls each quiet kind
+ // back to the inbound cursor, so this never moves a cursor backward.
+ const before = catalogSinceQuery(catalogSeqs);
+ if (isPlainObjectShallow(data.maxSequences)) {
+ for (const kind of CATALOG_CURSOR_KINDS) {
+ const v = data.maxSequences[kind];
+ if (typeof v === 'string' && /^\d+$/.test(v)) catalogSeqs[kind] = v;
+ }
+ }
+ // Guard against a buggy/malicious peer that returns `hasMore: true` without
+ // advancing ANY cursor — that would loop forever re-pulling the same window.
+ // A well-behaved peer always advances at least one kind when hasMore is true
+ // (hasMore implies it returned a full page on some table).
+ if (catalogSinceQuery(catalogSeqs) === before) break;
+ hasMore = data.hasMore === true;
+ }
+
+ // Clear any prior gap once we successfully drained (sender either upgraded
+ // or the earlier block was transient). Skip when we just recorded a fresh
+ // block this cycle.
+ if (!blockedBySchema) {
+ await clearPeerSchemaGap(peerId, 'catalog')
+ .catch((err) => console.log(`⚠️ syncOrchestrator: clear catalog schema gap failed: ${err.message}`));
+ }
+
+ return { catalogSeqs, totalApplied, blockedBySchema };
+}
+
/**
* Safely parse a value to BigInt for BIGSERIAL comparison.
* Returns 0n for invalid/empty/negative inputs.
@@ -467,6 +558,15 @@ export async function syncWithPeer(peer) {
}
}
+ // --- Catalog sync (delta-based, multi-table, PostgreSQL only) ---
+ let catalogResult = { catalogSeqs: cursor.catalogSeqs, totalApplied: 0 };
+ if (categories.catalog) {
+ const isPostgres = getBackendName() === 'postgres';
+ if (isPostgres) {
+ catalogResult = await syncCatalogFromPeer(peer, peerId, cursor);
+ }
+ }
+
// --- Snapshot-based category syncs (parallel) ---
const dataCategoryResults = {};
// We no longer skip whole categories when a peer has SOME per-record
@@ -509,6 +609,12 @@ export async function syncWithPeer(peer) {
if (!cursors[peerId]) cursors[peerId] = {};
if (categories.brain) cursors[peerId].brainSeq = brainResult.brainSeq;
if (memoryResult.memorySeq !== (cursor.memorySeq ?? '0')) cursors[peerId].memorySeq = memoryResult.memorySeq;
+ // Persist the per-kind catalog cursor only when the drain wasn't blocked
+ // by a schema gap — a blocked cycle leaves the prior cursor so we re-try
+ // the same window after the sender upgrades (mirrors the snapshot path).
+ if (categories.catalog && !catalogResult.blockedBySchema && isPlainObjectShallow(catalogResult.catalogSeqs)) {
+ cursors[peerId].catalogSeqs = catalogResult.catalogSeqs;
+ }
if (!cursors[peerId].checksums) cursors[peerId].checksums = {};
for (const [cat, result] of Object.entries(dataCategoryResults)) {
if (result.checksum) cursors[peerId].checksums[cat] = result.checksum;
@@ -520,6 +626,7 @@ export async function syncWithPeer(peer) {
const parts = [];
if (brainResult.totalApplied > 0) parts.push(`${brainResult.totalApplied} brain`);
if (memoryResult.totalApplied > 0) parts.push(`${memoryResult.totalApplied} memory`);
+ if (catalogResult.totalApplied > 0) parts.push(`${catalogResult.totalApplied} catalog`);
for (const [cat, result] of Object.entries(dataCategoryResults)) {
if (result.totalApplied > 0) parts.push(`${result.totalApplied} ${cat}`);
}
@@ -527,7 +634,7 @@ export async function syncWithPeer(peer) {
console.log(`🔄 Synced with ${peer.name}: ${parts.join(', ')} changes`);
}
- return { brain: brainResult, memory: memoryResult, ...dataCategoryResults };
+ return { brain: brainResult, memory: memoryResult, catalog: catalogResult, ...dataCategoryResults };
} finally {
syncingPeers.delete(peerId);
}
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index cfedea4c53..63c70f4806 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -11,7 +11,7 @@ vi.mock('./instances.js', () => ({
UNKNOWN_INSTANCE_ID: 'unknown',
DEFAULT_SYNC_CATEGORIES: {
brain: false, memory: false, goals: false,
- character: false, digitalTwin: false, meatspace: false
+ character: false, digitalTwin: false, meatspace: false, catalog: false
}
}));
vi.mock('./brainSyncLog.js', () => ({
@@ -25,6 +25,22 @@ vi.mock('./memorySync.js', () => ({
applyRemoteChanges: vi.fn(),
getMaxSequence: vi.fn().mockResolvedValue('0')
}));
+vi.mock('./catalogSync.js', async (importOriginal) => {
+ // Keep the real countAppliedFromStats (pure tally over the stats shape) so
+ // the orchestrator's totalApplied assertions exercise the production sum.
+ const actual = await importOriginal();
+ return {
+ countAppliedFromStats: actual.countAppliedFromStats,
+ applyRemoteChanges: vi.fn().mockResolvedValue({
+ scraps: { inserted: 0, updated: 0 }, ingredients: { inserted: 0, updated: 0 },
+ sources: { applied: 0 }, refs: { applied: 0 }, relations: { applied: 0 },
+ tags: { inserted: 0, updated: 0 }, media: { applied: 0 }, errors: []
+ }),
+ getMaxSequences: vi.fn().mockResolvedValue({
+ scraps: '0', ingredients: '0', sources: '0', refs: '0', relations: '0', tags: '0', media: '0'
+ })
+ };
+});
vi.mock('./memoryBackend.js', () => ({
getBackendName: vi.fn(() => 'postgres')
}));
@@ -61,6 +77,7 @@ vi.mock('fs/promises', () => ({
import { getPeers } from './instances.js';
import { applyRemoteChanges as applyBrainChanges } from './brainSync.js';
import { applyRemoteChanges as applyMemoryChanges } from './memorySync.js';
+import { applyRemoteChanges as applyCatalogChanges } from './catalogSync.js';
import { instanceEvents } from './instanceEvents.js';
import { syncWithPeer, syncAllPeers, initSyncOrchestrator, stopSyncOrchestrator } from './syncOrchestrator.js';
@@ -295,6 +312,111 @@ describe('syncOrchestrator', () => {
});
});
+ describe('catalog sync (delta-based, Postgres-only)', () => {
+ const catalogPeer = { ...mockPeer, syncCategories: { catalog: true } };
+
+ it('pulls /api/catalog/sync with per-kind cursors and applies locally', async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ ingredients: [{ id: 'cat-chr-1' }],
+ refs: [{ ingredientId: 'cat-chr-1', refKind: 'universe', refId: 'u1', role: 'canon-character' }],
+ maxSequences: { scraps: '0', ingredients: '7', sources: '0', refs: '3', relations: '0', tags: '0', media: '0' },
+ hasMore: false,
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ }),
+ });
+ applyCatalogChanges.mockResolvedValueOnce({
+ scraps: { inserted: 0, updated: 0 }, ingredients: { inserted: 1, updated: 0 },
+ sources: { applied: 0 }, refs: { applied: 1 }, relations: { applied: 0 },
+ tags: { inserted: 0, updated: 0 }, media: { applied: 0 }, errors: [],
+ });
+
+ const result = await syncWithPeer(catalogPeer);
+
+ const url = mockFetch.mock.calls[0][0];
+ expect(url).toContain('/api/catalog/sync?');
+ expect(url).toContain('since[ingredients]=0');
+ expect(url).toContain('since[refs]=0');
+ expect(applyCatalogChanges).toHaveBeenCalledTimes(1);
+ // inserted ingredient (1) + applied ref (1)
+ expect(result.catalog.totalApplied).toBe(2);
+ });
+
+ it('drains multiple batches via hasMore, advancing the per-kind cursor', async () => {
+ mockFetch
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ ingredients: [{ id: 'a' }],
+ maxSequences: { scraps: '0', ingredients: '5', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' },
+ hasMore: true,
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ ingredients: [{ id: 'b' }],
+ maxSequences: { scraps: '0', ingredients: '9', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' },
+ hasMore: false,
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ }),
+ });
+ applyCatalogChanges.mockResolvedValue({
+ scraps: { inserted: 0, updated: 0 }, ingredients: { inserted: 1, updated: 0 },
+ sources: { applied: 0 }, refs: { applied: 0 }, relations: { applied: 0 },
+ tags: { inserted: 0, updated: 0 }, media: { applied: 0 }, errors: [],
+ });
+
+ const result = await syncWithPeer(catalogPeer);
+
+ expect(applyCatalogChanges).toHaveBeenCalledTimes(2);
+ expect(result.catalog.totalApplied).toBe(2);
+ // Second pull must carry the cursor from the first batch.
+ const secondUrl = mockFetch.mock.calls[1][0];
+ expect(secondUrl).toContain('since[ingredients]=5');
+ // Final cursor advanced to the last batch's max.
+ expect(result.catalog.catalogSeqs.ingredients).toBe('9');
+ });
+
+ it('records a schema gap and stops draining when the sender is ahead on catalog', async () => {
+ mockFetch.mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ ingredients: [{ id: 'x' }],
+ maxSequences: { scraps: '0', ingredients: '5', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' },
+ hasMore: true,
+ portosMeta: { schemaVersions: { catalog: 99 }, portosVersion: '99.0.0' },
+ }),
+ });
+ const mismatch = new Error('catalog ahead');
+ mismatch.code = 'CATALOG_SCHEMA_VERSION_AHEAD';
+ mismatch.diff = { ahead: [{ category: 'catalog', senderV: 99, receiverV: 1 }], behind: [] };
+ applyCatalogChanges.mockRejectedValueOnce(mismatch);
+
+ const { updatePeer } = await import('./instances.js');
+ getPeers.mockResolvedValue([{ ...catalogPeer, id: 'local-peer-row', instanceId: catalogPeer.instanceId }]);
+
+ const result = await syncWithPeer(catalogPeer);
+
+ // Only one apply attempt — we stop draining on the block (no hasMore loop).
+ expect(applyCatalogChanges).toHaveBeenCalledTimes(1);
+ expect(result.catalog.blockedBySchema).toBeTruthy();
+ // Gap persisted on the local peer row under schemaGaps.catalog.
+ expect(updatePeer).toHaveBeenCalledWith(
+ 'local-peer-row',
+ expect.objectContaining({
+ schemaGaps: expect.objectContaining({
+ catalog: expect.objectContaining({
+ ahead: [{ category: 'catalog', senderV: 99, receiverV: 1 }],
+ }),
+ }),
+ }),
+ );
+ });
+ });
+
describe('categoriesCoveredByPeerSync (per-direction coverage)', () => {
it('returns outbound from our local subs, grouped by snapshot category', async () => {
const peerSync = await import('./sharing/peerSync.js');