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

test(catalog): add Zod + sync + DDL parity guards for the catalog stack

[._.]/ Adam Eivy21bdd7153700
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
new file mode 100644
index 0000000000..4c0c62cd04
--- /dev/null
+++ b/server/lib/catalogValidation.test.js
@@ -0,0 +1,241 @@
+/**
+ * Zod boundary tests for the Creative Ingredients Catalog validators.
+ * Pure — no DB, no LLM.
+ *
+ * The catalog routes lean entirely on these schemas as the contract between
+ * client/peer input and the DB layer. A regression that loosens (or breaks)
+ * one of these gates would land an unbounded blob in Postgres. Boundary tests
+ * are cheap and exercise the exact failure modes the schema was written for.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ INGREDIENT_TYPES,
+ REF_KINDS,
+ catalogScrapCreateSchema,
+ catalogIngredientCreateSchema,
+ catalogIngredientPatchSchema,
+ catalogIngredientQuerySchema,
+ catalogIngredientLinkSchema,
+ catalogScrapCommitSchema,
+ catalogSyncEnvelopeSchema,
+} from './catalogValidation.js';
+
+describe('catalogValidation — ingredient types & ref kinds', () => {
+ it('exposes the six v1 ingredient types as a frozen list', () => {
+ expect(INGREDIENT_TYPES).toEqual(['character', 'place', 'object', 'idea', 'scene', 'concept']);
+ expect(Object.isFrozen(INGREDIENT_TYPES)).toBe(true);
+ });
+
+ it('exposes the documented ref kinds (universe/series/issue/work/creative-director)', () => {
+ expect(REF_KINDS).toEqual(['universe', 'series', 'issue', 'work', 'creative-director']);
+ expect(Object.isFrozen(REF_KINDS)).toBe(true);
+ });
+});
+
+describe('catalogValidation — catalogScrapCreateSchema', () => {
+ it('accepts a minimal paste body', () => {
+ const out = catalogScrapCreateSchema.parse({ rawText: 'hello world' });
+ expect(out.rawText).toBe('hello world');
+ });
+
+ it('rejects empty rawText', () => {
+ expect(() => catalogScrapCreateSchema.parse({ rawText: '' })).toThrow();
+ });
+
+ it('rejects rawText over 2MB', () => {
+ const huge = 'a'.repeat(2_000_001);
+ expect(() => catalogScrapCreateSchema.parse({ rawText: huge })).toThrow();
+ });
+
+ it('accepts known sourceKinds', () => {
+ for (const k of ['paste', 'brain-bridge', 'importer-handoff', 'manual']) {
+ expect(() => catalogScrapCreateSchema.parse({ rawText: 'x', sourceKind: k })).not.toThrow();
+ }
+ });
+
+ it('rejects unknown sourceKinds (strict enum)', () => {
+ expect(() => catalogScrapCreateSchema.parse({ rawText: 'x', sourceKind: 'firehose' })).toThrow();
+ });
+
+ it('rejects extra keys (strict)', () => {
+ expect(() => catalogScrapCreateSchema.parse({ rawText: 'x', sneaky: true })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogIngredientCreateSchema', () => {
+ it('accepts every v1 type', () => {
+ for (const t of INGREDIENT_TYPES) {
+ const out = catalogIngredientCreateSchema.parse({ type: t, name: 'X' });
+ expect(out.type).toBe(t);
+ }
+ });
+
+ it('rejects an unknown type (gates the 7th-type addition)', () => {
+ expect(() => catalogIngredientCreateSchema.parse({ type: 'faction', name: 'X' })).toThrow();
+ });
+
+ it('trims + requires name', () => {
+ expect(() => catalogIngredientCreateSchema.parse({ type: 'idea', name: ' ' })).toThrow();
+ const out = catalogIngredientCreateSchema.parse({ type: 'idea', name: ' Hello ' });
+ expect(out.name).toBe('Hello');
+ });
+
+ it('caps payload at 200KB stringified', () => {
+ const big = { blob: 'x'.repeat(210_000) };
+ expect(() => catalogIngredientCreateSchema.parse({ type: 'idea', name: 'X', payload: big })).toThrow();
+ });
+
+ it('accepts a payload near the cap', () => {
+ const ok = { blob: 'x'.repeat(190_000) };
+ expect(() => catalogIngredientCreateSchema.parse({ type: 'idea', name: 'X', payload: ok })).not.toThrow();
+ });
+});
+
+describe('catalogValidation — catalogIngredientPatchSchema', () => {
+ it('accepts a tag-only patch', () => {
+ const out = catalogIngredientPatchSchema.parse({ tags: ['noir'] });
+ expect(out.tags).toEqual(['noir']);
+ });
+
+ it('rejects extra keys', () => {
+ expect(() => catalogIngredientPatchSchema.parse({ name: 'X', extra: 1 })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogIngredientQuerySchema', () => {
+ it('coerces numeric limit/offset', () => {
+ const out = catalogIngredientQuerySchema.parse({ limit: '50', offset: '0' });
+ expect(out.limit).toBe(50);
+ expect(out.offset).toBe(0);
+ });
+
+ it('caps limit at 200', () => {
+ expect(() => catalogIngredientQuerySchema.parse({ limit: '500' })).toThrow();
+ });
+
+ it('rejects negative offset', () => {
+ expect(() => catalogIngredientQuerySchema.parse({ offset: '-1' })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogIngredientLinkSchema', () => {
+ it('accepts every ref kind', () => {
+ for (const k of REF_KINDS) {
+ expect(() =>
+ catalogIngredientLinkSchema.parse({ refKind: k, refId: 'r1', role: 'canon-character' }),
+ ).not.toThrow();
+ }
+ });
+
+ it('rejects unknown ref kind', () => {
+ expect(() =>
+ catalogIngredientLinkSchema.parse({ refKind: 'galaxy', refId: 'r1', role: 'canon' }),
+ ).toThrow();
+ });
+
+ it('caps refId at 120 chars', () => {
+ expect(() =>
+ catalogIngredientLinkSchema.parse({ refKind: 'universe', refId: 'a'.repeat(200), role: 'canon-character' }),
+ ).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogScrapCommitSchema', () => {
+ it('accepts an empty accepted list (user rejected every draft)', () => {
+ const out = catalogScrapCommitSchema.parse({ accepted: [] });
+ expect(out.accepted).toEqual([]);
+ });
+
+ it('rejects more than 200 accepted drafts', () => {
+ const many = Array.from({ length: 201 }, (_, i) => ({ type: 'idea', name: `n${i}` }));
+ expect(() => catalogScrapCommitSchema.parse({ accepted: many })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogSyncEnvelopeSchema', () => {
+ const isoNow = '2026-05-29T00:00:00.000Z';
+
+ it('accepts a minimal scraps-only envelope', () => {
+ const env = {
+ scraps: [{ id: 'cat-scrap-1', rawText: 'hi', createdAt: isoNow, updatedAt: isoNow }],
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).not.toThrow();
+ });
+
+ it('accepts an ingredients envelope with v2 tombstone fields', () => {
+ const env = {
+ ingredients: [
+ {
+ id: 'cat-chr-1',
+ type: 'character',
+ name: 'X',
+ createdAt: isoNow,
+ updatedAt: isoNow,
+ deleted: true,
+ deletedAt: isoNow,
+ },
+ ],
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).not.toThrow();
+ });
+
+ it('accepts a v1 ref envelope without tombstone fields (mixed-version peer)', () => {
+ const env = {
+ refs: [
+ {
+ ingredientId: 'cat-chr-1',
+ refKind: 'universe',
+ refId: 'u1',
+ role: 'canon-character',
+ createdAt: isoNow,
+ },
+ ],
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).not.toThrow();
+ });
+
+ it('rejects an envelope whose ingredient payload exceeds 200KB', () => {
+ const env = {
+ ingredients: [
+ {
+ id: 'cat-chr-1',
+ type: 'character',
+ name: 'X',
+ payload: { blob: 'x'.repeat(210_000) },
+ createdAt: isoNow,
+ updatedAt: isoNow,
+ },
+ ],
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).toThrow();
+ });
+
+ it('caps each kind array length so a malicious peer can\'t push millions of rows', () => {
+ const env = {
+ ingredients: Array.from({ length: 5_001 }, (_, i) => ({
+ id: `cat-chr-${i}`,
+ type: 'character',
+ name: 'X',
+ createdAt: isoNow,
+ updatedAt: isoNow,
+ })),
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).toThrow();
+ });
+
+ it('accepts portosMeta.schemaVersions.catalog for the version gate', () => {
+ const env = {
+ portosMeta: { portosVersion: '2.10.0', schemaVersions: { catalog: 3 } },
+ };
+ const out = catalogSyncEnvelopeSchema.parse(env);
+ expect(out.portosMeta.schemaVersions.catalog).toBe(3);
+ });
+
+ it('caps portosMeta at 4KB so the escape hatch can\'t carry junk', () => {
+ const env = {
+ portosMeta: { junk: 'x'.repeat(5000) },
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).toThrow();
+ });
+});
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
new file mode 100644
index 0000000000..ba08336fd5
--- /dev/null
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -0,0 +1,174 @@
+/**
+ * Catalog DDL parity test — locks the schema definitions in
+ * `server/scripts/init-db.sql` (fresh-install path) and the `catalogDDL`
+ * array inside `server/lib/db.js` `ensureSchema()` (upgrade path) so a future
+ * PR that updates one without the other surfaces here instead of in the wild.
+ *
+ * Same risk exists for the `memories` / `memory_links` DDL but has been
+ * tolerated since the memory system landed; this test only covers catalog.
+ *
+ * The test is structural, not a SQL parser — it extracts table column sets,
+ * index names, trigger / function names, the `type` CHECK list, and the
+ * `search_tsv` payload-field set from each source and asserts the sets are
+ * equal. Cosmetic differences (whitespace, comments, ordering) are tolerated;
+ * a column added on one side but not the other is not.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const INIT_SQL = readFileSync(join(HERE, '..', 'scripts', 'init-db.sql'), 'utf8');
+const DB_JS = readFileSync(join(HERE, 'db.js'), 'utf8');
+
+const CATALOG_TABLES = [
+ 'catalog_scraps',
+ 'catalog_ingredients',
+ 'catalog_ingredient_sources',
+ 'catalog_ingredient_refs',
+];
+
+// Strip line comments + collapse whitespace so column lists compare cleanly.
+const normalize = (s) => s
+ .replace(/--[^\n]*\n/g, '\n')
+ .replace(/\s+/g, ' ')
+ .trim();
+
+function extractCreateTable(source, table) {
+ const re = new RegExp(`CREATE TABLE IF NOT EXISTS ${table}\\s*\\(([\\s\\S]*?)\\)(?:\\s*;|\\s*\`)`, 'i');
+ const m = re.exec(source);
+ if (!m) return null;
+ return normalize(m[1]);
+}
+
+// A column "name" for parity purposes: the identifier up to the first
+// space. Strips inline comments, then splits on commas at depth-0 parens so
+// `CHECK (type IN ('a','b'))` survives without breaking on its inner comma.
+function extractColumnNames(body) {
+ const parts = [];
+ let depth = 0;
+ let buf = '';
+ for (const ch of body) {
+ if (ch === '(') depth++;
+ if (ch === ')') depth--;
+ if (ch === ',' && depth === 0) {
+ parts.push(buf.trim());
+ buf = '';
+ } else {
+ buf += ch;
+ }
+ }
+ if (buf.trim()) parts.push(buf.trim());
+ return parts
+ .map((p) => p.split(/\s+/)[0])
+ .filter((p) => p && !/^(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT)$/i.test(p));
+}
+
+function extractIndexNames(source, prefix = 'idx_catalog_') {
+ const out = new Set();
+ const re = new RegExp(`CREATE INDEX IF NOT EXISTS\\s+(${prefix}\\w+)`, 'gi');
+ let m;
+ while ((m = re.exec(source)) !== null) out.add(m[1]);
+ return out;
+}
+
+function extractFunctionNames(source, prefix = 'update_catalog_') {
+ const out = new Set();
+ const re = new RegExp(`CREATE OR REPLACE FUNCTION\\s+(${prefix}\\w+)`, 'gi');
+ let m;
+ while ((m = re.exec(source)) !== null) out.add(m[1]);
+ return out;
+}
+
+function extractTriggerNames(source, prefix = 'trg_catalog_') {
+ const out = new Set();
+ const re = new RegExp(`CREATE TRIGGER\\s+(${prefix}\\w+)`, 'gi');
+ let m;
+ while ((m = re.exec(source)) !== null) out.add(m[1]);
+ return out;
+}
+
+// Pull the `type IN (...)` literal set out of the catalog_ingredients CHECK.
+function extractTypeCheckSet(source) {
+ const m = /CHECK\s*\(\s*type\s+IN\s*\(([^)]*)\)\s*\)/i.exec(source);
+ if (!m) return null;
+ return new Set(
+ m[1]
+ .split(',')
+ .map((s) => s.replace(/['"\s]/g, ''))
+ .filter(Boolean),
+ );
+}
+
+// Pull the `payload->>'<key>'` identifiers from the `search_tsv` generated
+// expression. Both files repeat them in the same per-line shape; we just
+// collect the set across the whole source.
+function extractPayloadFtsKeys(source) {
+ const out = new Set();
+ const re = /payload->>'([a-zA-Z0-9_]+)'/g;
+ let m;
+ while ((m = re.exec(source)) !== null) out.add(m[1]);
+ return out;
+}
+
+describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
+ it.each(CATALOG_TABLES)('table %s has the same columns in both files', (table) => {
+ const sqlBody = extractCreateTable(INIT_SQL, table);
+ const jsBody = extractCreateTable(DB_JS, table);
+ expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();
+ expect(jsBody, `db.js missing CREATE TABLE ${table}`).toBeTruthy();
+ const sqlCols = new Set(extractColumnNames(sqlBody));
+ const jsCols = new Set(extractColumnNames(jsBody));
+ expect([...sqlCols].sort()).toEqual([...jsCols].sort());
+ });
+
+ it('every idx_catalog_* index name appears in both files', () => {
+ const sqlIdx = extractIndexNames(INIT_SQL);
+ const jsIdx = extractIndexNames(DB_JS);
+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
+ expect(sqlIdx.size).toBeGreaterThan(0);
+ });
+
+ it('every update_catalog_* trigger function appears in both files', () => {
+ const sqlFns = extractFunctionNames(INIT_SQL);
+ const jsFns = extractFunctionNames(DB_JS);
+ expect([...sqlFns].sort()).toEqual([...jsFns].sort());
+ expect(sqlFns.size).toBeGreaterThan(0);
+ });
+
+ it('every trg_catalog_* trigger appears in both files', () => {
+ const sqlTrgs = extractTriggerNames(INIT_SQL);
+ const jsTrgs = extractTriggerNames(DB_JS);
+ expect([...sqlTrgs].sort()).toEqual([...jsTrgs].sort());
+ expect(sqlTrgs.size).toBeGreaterThan(0);
+ });
+
+ it('catalog_ingredients type CHECK list matches', () => {
+ // The init-db.sql CREATE TABLE block carries the CHECK; the db.js
+ // version embeds it inline in the same CREATE. The parity guard catches
+ // either side adding a 7th type without updating the other.
+ const sqlSet = extractTypeCheckSet(INIT_SQL);
+ const jsSet = extractTypeCheckSet(DB_JS);
+ expect(sqlSet, 'init-db.sql is missing the type CHECK').toBeTruthy();
+ expect(jsSet, 'db.js is missing the type CHECK').toBeTruthy();
+ expect([...sqlSet].sort()).toEqual([...jsSet].sort());
+ });
+
+ it('search_tsv payload field set matches', () => {
+ // Both files re-declare the GENERATED ALWAYS expression character-for-
+ // character today. If one side adds a payload key (e.g. voiceNotes) and
+ // the other lags, the FTS index expression mismatches and search returns
+ // different rows on a fresh install vs an upgraded install.
+ const sqlKeys = extractPayloadFtsKeys(INIT_SQL);
+ const jsKeys = extractPayloadFtsKeys(DB_JS);
+ expect([...sqlKeys].sort()).toEqual([...jsKeys].sort());
+ // Sanity: today's v2 expression covers the bible-backfilled character
+ // fields. If either drops below the documented set the test is lying.
+ for (const required of ['description', 'physicalDescription', 'personality', 'background', 'summary', 'notes']) {
+ expect(sqlKeys.has(required), `init-db.sql search_tsv missing ${required}`).toBe(true);
+ expect(jsKeys.has(required), `db.js search_tsv missing ${required}`).toBe(true);
+ }
+ });
+});
diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.js
new file mode 100644
index 0000000000..1f34626e4b
--- /dev/null
+++ b/server/services/catalogSync.test.js
@@ -0,0 +1,208 @@
+/**
+ * Unit tests for catalogSync — the peer→peer envelope apply path.
+ *
+ * The catalogDB upserts are mocked so this test stays pure (no Postgres).
+ * The assertions cover:
+ * - per-kind dispatch (scraps → ingredients → sources → refs)
+ * - per-row try/catch isolation (one bad row doesn't abort the rest)
+ * - the schema-version gate (sender ahead on `catalog` → 412)
+ * - cursor normalization in getChangesSince (scalar vs per-kind)
+ * - per-kind cursor advance falls back to the inbound cursor on quiet kinds
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./catalogDB.js', () => ({
+ getScrapChangesSince: vi.fn(),
+ getIngredientChangesSince: vi.fn(),
+ getSourceChangesSince: vi.fn(),
+ getRefChangesSince: vi.fn(),
+ getMaxSequences: vi.fn(),
+ upsertScrapFromPeer: vi.fn(),
+ upsertIngredientFromPeer: vi.fn(),
+ upsertSourceFromPeer: vi.fn(),
+ upsertRefFromPeer: vi.fn(),
+}));
+
+vi.mock('../lib/schemaVersions.js', async () => {
+ const actual = await vi.importActual('../lib/schemaVersions.js');
+ return actual;
+});
+
+const catalogDB = await import('./catalogDB.js');
+const {
+ applyRemoteChanges,
+ getChangesSince,
+ CatalogSyncVersionMismatchError,
+} = await import('./catalogSync.js');
+const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('applyRemoteChanges — dispatch + stats', () => {
+ it('routes each kind to its upsert and counts inserts/updates/skips', async () => {
+ catalogDB.upsertScrapFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: false });
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: false }); // LWW skip
+ catalogDB.upsertSourceFromPeer.mockResolvedValueOnce(undefined);
+ catalogDB.upsertRefFromPeer.mockResolvedValueOnce(undefined);
+
+ const stats = await applyRemoteChanges({
+ scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],
+ ingredients: [
+ { id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' },
+ { id: 'i2', type: 'character', name: 'B', createdAt: 't', updatedAt: 't' },
+ ],
+ sources: [{ ingredientId: 'i1', scrapId: 's1', extractedAt: 't' }],
+ refs: [{ ingredientId: 'i1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: 't' }],
+ });
+
+ expect(stats.scraps.inserted).toBe(1);
+ expect(stats.ingredients.updated).toBe(1);
+ expect(stats.ingredients.skipped).toBe(1);
+ expect(stats.sources.applied).toBe(1);
+ expect(stats.refs.applied).toBe(1);
+ expect(stats.errors).toHaveLength(0);
+ });
+
+ 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 });
+
+ const stats = await applyRemoteChanges({
+ scraps: [
+ { id: 'bad', rawText: 'x', createdAt: 't', updatedAt: 't' },
+ { id: 'good', rawText: 'y', createdAt: 't', updatedAt: 't' },
+ ],
+ });
+
+ expect(stats.scraps.failed).toBe(1);
+ expect(stats.scraps.inserted).toBe(1);
+ expect(stats.errors).toHaveLength(1);
+ expect(stats.errors[0]).toMatchObject({ kind: 'scrap', id: 'bad', message: 'boom' });
+ });
+
+ it('applies scraps before ingredients so source FKs can land in the same envelope', async () => {
+ const order = [];
+ catalogDB.upsertScrapFromPeer.mockImplementation(async () => {
+ order.push('scrap');
+ return { applied: true, isInsert: true };
+ });
+ catalogDB.upsertIngredientFromPeer.mockImplementation(async () => {
+ order.push('ingredient');
+ return { applied: true, isInsert: true };
+ });
+ catalogDB.upsertSourceFromPeer.mockImplementation(async () => {
+ order.push('source');
+ });
+ catalogDB.upsertRefFromPeer.mockImplementation(async () => {
+ order.push('ref');
+ });
+
+ await applyRemoteChanges({
+ 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']);
+ });
+});
+
+describe('applyRemoteChanges — schema-version gate', () => {
+ it('rejects envelopes whose sender is ahead on `catalog` with a 412', async () => {
+ const tooNew = PORTOS_SCHEMA_VERSIONS.catalog + 1;
+ await expect(applyRemoteChanges({
+ portosMeta: { schemaVersions: { catalog: tooNew } },
+ ingredients: [],
+ })).rejects.toBeInstanceOf(CatalogSyncVersionMismatchError);
+
+ // The thrown error carries the HTTP status + a structured diff.
+ try {
+ await applyRemoteChanges({
+ portosMeta: { schemaVersions: { catalog: tooNew } },
+ ingredients: [],
+ });
+ } catch (err) {
+ expect(err.status).toBe(412);
+ expect(err.code).toBe('CATALOG_SCHEMA_VERSION_AHEAD');
+ expect(err.diff.ahead[0].category).toBe('catalog');
+ }
+ });
+
+ it('accepts envelopes from a sender behind on `catalog`', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValue({ applied: true, isInsert: true });
+ const stats = await applyRemoteChanges({
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' }],
+ });
+ expect(stats.ingredients.inserted).toBe(1);
+ });
+
+ it('accepts envelopes with no portosMeta (legacy/forked peers)', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValue({ applied: true, isInsert: true });
+ const stats = await applyRemoteChanges({
+ ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' }],
+ });
+ expect(stats.ingredients.inserted).toBe(1);
+ });
+});
+
+describe('getChangesSince — cursor normalization + per-kind advance', () => {
+ beforeEach(() => {
+ catalogDB.getScrapChangesSince.mockResolvedValue({ items: [], hasMore: false });
+ catalogDB.getIngredientChangesSince.mockResolvedValue({ items: [], hasMore: false });
+ catalogDB.getSourceChangesSince.mockResolvedValue({ items: [], hasMore: false });
+ catalogDB.getRefChangesSince.mockResolvedValue({ items: [], hasMore: false });
+ });
+
+ it('accepts a scalar since and applies it uniformly to all four 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);
+ });
+
+ it('accepts a per-kind cursor object', async () => {
+ await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20' }, 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);
+ });
+
+ it('rejects non-numeric cursor values, falling back to "0"', async () => {
+ await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined }, 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);
+ });
+
+ it('per-kind maxSequence falls back to the inbound cursor on quiet kinds', async () => {
+ catalogDB.getScrapChangesSince.mockResolvedValue({
+ items: [{ id: 's2', syncSequence: '100' }],
+ hasMore: false,
+ });
+ catalogDB.getIngredientChangesSince.mockResolvedValue({ items: [], hasMore: false });
+
+ const res = await getChangesSince({ scraps: '50', ingredients: '99', sources: '88', refs: '77' }, 100);
+
+ // Quiet kinds reflect the inbound cursor — NOT 0 — so the next pull
+ // doesn't move backward.
+ expect(res.maxSequences.scraps).toBe('100');
+ expect(res.maxSequences.ingredients).toBe('99');
+ expect(res.maxSequences.sources).toBe('88');
+ expect(res.maxSequences.refs).toBe('77');
+ });
+
+ it('hasMore is true when ANY kind reports more', async () => {
+ catalogDB.getSourceChangesSince.mockResolvedValue({ items: [], hasMore: true });
+ const res = await getChangesSince('0', 100);
+ expect(res.hasMore).toBe(true);
+ });
+});