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
fix: preserve Catalog parent links across sync pages (#8683)
[._.]/ Adam Eivy3e6742837616
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 0d5560ea49..c5f997a1eb 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -30,6 +30,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](**Where it lives.** PostgreSQL via `server/lib/db.js` + `server/scripts/init-db.sql`. Service modules own the storage adapter (e.g. `server/services/catalogDB.js`, `server/services/memoryDB.js`).**Examples.**+- `catalog_pending_applies` — receiver-local, db-primary inbox for Catalog tags/scraps arriving before their parents. Full wire rows and source timestamps survive restart; duplicate delivery coalesces by kind/id, and ready rows drain under normal LWW. Not exported to peers or user lists; no binary assets or TTL (unresolved data must not expire). Covered by PostgreSQL backup. Boot DDL and DB migration 011 install the empty store without a seed.- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.- `catalog_ingredient_refs` — homing links from an ingredient to the universe/series/creative-director/issue/work that consumes it. Since #7615, `POST /scraps/:id/commit` (the paste→extract→review ingest flow, plus bulk-import's long-standing `defaults.universeRef`) writes one `ref_kind='universe'` row per committed ingredient in the same transaction as the ingredient insert — the role is derived from the ingredient's type (`universeRefRoleForType` in `server/services/catalogDB/refs.js`) unless the caller overrides it. Omitting `universeRef` at commit time leaves the ingredient unlinked (the catalog's "Raw" bucket), exactly as before #7615.- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges. Scrap commits with explicit `relationships` write only the reviewed edges (including none for `[]`), atomically with ingredients, source links, and universe refs. Legacy callers omitting the field still receive one `related-to` edge per unordered pair in batches of 2–25. The additive graph API is documented in [API.md](API.md#catalog-scrap-graph-commits).diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 8da2305f85..c54424e51a 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -32,7 +32,7 @@ init-db.sql, each with a one-line reason.| `reviewQueueTriage.js` | `reviewQueueTriageDdl` | Machine-local Review Hub presentation markers — snooze, optional dismissal, and delivery generation keyed by canonical action identity || `cosAgentFeedback.js` | `cosAgentFeedbackDdl` | Durable machine-local references to completed manual CoS runs awaiting a rating (agent id + archive locator only) || `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) |-| `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types |+| `catalog.js` | `catalogDdl`, `catalogUserTypesDdl`, `catalogPendingAppliesDdl` | Catalog scraps/ingredients/tags/media + user-defined types + receiver-local dependency inbox || `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets, and Code Animation jobs || `universes.js` | `universesDdl` | Universes, machine-local character voice profiles/renders, + universe run history || `library.js` | `libraryDdl` | Authors, artists, albums, tracks |diff --git a/server/lib/db/schema/catalog.js b/server/lib/db/schema/catalog.jsindex fd53caa5d9..ec51a878ca 100644--- a/server/lib/db/schema/catalog.js+++ b/server/lib/db/schema/catalog.js@@ -6,7 +6,19 @@// catalog_user_types is a separate export because in the original array it sits// AFTER the media block, not adjacent to the other catalog tables — the composer// (index.js) inserts it at that same position so the DDL order is byte-identical.+export const catalogPendingAppliesDdl = [+ `CREATE TABLE IF NOT EXISTS catalog_pending_applies (+ kind TEXT NOT NULL CHECK (kind IN ('tags', 'scraps')),+ id TEXT NOT NULL,+ parent_id TEXT NOT NULL,+ source_updated_at TIMESTAMPTZ NOT NULL,+ payload JSONB NOT NULL,+ PRIMARY KEY (kind, id)+ )`,+];+export const catalogDdl = [+ ...catalogPendingAppliesDdl,`CREATE TABLE IF NOT EXISTS catalog_scraps (id TEXT PRIMARY KEY,title TEXT,diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex 2c1f795cc1..54f9212ef4 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -22,7 +22,7 @@ import { userActionsDdl } from './userActions.js';import { reviewQueueTriageDdl } from './reviewQueueTriage.js';import { cosAgentFeedbackDdl } from './cosAgentFeedback.js';import { aiGraphDdl } from './aiGraph.js';-import { catalogDdl, catalogUserTypesDdl } from './catalog.js';+import { catalogDdl, catalogUserTypesDdl, catalogPendingAppliesDdl } from './catalog.js';import { mediaDdl } from './media.js';import { universesDdl } from './universes.js';import { libraryDdl } from './library.js';@@ -50,6 +50,7 @@ export {aiGraphDdl,catalogDdl,catalogUserTypesDdl,+ catalogPendingAppliesDdl,mediaDdl,universesDdl,libraryDdl,diff --git a/server/scripts/db-migrations/011-catalog-pending-applies.js b/server/scripts/db-migrations/011-catalog-pending-applies.jsnew file mode 100644index 0000000000..aba04e5c2c--- /dev/null+++ b/server/scripts/db-migrations/011-catalog-pending-applies.js@@ -0,0 +1,6 @@+// Receiver-local durable inbox; no source records or replay cursors are changed.+import { catalogPendingAppliesDdl } from '../../lib/db/schema/catalog.js';++export async function up(client) {+ for (const statement of catalogPendingAppliesDdl) await client.query(statement);+}diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 0be3ef6cfa..d0c6341861 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -2243,3 +2243,13 @@ DROP TRIGGER IF EXISTS trg_catalog_ingredient_media_sync_feed ON catalog_ingrediCREATE CONSTRAINT TRIGGER trg_catalog_ingredient_media_sync_feed AFTER INSERT OR DELETE ON catalog_ingredient_media DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();DROP TRIGGER IF EXISTS trg_catalog_ingredient_media_sync_feed_update ON catalog_ingredient_media;CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_media_sync_feed_update AFTER UPDATE ON catalog_ingredient_media DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();++-- Durable receiver-local Catalog dependency inbox (#8683).+CREATE TABLE IF NOT EXISTS catalog_pending_applies (+ kind TEXT NOT NULL CHECK (kind IN ('tags', 'scraps')),+ id TEXT NOT NULL,+ parent_id TEXT NOT NULL,+ source_updated_at TIMESTAMPTZ NOT NULL,+ payload JSONB NOT NULL,+ PRIMARY KEY (kind, id)+ );diff --git a/server/services/catalogDB.tags.test.js b/server/services/catalogDB.tags.test.jsindex a5b9b4f982..ec8e7049d4 100644--- a/server/services/catalogDB.tags.test.js+++ b/server/services/catalogDB.tags.test.js@@ -2,7 +2,7 @@* Unit tests for the catalog tag-taxonomy DB helpers (`normalizeTags`,* `upsertTagFromPeer`). Postgres is mocked with an in-memory `catalog_tags`* map so the suite runs without a live database — we assert on the canonical- * dedup behavior + first-write-wins casing + the peer parent-less retry.+ * dedup behavior + first-write-wins casing + durable peer deferral.*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -38,6 +38,7 @@ vi.mock('../lib/db.js', () => ({failParentFkOnce = false;const err = new Error('insert or update violates foreign key constraint');err.code = '23503';+ err.constraint = 'catalog_tags_parent_id_fkey';throw err;}const isInsert = !tagStore.has(id);@@ -127,14 +128,28 @@ describe('upsertTagFromPeer', () => {expect(tagStore.get('cat-tag-noir').label).toBe('Noir');});- it('retries parent-less on an FK violation so the child row still lands', async () => {+ it('durably defers a missing-parent row without materializing a flattened child', async () => {failParentFkOnce = true; // first attempt (with parent) throws 23503const res = await upsertTagFromPeer({id: 'cat-tag-child', label: 'Child', parentId: 'cat-tag-missing',createdAt: 't', updatedAt: 't',});- expect(res.applied).toBe(true);- // Row landed with a null parent (the parent can re-link on a later page).- expect(tagStore.get('cat-tag-child').parentId).toBeNull();+ expect(res).toEqual({ applied: false, isInsert: false, deferred: true });+ expect(tagStore.has('cat-tag-child')).toBe(false);+ expect(query).toHaveBeenLastCalledWith(+ expect.stringContaining('INSERT INTO catalog_pending_applies'),+ ['tags', 'cat-tag-child', 'cat-tag-missing', 't', expect.stringContaining('"parentId":"cat-tag-missing"')],+ );});+ it('rejects the child when the durable inbox write fails', async () => {+ failParentFkOnce = true;+ const original = query.getMockImplementation();+ query.mockImplementationOnce(original).mockRejectedValueOnce(new Error('inbox unavailable'));+ await expect(upsertTagFromPeer({+ id: 'cat-tag-child', label: 'Child', parentId: 'cat-tag-missing',+ createdAt: 't', updatedAt: 't',+ })).rejects.toThrow('inbox unavailable');+ expect(tagStore.has('cat-tag-child')).toBe(false);+ });+});diff --git a/server/services/catalogDB/sync.js b/server/services/catalogDB/sync.jsindex 289cdc68e9..970827181f 100644--- a/server/services/catalogDB/sync.js+++ b/server/services/catalogDB/sync.js@@ -6,7 +6,7 @@* outbound pulls; the `upsert*FromPeer` writers apply an inbound peer's rows. Mixed-* version federation is handled per-table: "tombstone keys absent" is treated* as "peer has no opinion" so a pre-tombstone peer can't revive a local delete,- * and FK-lagged child/parent rows retry parent-less then re-link on a later page.+ * and FK-lagged children are durably deferred until their parents arrive.** The three tuple-unique kinds (refs, relations, media) additionally gate* their tombstone/revival apply on an `updated_at` change-clock (#8347): a@@ -159,12 +159,8 @@ export const getTagChangesSince = (since = '0', limit = 100) =>getFeedChangesSince('catalog_tags', rowToTag, since, limit);export async function upsertTagFromPeer(tag) {- // LWW on updated_at for the mutable fields (description/color/parent_id) +- // label. `parent_id` may FK to a tag that hasn't arrived yet in this envelope- // — the receiver orders tags before ingredients, but a parent can still lag a- // child across pages. We retry parent-less first: NULL the parent on FK- // violation so the child row still lands, and a later page carrying the- // parent re-runs this upsert (LWW) to restore the link.+ // Never materialize a child with a different parent: an equal-clock replay+ // cannot repair that under LWW. Persist the complete row on missing-parent FK.const apply = async (parentId) => query(`INSERT INTO catalog_tags(id, label, description, color, parent_id, created_at, updated_at)@@ -191,9 +187,10 @@ export async function upsertTagFromPeer(tag) {try {result = await apply(tag.parentId ?? null);} catch (err) {- // 23503 = foreign_key_violation (parent not present yet). Retry parent-less.- if (err?.code === '23503' && (tag.parentId ?? null) !== null) {- result = await apply(null);+ // A durable inbox write must succeed before this row is cursor-safe.+ if (err?.code === '23503' && err.constraint === 'catalog_tags_parent_id_fkey' && (tag.parentId ?? null) !== null) {+ await deferParentApply('tags', tag, tag.parentId, tag.updatedAt || tag.createdAt);+ return { applied: false, isInsert: false, deferred: true };} else {throw err;}@@ -232,12 +229,7 @@ export const getRefChangesSince = (since = '0', limit = 100) =>getFeedChangesSince('catalog_ingredient_refs', rowToRef, since, limit);export async function upsertScrapFromPeer(scrap) {- // A child scrap (parent_scrap_id set) may arrive in the envelope BEFORE its- // parent row — the sync apply path sorts parents first within one envelope,- // but a parent can still lag a child across pagination pages. Mirror the- // catalog_tags parent-less retry: on FK violation, NULL the parent so the- // child still lands, and a later page carrying the parent re-runs this upsert- // (LWW) to restore the link. chunk_index has no FK, so it always rides.+ // Cross-page children remain in the durable inbox, not the top-level list.const apply = async (parentScrapId) => query(`INSERT INTO catalog_scraps(id, title, raw_text, source_kind, metadata, embedding, embedding_model,@@ -280,9 +272,10 @@ export async function upsertScrapFromPeer(scrap) {try {result = await apply(parentId);} catch (err) {- // 23503 = foreign_key_violation (parent not present yet). Retry parent-less.- if (err?.code === '23503' && parentId !== null) {- result = await apply(null);+ // A durable inbox write must succeed before this row is cursor-safe.+ if (err?.code === '23503' && err.constraint === 'catalog_scraps_parent_scrap_id_fkey' && parentId !== null) {+ await deferParentApply('scraps', scrap, parentId, scrap.updatedAt);+ return { applied: false, isInsert: false, deferred: true };} else {throw err;}@@ -397,3 +390,54 @@ export async function upsertRefFromPeer(ref) {);}}++// The inbox is db-primary, receiver-local, and covered by the normal DB backup.+// Its key coalesces duplicate delivery; source clocks prevent an older replay+// from replacing a newer deferred edit. No success is returned before commit.+async function deferParentApply(kind, row, parentId, updatedAt) {+ await query(+ `INSERT INTO catalog_pending_applies (kind, id, parent_id, source_updated_at, payload)+ VALUES ($1, $2, $3, $4, $5::jsonb)+ ON CONFLICT (kind, id) DO UPDATE SET+ parent_id = EXCLUDED.parent_id,+ source_updated_at = EXCLUDED.source_updated_at,+ payload = EXCLUDED.payload+ WHERE EXCLUDED.source_updated_at > catalog_pending_applies.source_updated_at`,+ [kind, row.id, parentId, updatedAt, JSON.stringify(row)],+ );+}++export async function drainPendingCatalogApplies() {+ // No in-memory ownership: every apply (even an empty page after restart)+ // recovers ready rows. Iterate so a multi-level hierarchy drains completely.+ for (const [kind, table, upsert] of [+ ['tags', 'catalog_tags', upsertTagFromPeer],+ ['scraps', 'catalog_scraps', upsertScrapFromPeer],+ ]) {+ let progressed;+ do {+ progressed = false;+ const { rows } = await query(+ `SELECT p.id, p.payload FROM catalog_pending_applies p+ WHERE p.kind = $1 AND (+ EXISTS (SELECT 1 FROM ${table} parent WHERE parent.id = p.parent_id)+ OR EXISTS (SELECT 1 FROM ${table} current+ WHERE current.id = p.id AND current.updated_at >= p.source_updated_at))+ ORDER BY p.id LIMIT 100`,+ [kind],+ );+ for (const pending of rows) {+ const result = await upsert(pending.payload);+ if (result.deferred) continue; // parent deleted since the readiness query+ // Crash after apply is safe (LWW replay); compare payload so concurrent+ // delivery of a newer deferred edit cannot be deleted by this drain.+ const removed = await query(+ `DELETE FROM catalog_pending_applies+ WHERE kind = $1 AND id = $2 AND payload = $3::jsonb`,+ [kind, pending.id, JSON.stringify(pending.payload)],+ );+ progressed ||= removed.rowCount > 0;+ }+ } while (progressed);+ }+}diff --git a/server/services/catalogSync.js b/server/services/catalogSync.jsindex 0cffff291f..ecd4ba1671 100644--- a/server/services/catalogSync.js+++ b/server/services/catalogSync.js@@ -46,6 +46,7 @@ import {upsertRelationFromPeer,upsertTagFromPeer,upsertMediaFromPeer,+ drainPendingCatalogApplies,normalizeTags,} from './catalogDB.js';import { compareSchemaVersions, scopeVersionDiff, formatVersionGap, catalogEnvelopeHasLiveRows, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';@@ -190,7 +191,8 @@ export async function applyRemoteChanges(envelope = {}) {try {res = await upsertFn(item);if (lww) {- if (!res.applied) tally.skipped++;+ if (res.deferred) tally.deferred = (tally.deferred || 0) + 1;+ else if (!res.applied) tally.skipped++;else if (res.isInsert) tally.inserted++;else tally.updated++;} else {@@ -276,8 +278,8 @@ export async function applyRemoteChanges(envelope = {}) {return { ...ing, tags: registered };};- // Tags first — they carry a `parent_id` self-FK (handled by the parent-less- // retry in upsertTagFromPeer) and are referenced by the freeform tag arrays+ // Tags first — they carry a `parent_id` self-FK (durably deferred by+ // upsertTagFromPeer) and are referenced by the freeform tag arrays// on ingredients, so we want the canonical rows present before the ingredient// rows land. They have no FK to scraps/ingredients, so ordering is otherwise// free.@@ -290,8 +292,8 @@ export async function applyRemoteChanges(envelope = {}) {// join rows land). Chunked scraps self-FK: a child carries// `parentScrapId` → another scrap row, so order PARENT rows (no// parentScrapId) before CHILD rows within this envelope to avoid an FK- // violation on the child insert. (`upsertScrapFromPeer` also retries- // parent-less on FK error to cover a parent lagging across pages.)+ // violation on the child insert. (`upsertScrapFromPeer` durably defers+ // children whose parent is on a later page.)const orderedScraps = Array.isArray(envelope.scraps)? [...envelope.scraps].sort((a, b) => {const aChild = a?.parentScrapId ? 1 : 0;@@ -304,6 +306,10 @@ export async function applyRemoteChanges(envelope = {}) {errLabel: 'scrap', idFor: (s) => s?.id,});+ // Also runs on empty envelopes: persisted dependencies survive restarts.+ // Complete scraps before source joins attempt their FK-dependent writes.+ await drainPendingCatalogApplies();+await applyKind({items: envelope.ingredients, upsertFn: upsertIngredientFromPeer, tally: stats.ingredients, lww: true,errLabel: 'ingredient', idFor: (i) => i?.id, prepare: friendlifyIngredientTagsBeforeApply,diff --git a/server/services/catalogSync.pendingParents.db.test.js b/server/services/catalogSync.pendingParents.db.test.jsnew file mode 100644index 0000000000..91f212bb88--- /dev/null+++ b/server/services/catalogSync.pendingParents.db.test.js@@ -0,0 +1,127 @@+/**+ * #8683: real FK/LWW behavior through the public sync apply boundary.+ * Only runs against the guarded test DB. Each test owns uniquely named rows.+ */+import { afterAll, describe, expect, it } from 'vitest';+import { randomUUID } from 'node:crypto';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { checkHealth, close, ensureSchema, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';+import { applyRemoteChanges } from './catalogSync.js';+import { getScrap, listScraps } from './catalogDB/scraps.js';+import { up as migrateInbox } from '../scripts/db-migrations/011-catalog-pending-applies.js';++const health = await checkHealth();+const ready = requireDbOrSkip('catalogSync.pendingParents', health.connected, health.error);+if (ready) await ensureSchema();+const prefix = `pending-test-${randomUUID()}`;+const clock = '2026-01-01T00:00:00.000Z';+const later = '2026-01-02T00:00:00.000Z';+const envelope = (kind, rows) => ({+ [kind]: rows, portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },+});+const childRow = (kind, id, parentId, updatedAt = clock) => kind === 'tags'+ ? { id, label: id, description: 'Child description', color: '#112233', parentId, createdAt: clock, updatedAt }+ : { id, title: id, rawText: 'Example chunk text', metadata: { example: true }, chunkIndex: 1,+ parentScrapId: parentId, createdAt: clock, updatedAt };+const tableFor = (kind) => kind === 'tags' ? 'catalog_tags' : 'catalog_scraps';+const parentFor = (kind) => kind === 'tags' ? 'parent_id' : 'parent_scrap_id';+const saved = async (kind, id) => (await query(`SELECT * FROM ${tableFor(kind)} WHERE id = $1`, [id])).rows[0];+const pending = async (id) => (await query('SELECT * FROM catalog_pending_applies WHERE id = $1', [id])).rows;++afterAll(async () => {+ if (!ready) return;+ await query('DELETE FROM catalog_pending_applies WHERE id LIKE $1', [`${prefix}%`]);+ await query('DELETE FROM catalog_tags WHERE id LIKE $1', [`${prefix}%`]);+ await query('DELETE FROM catalog_scraps WHERE id LIKE $1', [`${prefix}%`]);+ await close();+});++describe.skipIf(!ready)('durable Catalog parent deferral', () => {+ it.each(['tags', 'scraps'])('reaches a later %s page after deferral and recovers in a fresh process', async (kind) => {+ const id = `${prefix}-${kind}-paged-child`;+ const parentId = `${id}-parent`;+ const child = childRow(kind, id, parentId);+ // Re-running the additive migration must not discard deferred payloads.+ const pageOne = await applyRemoteChanges(envelope(kind, [child]));+ expect(pageOne[kind]).toMatchObject({ failed: 0, deferred: 1, inserted: 0, updated: 0 });+ expect(await saved(kind, id)).toBeUndefined();+ expect((await pending(id))[0].payload).toEqual(child);+ await migrateInbox({ query });+ expect((await pending(id))[0].payload).toEqual(child);+ if (kind === 'scraps') {+ expect(await getScrap(id)).toBeNull();+ expect((await listScraps({ limit: 10000 })).items.some((row) => row.id === id)).toBe(false);+ }++ // failed=0 lets the real pull caller advance this kind's page cursor.+ // A fresh Node process has no module state from page one; it receives ONLY+ // the later parent page, with no replay or source edit of the child.+ const parent = childRow(kind, parentId, null, later);+ const code = `+ import { applyRemoteChanges } from './services/catalogSync.js';+ import { close } from './lib/db.js';+ try { await applyRemoteChanges(JSON.parse(process.argv[1])); }+ finally { await close(); }+ `;+ await promisify(execFile)(process.execPath, ['--input-type=module', '-e', code, JSON.stringify(envelope(kind, [parent]))], {+ cwd: new URL('..', import.meta.url), timeout: 20000,+ env: { ...process.env, NODE_ENV: 'test', PGDATABASE: process.env.PGDATABASE },+ });+ const stored = await saved(kind, id);+ expect(stored[parentFor(kind)]).toBe(parentId);+ expect(stored.updated_at.toISOString()).toBe(clock);+ if (kind === 'scraps') {+ expect(stored.chunk_index).toBe(1);+ expect(stored.raw_text).toBe(child.rawText);+ } else {+ expect(stored.description).toBe(child.description);+ expect(stored.color).toBe(child.color);+ }+ expect(await pending(id)).toEqual([]);+ const replay = await applyRemoteChanges(envelope(kind, [child, parent]));+ expect(replay[kind]).toMatchObject({ failed: 0, inserted: 0, updated: 0, skipped: 2 });+ expect((await saved(kind, id))[parentFor(kind)]).toBe(parentId);+ });++ it.each(['tags', 'scraps'])('coalesces %s replays and lets a newer local edit supersede pending data', async (kind) => {+ const id = `${prefix}-${kind}-stale-child`;+ const child = childRow(kind, id, `${id}-parent`);+ await applyRemoteChanges(envelope(kind, [child, { ...child, updatedAt: later }, child]));+ expect(await pending(id)).toHaveLength(1);+ expect((await pending(id))[0].payload.updatedAt).toBe(later);++ // Simulate a local record edit before the pending parent arrives. It must+ // retain its newer content AND deliberate parent removal.+ if (kind === 'tags') {+ await query('INSERT INTO catalog_tags (id, label, updated_at) VALUES ($1, $2, $3)',+ [id, 'Newer local label', '2026-01-03T00:00:00Z']);+ } else {+ await query('INSERT INTO catalog_scraps (id, raw_text, updated_at) VALUES ($1, $2, $3)',+ [id, 'Newer local text', '2026-01-03T00:00:00Z']);+ }+ await applyRemoteChanges({});+ expect(await pending(id)).toEqual([]);+ const stored = await saved(kind, id);+ expect(stored[parentFor(kind)]).toBeNull();+ expect(kind === 'tags' ? stored.label : stored.raw_text).toBe(kind === 'tags' ? 'Newer local label' : 'Newer local text');+ });++ it('drains a multilevel hierarchy and recovers an apply committed before inbox acknowledgement', async () => {+ const ids = ['leaf', 'middle', 'root'].map((part) => `${prefix}-chain-${part}`);+ await applyRemoteChanges(envelope('tags', [childRow('tags', ids[0], ids[1]), childRow('tags', ids[1], ids[2])]));+ await applyRemoteChanges(envelope('tags', [childRow('tags', ids[2], null)]));+ expect((await saved('tags', ids[0])).parent_id).toBe(ids[1]);+ expect((await saved('tags', ids[1])).parent_id).toBe(ids[2]);+ const row = childRow('tags', ids[0], ids[1]);+ await query(+ 'INSERT INTO catalog_pending_applies (kind, id, parent_id, source_updated_at, payload) VALUES ($1, $2, $3, $4, $5::jsonb)',+ ['tags', row.id, row.parentId, row.updatedAt, JSON.stringify(row)],+ );+ await applyRemoteChanges({});+ expect(await pending(row.id)).toEqual([]);+ expect((await saved('tags', row.id)).parent_id).toBe(row.parentId);+ });+});diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.jsindex 1231dfc3af..8b8e88dde4 100644--- a/server/services/catalogSync.test.js+++ b/server/services/catalogSync.test.js@@ -13,6 +13,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';vi.mock('./catalogDB.js', () => ({+ drainPendingCatalogApplies: vi.fn(async () => {}),getScrapChangesSince: vi.fn(),getIngredientChangesSince: vi.fn(),getSourceChangesSince: vi.fn(),diff --git a/server/services/catalogSync.userTypes.test.js b/server/services/catalogSync.userTypes.test.jsindex 5f530ca935..6192759681 100644--- a/server/services/catalogSync.userTypes.test.js+++ b/server/services/catalogSync.userTypes.test.js@@ -18,6 +18,7 @@ vi.mock('./settings.js', () => ({// catalogDB upserts/changes are no-ops here — we only exercise the catalogTypes// path, but applyRemoteChanges dispatches every kind, so stub them all.vi.mock('./catalogDB.js', () => ({+ drainPendingCatalogApplies: vi.fn(async () => {}),getScrapChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),getIngredientChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),getSourceChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 83d3bb92a3..66480c2c25 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -629,6 +629,29 @@ describe('syncOrchestrator', () => {expect(applyCatalogChanges).toHaveBeenCalledTimes(1);});+ it('advances durably deferred child cursors to reach later tag and scrap parent pages', async () => {+ for (const position of ['1', '2']) {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ maxSequences: { tags: position, scraps: position }, hasMore: position === '1',+ }),+ });+ }+ applyCatalogChanges+ .mockResolvedValueOnce({+ tags: { deferred: 1, failed: 0 }, scraps: { deferred: 1, failed: 0 },+ })+ .mockResolvedValueOnce({+ tags: { inserted: 1, failed: 0 }, scraps: { inserted: 1, failed: 0 },+ });+ const result = await syncWithPeer(catalogPeer);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(mockFetch.mock.calls[1][0]).toContain('since[tags]=1');+ expect(mockFetch.mock.calls[1][0]).toContain('since[scraps]=1');+ expect(result.catalog.catalogSeqs).toMatchObject({ tags: '2', scraps: '2' });+ });+it('holds a kind cursor when that kind had apply failures (parent on a later page)', async () => {// A ref fails because its parent ingredient is on a later page; the// ingredient itself applies cleanly in the same batch.diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 7da788116e..2f80c4e8e2 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -24,6 +24,7 @@ export const DB_TEST_INCLUDE = ['services/catalogDB.test.js','services/catalogDB.facets.db.test.js','services/catalogSync.tombstoneRevival.db.test.js',+ 'services/catalogSync.pendingParents.db.test.js','services/humanActivity.db.test.js','services/postRunDb.db.test.js','services/userActions.db.test.js',