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: cover catalog DB CRUD, bible→catalog idempotency, and Catalog/IngredientPicker UI

[._.]/ Adam Eivy59c42705e192
diff --git a/client/src/components/IngredientPicker.test.jsx b/client/src/components/IngredientPicker.test.jsx
new file mode 100644
index 0000000000..ed5d034889
--- /dev/null
+++ b/client/src/components/IngredientPicker.test.jsx
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+vi.mock('../services/apiCatalog', () => ({
+ listCatalogIngredients: vi.fn(),
+}));
+
+import IngredientPicker from './IngredientPicker';
+import { listCatalogIngredients } from '../services/apiCatalog';
+
+const sample = [
+ { id: 'i-1', name: 'Ada Lovelace', type: 'character', payload: { description: 'Mathematician, programmer, dreamer.' }, tags: ['historical'] },
+ { id: 'i-2', name: 'Babbage Hall', type: 'place', payload: { description: 'A drafty workshop full of brass.' } },
+];
+
+const renderPicker = (props = {}) => render(
+ <MemoryRouter>
+ <IngredientPicker open onClose={() => {}} onSelect={() => {}} {...props} />
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listCatalogIngredients.mockResolvedValue({ items: sample });
+});
+
+describe('IngredientPicker', () => {
+ it('does not fetch or render its chrome while closed', () => {
+ render(
+ <MemoryRouter>
+ <IngredientPicker open={false} onClose={() => {}} onSelect={() => {}} />
+ </MemoryRouter>,
+ );
+ expect(listCatalogIngredients).not.toHaveBeenCalled();
+ expect(screen.queryByRole('heading', { name: /Pick an ingredient/i })).toBeNull();
+ });
+
+ it('fetches and renders the ingredient rows when open', async () => {
+ renderPicker();
+ await waitFor(() => expect(screen.getByText('Ada Lovelace')).toBeTruthy());
+ expect(screen.getByText('Babbage Hall')).toBeTruthy();
+ expect(screen.getByText(/Mathematician, programmer/i)).toBeTruthy();
+ // The first fetch goes out with no query and silent mode.
+ expect(listCatalogIngredients).toHaveBeenCalledWith(
+ expect.objectContaining({ q: undefined, limit: 50, silent: true }),
+ );
+ });
+
+ it('scopes the fetch to the supplied type and labels the heading', async () => {
+ renderPicker({ type: 'character' });
+ await waitFor(() => expect(screen.getByText('Ada Lovelace')).toBeTruthy());
+ expect(listCatalogIngredients).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'character' }),
+ );
+ expect(screen.getByText('(character)')).toBeTruthy();
+ });
+
+ it('hides ingredients listed in excludeIds', async () => {
+ renderPicker({ excludeIds: ['i-1'] });
+ await waitFor(() => expect(screen.getByText('Babbage Hall')).toBeTruthy());
+ expect(screen.queryByText('Ada Lovelace')).toBeNull();
+ });
+
+ it('single-select fires onSelect with the row then closes', async () => {
+ const onSelect = vi.fn();
+ const onClose = vi.fn();
+ renderPicker({ onSelect, onClose });
+ await waitFor(() => expect(screen.getByText('Ada Lovelace')).toBeTruthy());
+
+ fireEvent.click(screen.getByText('Ada Lovelace'));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'i-1' }));
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('multi-select collects checked rows and fires onSelect with an array', async () => {
+ const onSelect = vi.fn();
+ const onClose = vi.fn();
+ renderPicker({ multi: true, onSelect, onClose });
+ await waitFor(() => expect(screen.getByText('Ada Lovelace')).toBeTruthy());
+
+ fireEvent.click(screen.getByLabelText(/Select Ada Lovelace/i));
+ fireEvent.click(screen.getByLabelText(/Select Babbage Hall/i));
+ expect(screen.getByText('2 selected')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: /Add Selected/i }));
+ expect(onSelect).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'i-1' }),
+ expect.objectContaining({ id: 'i-2' }),
+ ]),
+ );
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('renders the empty state with a link to the catalog when nothing matches', async () => {
+ listCatalogIngredients.mockResolvedValue({ items: [] });
+ renderPicker();
+ await waitFor(() => expect(screen.getByText(/No matching ingredients/i)).toBeTruthy());
+ expect(screen.getByRole('link', { name: /Create new in Catalog/i })).toBeTruthy();
+ });
+
+ it('falls back to an empty list when the fetch rejects', async () => {
+ listCatalogIngredients.mockRejectedValue(new Error('boom'));
+ renderPicker();
+ await waitFor(() => expect(screen.getByText(/No matching ingredients/i)).toBeTruthy());
+ });
+
+ it('disables Add Selected until at least one row is checked', async () => {
+ renderPicker({ multi: true });
+ await waitFor(() => expect(screen.getByText('Ada Lovelace')).toBeTruthy());
+ const addBtn = screen.getByRole('button', { name: /Add Selected/i });
+ expect(addBtn.disabled).toBe(true);
+ fireEvent.click(screen.getByLabelText(/Select Ada Lovelace/i));
+ await act(async () => {}); // flush state
+ expect(addBtn.disabled).toBe(false);
+ });
+});
diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsx
new file mode 100644
index 0000000000..c5ea13b635
--- /dev/null
+++ b/client/src/pages/Catalog.test.jsx
@@ -0,0 +1,146 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+vi.mock('../services/apiCatalog', () => ({
+ listCatalogIngredients: vi.fn(),
+ createCatalogIngredient: vi.fn(),
+ deleteCatalogIngredient: vi.fn(),
+ getCatalogStats: vi.fn(),
+}));
+
+vi.mock('../components/ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+import Catalog from './Catalog';
+import {
+ listCatalogIngredients,
+ createCatalogIngredient,
+ deleteCatalogIngredient,
+ getCatalogStats,
+} from '../services/apiCatalog';
+import toast from '../components/ui/Toast';
+
+const sample = [
+ { id: 'i-1', name: 'Echo Saint', type: 'character', payload: { physicalDescription: 'A wiry figure in a long coat.' }, tags: ['noir'] },
+ { id: 'i-2', name: 'Old Harbor', type: 'place', payload: { description: 'Brine and rust.' }, tags: [] },
+];
+
+const renderCatalog = () => render(
+ <MemoryRouter>
+ <Catalog />
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listCatalogIngredients.mockResolvedValue({ items: sample });
+ getCatalogStats.mockResolvedValue({ total: 2, byType: { character: 1, place: 1 } });
+});
+
+describe('Catalog page', () => {
+ it('renders the fetched ingredient cards with snippet + count', async () => {
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+ expect(screen.getByText('Old Harbor')).toBeTruthy();
+ expect(screen.getByText(/wiry figure in a long coat/i)).toBeTruthy();
+ // Total count comes from stats.
+ expect(screen.getByText(/2 ingredients/i)).toBeTruthy();
+ });
+
+ it('filters by type when a type chip is clicked', async () => {
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+
+ fireEvent.click(screen.getByRole('button', { name: /^Character/i }));
+ await waitFor(() => {
+ expect(listCatalogIngredients).toHaveBeenLastCalledWith(
+ expect.objectContaining({ type: 'character' }),
+ );
+ });
+ });
+
+ it('debounces search input into the list fetch', async () => {
+ vi.useFakeTimers();
+ renderCatalog();
+ // Drain the initial mount fetch.
+ await act(async () => { await vi.runOnlyPendingTimersAsync(); });
+
+ fireEvent.change(screen.getByLabelText(/Search catalog/i), { target: { value: 'harbor' } });
+ // Before the debounce window elapses, q hasn't been pushed yet.
+ expect(listCatalogIngredients).not.toHaveBeenCalledWith(
+ expect.objectContaining({ q: 'harbor' }),
+ );
+ await act(async () => { await vi.advanceTimersByTimeAsync(350); });
+ expect(listCatalogIngredients).toHaveBeenLastCalledWith(
+ expect.objectContaining({ q: 'harbor' }),
+ );
+ vi.useRealTimers();
+ });
+
+ it('creates an ingredient and optimistically prepends it', async () => {
+ createCatalogIngredient.mockResolvedValue({
+ id: 'i-3', name: 'New Idea', type: 'idea', payload: { summary: 'spark' }, tags: [],
+ });
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+
+ fireEvent.click(screen.getByRole('button', { name: /^New$/i }));
+ fireEvent.change(screen.getByLabelText(/^Name$/i), { target: { value: 'New Idea' } });
+
+ await act(async () => {
+ fireEvent.submit(screen.getByLabelText(/^Name$/i).closest('form'));
+ });
+
+ expect(createCatalogIngredient).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'New Idea' }),
+ { silent: true },
+ );
+ await waitFor(() => expect(screen.getByText('New Idea')).toBeTruthy());
+ expect(toast.success).toHaveBeenCalled();
+ });
+
+ it('two-click-arms then deletes a card, removing it locally', async () => {
+ deleteCatalogIngredient.mockResolvedValue({ success: true });
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+
+ // Arm: the per-card Delete button reveals the Yes/No confirm.
+ fireEvent.click(screen.getByLabelText(/Delete Echo Saint/i));
+ const yesBtn = await screen.findByRole('button', { name: /^Yes$/i });
+
+ await act(async () => { fireEvent.click(yesBtn); });
+
+ await waitFor(() => expect(screen.queryByText('Echo Saint')).toBeNull());
+ expect(screen.getByText('Old Harbor')).toBeTruthy();
+ expect(deleteCatalogIngredient).toHaveBeenCalledWith('i-1', { silent: true });
+ });
+
+ it('restores the row when delete fails', async () => {
+ deleteCatalogIngredient.mockRejectedValue(new Error('nope'));
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+
+ fireEvent.click(screen.getByLabelText(/Delete Echo Saint/i));
+ const yesBtn = await screen.findByRole('button', { name: /^Yes$/i });
+ await act(async () => { fireEvent.click(yesBtn); });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalled());
+ // Optimistic removal is rolled back.
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+ });
+
+ it('shows the empty state when the catalog has no ingredients', async () => {
+ listCatalogIngredients.mockResolvedValue({ items: [] });
+ getCatalogStats.mockResolvedValue({ total: 0, byType: {} });
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText(/Your catalog is empty/i)).toBeTruthy());
+ });
+
+ it('surfaces a toast when the list fetch fails', async () => {
+ listCatalogIngredients.mockRejectedValue(new Error('load failed'));
+ renderCatalog();
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('load failed'));
+ });
+});
diff --git a/server/scripts/migrateBibleToCatalog.test.js b/server/scripts/migrateBibleToCatalog.test.js
new file mode 100644
index 0000000000..aaec459835
--- /dev/null
+++ b/server/scripts/migrateBibleToCatalog.test.js
@@ -0,0 +1,187 @@
+/**
+ * Idempotency tests for the bible→catalog backfill.
+ *
+ * The migration is wired into boot and MUST be safe to run repeatedly: a
+ * second run (with `force: true`, since the marker would otherwise short-
+ * circuit it) must promote zero new ingredients because every embedded entry
+ * already carries the deterministic `ingredientId` stamped by the first run.
+ *
+ * The migration's two DB dependencies (`universeBuilder`, `catalogDB`) are
+ * replaced with in-memory fakes so the test needs no Postgres. The marker
+ * file I/O (`fs/promises`) is mocked to an in-memory blob so we can assert
+ * the short-circuit-on-marker behavior without touching disk.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// --- In-memory universe store --------------------------------------------
+// Mutable so the migration's Phase-2 `updateUniverse` mutator can stamp
+// ingredientId back onto entries and a second run sees the stamped shape.
+let universes = [];
+
+vi.mock('../services/universeBuilder.js', () => ({
+ listUniverses: vi.fn(async () => universes.filter((u) => !u.deleted)),
+ updateUniverse: vi.fn(async (id, patchOrMutator) => {
+ const u = universes.find((x) => x.id === id);
+ if (!u) return null;
+ const patch = typeof patchOrMutator === 'function' ? patchOrMutator(u) : patchOrMutator;
+ if (!patch) return u;
+ Object.assign(u, patch);
+ return u;
+ }),
+}));
+
+// --- In-memory catalog store ---------------------------------------------
+// Keyed by id. `createIngredient` mirrors the real one's PK-conflict throw so
+// a non-idempotent migration (re-INSERT at a deterministic id) would surface
+// as a thrown error / errors counter bump.
+let ingredients = new Map();
+let refLinks = []; // { ingredientId, refKind, refId, role }
+
+const createIngredient = vi.fn(async ({ id, type, name, payload = {}, tags = [] }) => {
+ if (ingredients.has(id)) {
+ throw new Error(`duplicate key value violates unique constraint (id=${id})`);
+ }
+ const row = { id, type, name, payload, tags, deleted: false };
+ ingredients.set(id, row);
+ return row;
+});
+
+const getIngredient = vi.fn(async (id) => {
+ const row = ingredients.get(id);
+ return row && !row.deleted ? row : null;
+});
+
+const reviveDeletedIngredient = vi.fn(async (id, { type, name, payload, tags }) => {
+ const row = ingredients.get(id);
+ if (!row || !row.deleted) return null;
+ Object.assign(row, { deleted: false, type, name, payload, tags });
+ return row;
+});
+
+const linkIngredientToRef = vi.fn(async (ingredientId, refKind, refId, role) => {
+ const exists = refLinks.some(
+ (r) => r.ingredientId === ingredientId && r.refKind === refKind && r.refId === refId && r.role === role,
+ );
+ if (!exists) refLinks.push({ ingredientId, refKind, refId, role });
+});
+
+vi.mock('../services/catalogDB.js', () => ({
+ createIngredient: (...args) => createIngredient(...args),
+ getIngredient: (...args) => getIngredient(...args),
+ reviveDeletedIngredient: (...args) => reviveDeletedIngredient(...args),
+ linkIngredientToRef: (...args) => linkIngredientToRef(...args),
+}));
+
+// --- In-memory marker file -----------------------------------------------
+let markerBlob = null; // string | null
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async () => {
+ if (markerBlob === null) {
+ const err = new Error('ENOENT');
+ err.code = 'ENOENT';
+ throw err;
+ }
+ return markerBlob;
+ }),
+ writeFile: vi.fn(async (_path, data) => { markerBlob = data; }),
+}));
+
+import { migrateBibleToCatalog } from './migrateBibleToCatalog.js';
+
+function makeUniverse(overrides = {}) {
+ return {
+ id: 'u-1',
+ deleted: false,
+ characters: [
+ { id: 'c-1', name: 'Echo Saint', physicalDescription: 'A wiry figure.' },
+ { id: 'c-2', name: 'Mirror Doe', personality: 'Wry' },
+ ],
+ places: [{ id: 'p-1', name: 'Old Harbor', description: 'Brine.' }],
+ objects: [{ id: 'o-1', name: 'Brass Key' }],
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ universes = [makeUniverse()];
+ ingredients = new Map();
+ refLinks = [];
+ markerBlob = null;
+ vi.clearAllMocks();
+});
+
+describe('migrateBibleToCatalog', () => {
+ it('promotes every embedded canon entry on the first run', async () => {
+ const result = await migrateBibleToCatalog();
+ expect(result.skipped).toBe(false);
+ expect(result.stats.universesScanned).toBe(1);
+ // 2 characters + 1 place + 1 object = 4 promotions.
+ expect(result.stats.promoted).toBe(4);
+ expect(result.stats.errors).toBe(0);
+ expect(ingredients.size).toBe(4);
+ // Each entry got its ingredientId stamped back onto the universe.
+ const u = universes[0];
+ expect(u.characters.every((c) => typeof c.ingredientId === 'string')).toBe(true);
+ expect(u.places[0].ingredientId).toMatch(/^cat-plc-bible-/);
+ expect(u.objects[0].ingredientId).toMatch(/^cat-obj-bible-/);
+ // One ref link per promoted entry.
+ expect(refLinks).toHaveLength(4);
+ });
+
+ it('is idempotent: a second run promotes nothing new and inserts no duplicate rows', async () => {
+ await migrateBibleToCatalog();
+ const firstSize = ingredients.size;
+ const createCallsAfterFirst = createIngredient.mock.calls.length;
+
+ // Force a second run (the marker would otherwise short-circuit it).
+ const second = await migrateBibleToCatalog({ force: true });
+
+ expect(second.skipped).toBe(false);
+ expect(second.stats.promoted).toBe(0);
+ expect(second.stats.errors).toBe(0);
+ // No new ingredient rows, no duplicate-key throws.
+ expect(ingredients.size).toBe(firstSize);
+ expect(createIngredient.mock.calls.length).toBe(createCallsAfterFirst);
+ // The skipped counter accounts for every already-promoted entry.
+ expect(second.stats.skipped).toBe(4);
+ });
+
+ it('short-circuits when the marker is already at the current version', async () => {
+ await migrateBibleToCatalog();
+ // Marker is now written; a plain (non-forced) re-run must no-op.
+ const rerun = await migrateBibleToCatalog();
+ expect(rerun.skipped).toBe(true);
+ expect(rerun.marker.version).toBe(1);
+ });
+
+ it('re-links an already-promoted entry that lost its ref (idempotent linking)', async () => {
+ await migrateBibleToCatalog();
+ // Drop the ref links but keep the stamped ingredientId + catalog rows.
+ refLinks = [];
+
+ const second = await migrateBibleToCatalog({ force: true });
+ expect(second.stats.promoted).toBe(0);
+ // linkIngredientToRef is re-asserted for each already-promoted entry,
+ // re-creating the 4 missing links without minting new ingredients.
+ expect(refLinks).toHaveLength(4);
+ expect(ingredients.size).toBe(4);
+ });
+
+ it('skips universes flagged deleted', async () => {
+ universes = [makeUniverse({ deleted: true })];
+ const result = await migrateBibleToCatalog();
+ expect(result.stats.universesScanned).toBe(0);
+ expect(result.stats.promoted).toBe(0);
+ expect(ingredients.size).toBe(0);
+ });
+
+ it('preserves a foreign ingredientId stamped by a peer instead of minting a new one', async () => {
+ // Simulate a peer that already promoted this character under a random id.
+ universes[0].characters[0].ingredientId = 'cat-chr-peer-abc123';
+ const result = await migrateBibleToCatalog();
+ expect(ingredients.has('cat-chr-peer-abc123')).toBe(true);
+ // The other three entries still promote under deterministic ids.
+ expect(result.stats.promoted).toBe(4);
+ });
+});
diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.js
new file mode 100644
index 0000000000..ec06b9cbb3
--- /dev/null
+++ b/server/services/catalogDB.test.js
@@ -0,0 +1,272 @@
+/**
+ * Postgres-backed CRUD round-trip for the catalog data layer.
+ *
+ * This suite needs a live PostgreSQL instance with the catalog schema applied
+ * (the same one `npm start` connects to). If no DB is reachable — the common
+ * case in CI and on fresh checkouts — it SKIPS cleanly with a clear message
+ * rather than failing red. When a DB IS reachable it exercises the full
+ * scrap → ingredient → ref → source lifecycle and tears its rows back out so
+ * the suite is repeatable.
+ *
+ * `instances.js` is left under the global vitest.setup.js mock (getPeers → [])
+ * so no row created here fans out to live sync peers; nothing here exercises
+ * the createUniverse/createSeries peerSync import path, so mockNoPeers alone
+ * is sufficient per the CLAUDE.md record-creating-tests rule.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { checkHealth, ensureSchema, close } from '../lib/db.js';
+import * as catalogDB from './catalogDB.js';
+
+// Probe the DB once before the suite. `dbReady` gates every test: when false
+// we register the suite with `describe.skip` so the runner reports them as
+// skipped (with the reason logged) instead of erroring on a missing socket.
+let dbReady = false;
+let skipReason = '';
+
+beforeAll(async () => {
+ const health = await checkHealth();
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ return;
+ }
+ // Always run the idempotent ensureSchema upgrades before the suite: a DB
+ // provisioned by an older PortOS may have the catalog tables but be missing
+ // newer columns (e.g. the ref tombstone `deleted`/`deleted_at`). ensureSchema
+ // creates the tables when absent and ALTERs them up to current when present.
+ await ensureSchema().catch(() => {});
+ const recheck = await checkHealth();
+ if (!recheck.hasCatalogSchema) {
+ skipReason = 'catalog schema not present (ensureSchema did not create catalog tables)';
+ return;
+ }
+ dbReady = true;
+});
+
+// Vitest evaluates describe bodies eagerly, before beforeAll runs, so we can't
+// branch on `dbReady` at registration time. Instead each test no-ops with a
+// console note when the DB is unavailable — keeping the suite green and loud.
+function requireDb(t) {
+ if (!dbReady) {
+ console.log(`⏭️ catalogDB.test: skipping "${t}" — ${skipReason || 'no database'}`);
+ return false;
+ }
+ return true;
+}
+
+// Track ids created across tests so end-of-suite cleanup hard-deletes them
+// even when an assertion throws mid-test. Cleanup runs BEFORE the pool is
+// closed (single afterAll, in order) so the deletes have a live connection.
+const createdIngredientIds = new Set();
+const createdScrapIds = new Set();
+
+afterAll(async () => {
+ if (!dbReady) return;
+ for (const id of createdIngredientIds) {
+ await catalogDB.deleteIngredient(id, { hard: true }).catch(() => {});
+ }
+ for (const id of createdScrapIds) {
+ await catalogDB.deleteScrap(id, { hard: true }).catch(() => {});
+ }
+ await close();
+});
+
+describe('catalogDB (Postgres CRUD round-trip)', () => {
+ it('creates and reads back an ingredient with payload + tags', async () => {
+ if (!requireDb('create/get ingredient')) return;
+ const created = await catalogDB.createIngredient({
+ type: 'character',
+ name: ' Echo Saint ',
+ payload: { physicalDescription: 'A wiry figure in a long coat.', personality: 'Wry' },
+ tags: ['noir', 'protagonist'],
+ });
+ createdIngredientIds.add(created.id);
+
+ expect(created.id).toMatch(/^cat-chr-/);
+ expect(created.name).toBe('Echo Saint'); // trimmed
+ expect(created.type).toBe('character');
+ expect(created.payload.physicalDescription).toContain('wiry figure');
+ expect(created.tags).toEqual(['noir', 'protagonist']);
+ expect(created.deleted).toBe(false);
+
+ const fetched = await catalogDB.getIngredient(created.id);
+ expect(fetched).not.toBeNull();
+ expect(fetched.id).toBe(created.id);
+ expect(fetched.name).toBe('Echo Saint');
+ expect(fetched.payload.personality).toBe('Wry');
+ });
+
+ it('rejects an invalid type and a blank name', async () => {
+ if (!requireDb('create validation')) return;
+ await expect(catalogDB.createIngredient({ type: 'spaceship', name: 'X' }))
+ .rejects.toThrow(/Invalid ingredient type/);
+ await expect(catalogDB.createIngredient({ type: 'idea', name: ' ' }))
+ .rejects.toThrow(/name is required/);
+ });
+
+ it('updates name/payload/tags in place and preserves untouched fields', async () => {
+ if (!requireDb('update ingredient')) return;
+ const created = await catalogDB.createIngredient({
+ type: 'place',
+ name: 'Old Harbor',
+ payload: { description: 'Brine and rust.' },
+ tags: ['coastal'],
+ });
+ createdIngredientIds.add(created.id);
+
+ const updated = await catalogDB.updateIngredient(created.id, {
+ name: 'New Harbor',
+ tags: ['coastal', 'rebuilt'],
+ });
+ expect(updated.name).toBe('New Harbor');
+ expect(updated.tags).toEqual(['coastal', 'rebuilt']);
+ // payload untouched — only patched fields change
+ expect(updated.payload.description).toBe('Brine and rust.');
+ });
+
+ it('soft-deletes so GET returns null but the row survives for sync', async () => {
+ if (!requireDb('soft-delete ingredient')) return;
+ const created = await catalogDB.createIngredient({ type: 'object', name: 'Brass Key' });
+ createdIngredientIds.add(created.id);
+
+ await catalogDB.deleteIngredient(created.id);
+ const afterDelete = await catalogDB.getIngredient(created.id);
+ expect(afterDelete).toBeNull();
+
+ // The tombstone is still visible to the sync change-feed.
+ const { items } = await catalogDB.getIngredientChangesSince('0', 1000);
+ const tombstone = items.find((i) => i.id === created.id);
+ expect(tombstone).toBeTruthy();
+ expect(tombstone.deleted).toBe(true);
+ });
+
+ it('reviveDeletedIngredient un-deletes a soft-deleted row at the same id', async () => {
+ if (!requireDb('revive ingredient')) return;
+ const created = await catalogDB.createIngredient({
+ type: 'concept', name: 'Entropy', payload: { summary: 'old' },
+ });
+ createdIngredientIds.add(created.id);
+ await catalogDB.deleteIngredient(created.id);
+
+ const revived = await catalogDB.reviveDeletedIngredient(created.id, {
+ type: 'concept', name: 'Entropy', payload: { summary: 'new' }, tags: ['physics'],
+ });
+ expect(revived).not.toBeNull();
+ expect(revived.deleted).toBe(false);
+ expect(revived.payload.summary).toBe('new');
+
+ // A fresh GET now succeeds (the row is active again).
+ const fetched = await catalogDB.getIngredient(created.id);
+ expect(fetched.tags).toEqual(['physics']);
+
+ // Reviving a row that is NOT deleted returns null (no-op).
+ const noop = await catalogDB.reviveDeletedIngredient(created.id, {
+ type: 'concept', name: 'Entropy',
+ });
+ expect(noop).toBeNull();
+ });
+
+ it('lists ingredients filtered by type', async () => {
+ if (!requireDb('list by type')) return;
+ const scene = await catalogDB.createIngredient({ type: 'scene', name: 'Rooftop Standoff' });
+ createdIngredientIds.add(scene.id);
+
+ const { items } = await catalogDB.listIngredients({ type: 'scene', limit: 200 });
+ expect(items.every((i) => i.type === 'scene')).toBe(true);
+ expect(items.some((i) => i.id === scene.id)).toBe(true);
+ // The light list path strips the embedding column.
+ expect(items[0].embedding).toBeNull();
+ });
+
+ it('links an ingredient to a ref, lists both directions, then soft-unlinks', async () => {
+ if (!requireDb('ref link/unlink')) return;
+ const ing = await catalogDB.createIngredient({ type: 'character', name: 'Linker McRef' });
+ createdIngredientIds.add(ing.id);
+ const refId = `series-${ing.id}`; // unique synthetic ref id
+
+ await catalogDB.linkIngredientToRef(ing.id, 'series', refId, 'cast-character');
+
+ const refs = await catalogDB.listRefsForIngredient(ing.id);
+ expect(refs).toHaveLength(1);
+ expect(refs[0]).toMatchObject({ refKind: 'series', refId, role: 'cast-character', deleted: false });
+
+ const forRef = await catalogDB.listIngredientsForRef('series', refId);
+ expect(forRef).toHaveLength(1);
+ expect(forRef[0].ingredient.id).toBe(ing.id);
+ expect(forRef[0].role).toBe('cast-character');
+
+ await catalogDB.unlinkIngredientFromRef(ing.id, 'series', refId, 'cast-character');
+ // Live list paths hide tombstoned links.
+ expect(await catalogDB.listRefsForIngredient(ing.id)).toHaveLength(0);
+ expect(await catalogDB.listIngredientsForRef('series', refId)).toHaveLength(0);
+ });
+
+ it('creates a scrap, links it as an ingredient source, and hydrates it back', async () => {
+ if (!requireDb('scrap source link')) return;
+ const scrap = await catalogDB.createScrap({
+ title: 'Notebook page',
+ rawText: 'A long coat, a longer memory.',
+ sourceKind: 'paste',
+ });
+ createdScrapIds.add(scrap.id);
+ expect(scrap.id).toMatch(/^cat-scrap-/);
+
+ const ing = await catalogDB.createIngredient({ type: 'character', name: 'Sourced One' });
+ createdIngredientIds.add(ing.id);
+
+ await catalogDB.linkIngredientToSource(ing.id, scrap.id, { start: 0, end: 10 });
+
+ const sources = await catalogDB.listSourcesForIngredient(ing.id);
+ expect(sources).toHaveLength(1);
+ expect(sources[0]).toMatchObject({ scrapId: scrap.id, ingredientId: ing.id });
+ expect(sources[0].span).toEqual({ start: 0, end: 10 });
+
+ const forScrap = await catalogDB.listSourcesForScrap(scrap.id);
+ expect(forScrap.some((s) => s.ingredientId === ing.id)).toBe(true);
+
+ const hydrated = await catalogDB.listScrapsForIngredient(ing.id);
+ expect(hydrated).toHaveLength(1);
+ expect(hydrated[0].rawText).toContain('long coat');
+ });
+
+ it('exportSliceForRef bundles ingredients + scraps + refs for a ref', async () => {
+ if (!requireDb('export slice')) return;
+ const ing = await catalogDB.createIngredient({
+ type: 'character', name: 'Bundled Hero', payload: { role: 'lead' },
+ });
+ createdIngredientIds.add(ing.id);
+ const refId = `work-${ing.id}`;
+ await catalogDB.linkIngredientToRef(ing.id, 'work', refId, 'cast-character');
+ const scrap = await catalogDB.createScrap({ rawText: 'Origin notes.' });
+ createdScrapIds.add(scrap.id);
+ await catalogDB.linkIngredientToSource(ing.id, scrap.id);
+
+ const bundle = await catalogDB.exportSliceForRef('work', refId);
+ expect(bundle.version).toBe(1);
+ expect(bundle.ref).toEqual({ kind: 'work', id: refId });
+ expect(bundle.ingredients).toHaveLength(1);
+ const exported = bundle.ingredients[0];
+ expect(exported.id).toBe(ing.id);
+ expect(exported.roleForExportedRef).toBe('cast-character');
+ expect(exported.scraps).toHaveLength(1);
+ // Embedding is stripped from the export.
+ expect(exported.embedding).toBeUndefined();
+ });
+
+ it('getCatalogStats reflects created rows', async () => {
+ if (!requireDb('catalog stats')) return;
+ const ing = await catalogDB.createIngredient({ type: 'idea', name: 'Stat Idea' });
+ createdIngredientIds.add(ing.id);
+ const stats = await catalogDB.getCatalogStats();
+ expect(typeof stats.total).toBe('number');
+ expect(stats.byType.idea).toBeGreaterThanOrEqual(1);
+ });
+
+ it('getMaxSequences returns numeric-string cursors for every table', async () => {
+ if (!requireDb('max sequences')) return;
+ const seqs = await catalogDB.getMaxSequences();
+ for (const key of ['ingredients', 'scraps', 'sources', 'refs']) {
+ expect(seqs[key]).toMatch(/^\d+$/);
+ }
+ });
+});