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

bind catalog scrap-commit to a universe so committed ingredients stop landing unlinked (#7615)

[._.]/ Adam Eivy8f0e6f195174
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index 0322904ac8..e70171e19f 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -28,6 +28,23 @@ import {
ingestCatalogBrain,
} from '../services/apiCatalog';
import { markBrainInboxSentToCatalog } from '../services/apiBrain';
+import { listUniverseNames } from '../services/apiUniverseBuilder';
+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage';
+
+// The explicit "no universe" choice, preserving today's behavior exactly
+// (source link only, no catalog_ingredient_refs row).
+const UNASSIGNED_UNIVERSE = 'unassigned';
+// Where the last-picked "Catalogue into" universe id is remembered across
+// visits (#7615). A capture-source ingest (brain-bridge / voice-memo)
+// defaults to a universe named "Reality" instead, when one exists — captured
+// thought is factual by default.
+const LAST_UNIVERSE_STORAGE_KEY = 'catalog-ingest-last-universe';
+const REALITY_UNIVERSE_NAME = 'Reality';
+// Ingest source kinds that default to the Reality universe rather than the
+// last-used pick — mirrors SCRAP_SOURCE_KINDS' `factual: true` entries
+// (server/lib/catalogSourceKinds.js): brain-bridge and voice-memo capture the
+// user's own lived material, not invented story text.
+const FACTUAL_INGEST_KINDS = new Set(['brain', 'voice']);
// One review section per ingredient type. The first three are bible-shaped
// (character/place/object) and use `physicalDescription`/`description` as the
@@ -98,6 +115,10 @@ export default function CatalogIngest() {
const [url, setUrl] = useState('');
const [recording, setRecording] = useState(false);
const recorderRef = useRef(null);
+ // "Catalogue into" — the universe every committed ingredient binds to
+ // (#7615). Populated on mount; defaulted per-ingest in enterReviewFromResult.
+ const [universes, setUniverses] = useState([]);
+ const [universeRef, setUniverseRef] = useState(UNASSIGNED_UNIVERSE);
const brainHandledRef = useRef(false);
// Creative inbox note ids handed off from the Brain batch-send. Once the
// commit below succeeds we stamp these consumed so they drop out of the
@@ -114,6 +135,26 @@ export default function CatalogIngest() {
// MediaRecorder stream isn't left live with no UI to stop it.
useEffect(() => () => { recorderRef.current?.cancel?.(); }, []);
+ // Load the "Catalogue into" options once. Best-effort — an empty list just
+ // leaves Unassigned as the only choice.
+ useEffect(() => {
+ listUniverseNames({ silent: true }).then((list) => setUniverses(Array.isArray(list) ? list : [])).catch(() => {});
+ }, []);
+
+ // Default the "Catalogue into" pick for a freshly-entered review phase.
+ // Capture-source ingests (brain-bridge / voice-memo) default to the Reality
+ // universe when one exists; everything else defaults to the last-used
+ // choice (persisted through safeReadStorage), falling back to Reality, then
+ // Unassigned. `sourceKind` is one of 'paste' | 'url' | 'file' | 'voice' |
+ // 'brain' | 'babble'.
+ const defaultUniverseForSource = (sourceKind) => {
+ const reality = universes.find((u) => u.name === REALITY_UNIVERSE_NAME);
+ if (FACTUAL_INGEST_KINDS.has(sourceKind)) return reality?.id || UNASSIGNED_UNIVERSE;
+ const lastUsed = safeReadStorage(LAST_UNIVERSE_STORAGE_KEY);
+ if (lastUsed && (lastUsed === UNASSIGNED_UNIVERSE || universes.some((u) => u.id === lastUsed))) return lastUsed;
+ return reality?.id || UNASSIGNED_UNIVERSE;
+ };
+
// Any transition OUT of the paste phase that isn't the voice flow's own
// stop-and-transcribe (which nulls recorderRef before switching) must release
// the mic — otherwise starting File/URL/Paste ingest mid-recording hides the
@@ -183,9 +224,10 @@ export default function CatalogIngest() {
// Shared review-entry: every ingest path (paste / url / file / voice) yields
// a `{ scrap, draft }` response with the same draft shape, so they all funnel
// through here to populate the review phase.
- const enterReviewFromResult = (result) => {
+ const enterReviewFromResult = (result, sourceKind) => {
if (!result?.draft) { setPhase('paste'); return false; }
if (result.scrap?.id) setScrapId(result.scrap.id);
+ setUniverseRef(defaultUniverseForSource(sourceKind));
const d = Object.fromEntries(KIND_SECTIONS.map((s) => [
s.key,
Array.isArray(result.draft[s.key]) ? result.draft[s.key] : [],
@@ -227,7 +269,7 @@ export default function CatalogIngest() {
: extractFromCatalogScrap(created.scrap.id, {}, { silent: true }))
.catch((err) => { toast.error(err?.message || 'Extraction failed'); return null; });
setSubmitting(false);
- enterReviewFromResult(result);
+ enterReviewFromResult(result, babble ? 'babble' : 'paste');
};
const handleUrlIngest = async (e) => {
@@ -240,7 +282,7 @@ export default function CatalogIngest() {
const result = await ingestCatalogUrl({ url: trimmed }, { silent: true })
.catch((err) => { toast.error(err?.message || 'URL ingest failed'); return null; });
setSubmitting(false);
- enterReviewFromResult(result);
+ enterReviewFromResult(result, 'url');
};
// Brain → catalog handoff: the brain UI navigates here with
@@ -253,7 +295,7 @@ export default function CatalogIngest() {
const result = await ingestCatalogBrain({ brainType, brainId }, { silent: true })
.catch((err) => { toast.error(err?.message || 'Brain ingest failed'); return null; });
setSubmitting(false);
- enterReviewFromResult(result);
+ enterReviewFromResult(result, 'brain');
};
// Handle inbound router-state handoffs once on mount:
@@ -304,7 +346,7 @@ export default function CatalogIngest() {
{ silent: true },
).catch((err) => { toast.error(err?.message || 'File ingest failed'); return null; });
setSubmitting(false);
- enterReviewFromResult(result);
+ enterReviewFromResult(result, 'file');
};
const startRecording = async () => {
@@ -339,7 +381,7 @@ export default function CatalogIngest() {
{ silent: true },
).catch((err) => { toast.error(err?.message || 'Voice ingest failed'); return null; });
setSubmitting(false);
- enterReviewFromResult(result);
+ enterReviewFromResult(result, 'voice');
};
const handleBulkImport = async () => {
@@ -412,7 +454,10 @@ export default function CatalogIngest() {
return;
}
setCommitting(true);
- const result = await commitCatalogScrapDraft(scrapId, accepted, { silent: true }).catch((err) => {
+ const result = await commitCatalogScrapDraft(scrapId, accepted, {
+ universeRef: universeRef === UNASSIGNED_UNIVERSE ? undefined : universeRef,
+ silent: true,
+ }).catch((err) => {
toast.error(err?.message || 'Commit failed');
return null;
});
@@ -653,8 +698,25 @@ export default function CatalogIngest() {
{phase === 'review' && (
<div className="space-y-5">
- <div className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-300">
- Review the candidates below. Uncheck anything you don&apos;t want, edit names and descriptions inline, then commit the rest.
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <p className="text-sm text-gray-300">
+ Review the candidates below. Uncheck anything you don&apos;t want, edit names and descriptions inline, then commit the rest.
+ </p>
+ <div className="max-w-xs">
+ <label htmlFor="ingest-universe-ref" className="block text-sm font-medium mb-1 text-white">Catalogue into</label>
+ <select id="ingest-universe-ref" value={universeRef}
+ onChange={(e) => {
+ const next = e.target.value;
+ setUniverseRef(next);
+ safeWriteStorage(LAST_UNIVERSE_STORAGE_KEY, next);
+ }}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent">
+ <option value={UNASSIGNED_UNIVERSE}>Unassigned</option>
+ {universes.map((u) => (
+ <option key={u.id} value={u.id}>{u.name}</option>
+ ))}
+ </select>
+ </div>
</div>
{KIND_SECTIONS.map((section) => (
<ReviewSection
diff --git a/client/src/pages/CatalogIngest.test.jsx b/client/src/pages/CatalogIngest.test.jsx
index 81c9502440..6a1036bd8c 100644
--- a/client/src/pages/CatalogIngest.test.jsx
+++ b/client/src/pages/CatalogIngest.test.jsx
@@ -7,6 +7,7 @@ vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } })
vi.mock('../hooks/useProviderModels', () => ({ default: () => ({ providers: [], selectedProviderId: 'example-provider', selectedModel: 'example-model', availableModels: [], loading: false }) }));
vi.mock('../components/ProviderModelSelector', () => ({ default: ({ onEffortChange }) => <button type="button" onClick={() => onEffortChange('high')}>High effort</button> }));
vi.mock('../services/apiCatalog', () => ({ createCatalogScrap: vi.fn(), pruneCatalogScrap: vi.fn(), commitCatalogScrapDraft: vi.fn() }));
+vi.mock('../services/apiUniverseBuilder', () => ({ listUniverseNames: vi.fn().mockResolvedValue([]) }));
it('prunes only on request, keeps the brainstorm, and saves edited selected suggestions', async () => {
createCatalogScrap.mockResolvedValue({ scrap: { id: 'example-scrap' } });
pruneCatalogScrap.mockResolvedValue({ scrap: { id: 'example-scrap' }, draft: { ideas: [{ name: 'Moon story', summary: 'A missing moon.' }], scenes: [{ name: 'Argument', summary: 'Two travelers argue.' }] } });
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index e94c09f97c..f2df736bdc 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -28,8 +28,16 @@ export const extractFromCatalogScrap = (id, body = {}, options) =>
export const pruneCatalogScrap = (id, body, options) =>
request(`/catalog/scraps/${enc(id)}/prune`, { method: 'POST', body: JSON.stringify(body), ...options });
-export const commitCatalogScrapDraft = (id, accepted, options) =>
- request(`/catalog/scraps/${enc(id)}/commit`, { method: 'POST', body: JSON.stringify({ accepted }), ...options });
+// `universeRef` (+ optional `role`) binds every committed ingredient to that
+// universe — the "Catalogue into" select on CatalogIngest (#7615). Omitted
+// when the caller passes 'unassigned' (the "no universe" choice), reproducing
+// prior behavior exactly (source link only, no homing ref).
+export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, ...options } = {}) =>
+ request(`/catalog/scraps/${enc(id)}/commit`, {
+ method: 'POST',
+ body: JSON.stringify({ accepted, ...(universeRef ? { universeRef, ...(role ? { role } : {}) } : {}) }),
+ ...options,
+ });
// --- Alternate ingest sources (url / file / voice / brain) --------------
// Each returns { scrap, draft } — the same shape as extractFromCatalogScrap —
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8cd83b0e44..5241b4cb99 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -31,7 +31,8 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
**Examples.**
- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.
-- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).
+- `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 (the strongest argument for Postgres as the catalog graph store). Since #7615, committing a scrap also mints one `related-to` edge per unordered pair among the ingredients extracted from that scrap in one batch (bounded to batches of 25 or fewer), so a single source's extractions land as a connected cluster instead of isolated nodes.
- `catalog_scraps` / `catalog_ingredient_sources` — the catalog's SECOND grouping seam alongside refs (universe/series/work): a scrap is the raw pasted/imported text an ingredient was extracted from, and `catalog_ingredient_sources` links `(ingredient_id, scrap_id)` with an optional `span`. The ingredient detail page's `GET /ingredients/:id/details` joins the scrap's `title` onto each source link and batches every sibling ingredient extracted from the SAME scrap (`listSiblingIngredientsBySource`) in the one round-trip, so "what else came out of this piece?" is a rendered list, never a second fetch. `GET /ingredients?scrapId=<id>` (and `/catalog?scrap=<id>` client-side) filters the catalog to one scrap's whole extraction set — a provenance dimension orthogonal to the universe/series ref filters, so it composes with them rather than joining their mutual-exclusivity rule (#7617).
- `memories` / `memory_links` — long-term memory + pgvector similarity.
- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index cba4c70c58..84487497bd 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -403,11 +403,17 @@ export const catalogMediaVoiceMemoSchema = z.object({
role: z.string().trim().max(64).optional().nullable(),
}).strict();
+// `universeRef` (+ optional `role`) mirrors catalogBulkImportSchema.defaults
+// below — same field name, same shape — so the two ingest paths (bulk-import,
+// scrap-commit) cannot drift (#7615). Omitting `universeRef` reproduces
+// today's behavior exactly: source link only, no homing ref.
export const catalogScrapCommitSchema = z.object({
accepted: z.array(catalogIngredientCreateSchema.extend({
// Optional source-span hint (server forwards as-is to linkIngredientToSource).
span: z.record(z.string(), z.unknown()).optional(),
})).min(0).max(200),
+ universeRef: z.string().trim().min(1).max(120).optional(),
+ role: z.string().trim().min(1).max(64).optional(),
}).strict();
// /scraps/:id/extract — optional provider override (e.g., force a specific
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 488984443b..543a897dc9 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -177,6 +177,8 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
scrapId: scrap.id,
accepted: body.accepted,
embeds,
+ universeRef: body.universeRef,
+ role: body.role,
});
res.status(201).json({ scrap, ingredients: created });
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index be7116e1a4..d3f503aab9 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -325,6 +325,113 @@ describe.skipIf(!runDb)('GET /api/catalog/ingredients/:id/details — batched hy
});
});
+describe.skipIf(!runDb)('POST /api/catalog/scraps/:id/commit — universe binding + relations (#7615)', () => {
+ const UNI = `commit-uni-${NONCE}`;
+ afterAll(async () => {
+ await query('DELETE FROM catalog_ingredient_refs WHERE ref_id = $1', [UNI]).catch(() => {});
+ await query('DELETE FROM universes WHERE id = $1', [UNI]).catch(() => {});
+ });
+
+ it('links every committed ingredient to the universe with the type-derived role, and clusters the batch with related-to edges', async () => {
+ await query('INSERT INTO universes (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING', [UNI, `Commit Universe ${NONCE}`]);
+ const scrap = await catalogDB.createScrap({ rawText: `Commit binding source ${NONCE}` });
+ createdScrapIds.add(scrap.id);
+
+ const r = await request(makeApp())
+ .post(`/api/catalog/scraps/${scrap.id}/commit`)
+ .send({
+ accepted: [
+ { type: 'character', name: `Commit Hero ${NONCE}` },
+ { type: 'idea', name: `Commit Idea ${NONCE}` },
+ ],
+ universeRef: UNI,
+ });
+
+ expect(r.status).toBe(201);
+ expect(r.body.ingredients).toHaveLength(2);
+ const [hero, idea] = r.body.ingredients;
+ createdIngredientIds.add(hero.id);
+ createdIngredientIds.add(idea.id);
+
+ const heroRefs = await catalogDB.listRefsForIngredient(hero.id);
+ expect(heroRefs).toEqual([expect.objectContaining({ refKind: 'universe', refId: UNI, role: 'canon-character' })]);
+ const ideaRefs = await catalogDB.listRefsForIngredient(idea.id);
+ expect(ideaRefs).toEqual([expect.objectContaining({ refKind: 'universe', refId: UNI, role: 'reference' })]);
+
+ // HAS_ANY_HOMING_REF is true for both — neither buckets as unlinked (#7615 core symptom).
+ const facets = await request(makeApp()).get('/api/catalog/facets');
+ const uniBucket = facets.body.universes.find((u) => u.refId === UNI);
+ expect(uniBucket?.count).toBeGreaterThanOrEqual(2);
+
+ // A single scrap's extractions form a connected cluster: one related-to
+ // edge for the pair, direction = lexicographically smaller id first.
+ const heroRelations = await catalogDB.listRelationsForIngredient(hero.id);
+ const [smallerId, largerId] = [hero.id, idea.id].sort();
+ const edge = [...heroRelations.outbound, ...heroRelations.inbound].find((e) => e.kind === 'related-to');
+ expect(edge).toBeTruthy();
+ expect(edge.fromId).toBe(smallerId);
+ expect(edge.toId).toBe(largerId);
+ });
+
+ it('omitting universeRef reproduces prior behavior exactly — source link only, no homing ref', async () => {
+ const scrap = await catalogDB.createScrap({ rawText: `Commit no-universe source ${NONCE}` });
+ createdScrapIds.add(scrap.id);
+
+ const r = await request(makeApp())
+ .post(`/api/catalog/scraps/${scrap.id}/commit`)
+ .send({ accepted: [{ type: 'idea', name: `Commit Unbound Idea ${NONCE}` }] });
+
+ expect(r.status).toBe(201);
+ const ing = r.body.ingredients[0];
+ createdIngredientIds.add(ing.id);
+
+ const refs = await catalogDB.listRefsForIngredient(ing.id);
+ expect(refs).toHaveLength(0);
+ const sources = await catalogDB.listSourcesForIngredient(ing.id);
+ expect(sources).toHaveLength(1);
+ });
+
+ it('mints no relation edges for a single-item batch or a batch over the 25-row bound', async () => {
+ const scrap = await catalogDB.createScrap({ rawText: `Commit bound source ${NONCE}` });
+ createdScrapIds.add(scrap.id);
+ const accepted = Array.from({ length: 26 }, (_, i) => ({ type: 'idea', name: `Commit Bound Idea ${i} ${NONCE}` }));
+
+ const r = await request(makeApp())
+ .post(`/api/catalog/scraps/${scrap.id}/commit`)
+ .send({ accepted });
+
+ expect(r.status).toBe(201);
+ expect(r.body.ingredients).toHaveLength(26);
+ for (const ing of r.body.ingredients) createdIngredientIds.add(ing.id);
+
+ for (const ing of r.body.ingredients) {
+ const rel = await catalogDB.listRelationsForIngredient(ing.id);
+ expect(rel.outbound).toHaveLength(0);
+ expect(rel.inbound).toHaveLength(0);
+ }
+ });
+
+ it('rolls back every ingredient, ref, and relation edge on a mid-batch failure', async () => {
+ const scrap = await catalogDB.createScrap({ rawText: `Commit rollback source ${NONCE}` });
+ createdScrapIds.add(scrap.id);
+ // A null `name` clears the route/Zod boundary (commitScrap itself does no
+ // input validation — that's the route layer's job) but violates the
+ // `catalog_ingredients.name TEXT NOT NULL` DB constraint on the second
+ // insert, forcing a real mid-transaction failure.
+ await expect(catalogDB.commitScrap({
+ scrapId: scrap.id,
+ accepted: [
+ { type: 'idea', name: `Commit Rollback First ${NONCE}` },
+ { type: 'idea', name: null },
+ ],
+ universeRef: UNI,
+ })).rejects.toThrow();
+
+ const { items } = await catalogDB.listIngredients({ query: `Commit Rollback First ${NONCE}` });
+ expect(items).toHaveLength(0); // the first insert did not survive the rollback
+ });
+});
+
describe.skipIf(!runDb)('GET /api/catalog/facets + ingredient filters (#1762)', () => {
const UNI = `route-uni-${NONCE}`;
afterAll(async () => {
diff --git a/server/routes/catalogParsedBodies.test.js b/server/routes/catalogParsedBodies.test.js
index 61f1bfb1a6..faa311745e 100644
--- a/server/routes/catalogParsedBodies.test.js
+++ b/server/routes/catalogParsedBodies.test.js
@@ -252,6 +252,28 @@ describe('Catalog parsed write bodies', () => {
scrapId: 'scrap-1',
accepted,
embeds: [{ embedding: null, model: null }],
+ universeRef: undefined,
+ role: undefined,
+ });
+ });
+
+ it('forwards universeRef and role from the commit body (#7615)', async () => {
+ mocks.embedBatch.mockResolvedValue([{ embedding: null, model: null }]);
+ const response = await request(makeApp())
+ .post('/api/catalog/scraps/scrap-1/commit')
+ .send({
+ accepted: [{ type: 'idea', name: 'Draft' }],
+ universeRef: 'universe-1',
+ role: 'canon-idea',
+ });
+
+ expect(response.status).toBe(201);
+ expect(mocks.commitScrap).toHaveBeenCalledWith({
+ scrapId: 'scrap-1',
+ accepted: [{ type: 'idea', name: 'Draft' }],
+ embeds: [{ embedding: null, model: null }],
+ universeRef: 'universe-1',
+ role: 'canon-idea',
});
});
});
diff --git a/server/services/catalogDB.commit.test.js b/server/services/catalogDB.commit.test.js
index 9e58ac88de..b154e928bd 100644
--- a/server/services/catalogDB.commit.test.js
+++ b/server/services/catalogDB.commit.test.js
@@ -4,6 +4,8 @@ const mocks = vi.hoisted(() => ({
client: { query: vi.fn() },
createIngredient: vi.fn(),
linkIngredientToSource: vi.fn(),
+ linkIngredientToRef: vi.fn(),
+ linkIngredientRelation: vi.fn(),
withTransaction: vi.fn(),
}));
@@ -17,6 +19,11 @@ vi.mock('./catalogDB/ingredients.js', () => ({
vi.mock('./catalogDB/refs.js', () => ({
linkIngredientToSource: mocks.linkIngredientToSource,
+ linkIngredientToRef: mocks.linkIngredientToRef,
+ linkIngredientRelation: mocks.linkIngredientRelation,
+ // Real implementation — a small pure lookup, not worth mocking away from
+ // the type→role contract the tests below assert against.
+ universeRefRoleForType: (type) => ({ character: 'canon-character', place: 'canon-place', object: 'canon-object' }[type] || 'reference'),
}));
import { commitScrap } from './catalogDB/commit.js';
@@ -24,6 +31,12 @@ import { commitScrap } from './catalogDB/commit.js';
beforeEach(() => {
vi.clearAllMocks();
mocks.withTransaction.mockImplementation((fn) => fn(mocks.client));
+ // clearAllMocks resets call history but not a prior mockRejectedValue —
+ // reset the default resolution so one test's induced failure can't bleed
+ // into the next.
+ mocks.linkIngredientToSource.mockResolvedValue(undefined);
+ mocks.linkIngredientToRef.mockResolvedValue(undefined);
+ mocks.linkIngredientRelation.mockResolvedValue(undefined);
});
describe('commitScrap', () => {
@@ -91,4 +104,84 @@ describe('commitScrap', () => {
accepted: [{ type: 'idea', name: 'Example Idea' }],
})).rejects.toBe(failure);
});
+
+ it('links every ingredient to universeRef with the type-derived role, in the transaction client (#7615)', async () => {
+ mocks.createIngredient
+ .mockResolvedValueOnce({ id: 'cat-chr-example' })
+ .mockResolvedValueOnce({ id: 'cat-idea-example' });
+
+ await commitScrap({
+ scrapId: 'cat-scrap-example',
+ accepted: [
+ { type: 'character', name: 'Example Character' },
+ { type: 'idea', name: 'Example Idea' },
+ ],
+ universeRef: 'universe-1',
+ });
+
+ expect(mocks.linkIngredientToRef).toHaveBeenNthCalledWith(1, 'cat-chr-example', 'universe', 'universe-1', 'canon-character', { client: mocks.client });
+ expect(mocks.linkIngredientToRef).toHaveBeenNthCalledWith(2, 'cat-idea-example', 'universe', 'universe-1', 'reference', { client: mocks.client });
+ });
+
+ it('an explicit role overrides the type-derived default', async () => {
+ mocks.createIngredient.mockResolvedValueOnce({ id: 'cat-idea-example' });
+
+ await commitScrap({
+ scrapId: 'cat-scrap-example',
+ accepted: [{ type: 'idea', name: 'Example Idea' }],
+ universeRef: 'universe-1',
+ role: 'canon-idea',
+ });
+
+ expect(mocks.linkIngredientToRef).toHaveBeenCalledWith('cat-idea-example', 'universe', 'universe-1', 'canon-idea', { client: mocks.client });
+ });
+
+ it('links no universe ref when universeRef is omitted — prior behavior preserved', async () => {
+ mocks.createIngredient.mockResolvedValueOnce({ id: 'cat-idea-example' });
+
+ await commitScrap({ scrapId: 'cat-scrap-example', accepted: [{ type: 'idea', name: 'Example Idea' }] });
+
+ expect(mocks.linkIngredientToRef).not.toHaveBeenCalled();
+ });
+
+ it('mints one related-to edge per unordered pair, from_id = lexicographically smaller id', async () => {
+ mocks.createIngredient
+ .mockResolvedValueOnce({ id: 'cat-idea-b' })
+ .mockResolvedValueOnce({ id: 'cat-idea-a' })
+ .mockResolvedValueOnce({ id: 'cat-idea-c' });
+
+ await commitScrap({
+ scrapId: 'cat-scrap-example',
+ accepted: [
+ { type: 'idea', name: 'B' },
+ { type: 'idea', name: 'A' },
+ { type: 'idea', name: 'C' },
+ ],
+ });
+
+ // 3 ingredients (created in order b, a, c) → 3 unordered pairs, each
+ // oriented smaller-id-first regardless of creation order: cat-idea-a <
+ // cat-idea-b < cat-idea-c lexicographically.
+ expect(mocks.linkIngredientRelation).toHaveBeenCalledTimes(3);
+ expect(mocks.linkIngredientRelation).toHaveBeenCalledWith('cat-idea-a', 'cat-idea-b', 'related-to', { client: mocks.client });
+ expect(mocks.linkIngredientRelation).toHaveBeenCalledWith('cat-idea-b', 'cat-idea-c', 'related-to', { client: mocks.client });
+ expect(mocks.linkIngredientRelation).toHaveBeenCalledWith('cat-idea-a', 'cat-idea-c', 'related-to', { client: mocks.client });
+ });
+
+ it('mints no relation edges for a single-item batch', async () => {
+ mocks.createIngredient.mockResolvedValueOnce({ id: 'cat-idea-solo' });
+
+ await commitScrap({ scrapId: 'cat-scrap-example', accepted: [{ type: 'idea', name: 'Solo' }] });
+
+ expect(mocks.linkIngredientRelation).not.toHaveBeenCalled();
+ });
+
+ it('mints no relation edges for a batch over the 25-row bound', async () => {
+ const accepted = Array.from({ length: 26 }, (_, i) => ({ type: 'idea', name: `Idea ${i}` }));
+ for (let i = 0; i < 26; i++) mocks.createIngredient.mockResolvedValueOnce({ id: `cat-idea-${i}` });
+
+ await commitScrap({ scrapId: 'cat-scrap-example', accepted });
+
+ expect(mocks.linkIngredientRelation).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/catalogDB/commit.js b/server/services/catalogDB/commit.js
index dfb75e8e1a..48a1805eab 100644
--- a/server/services/catalogDB/commit.js
+++ b/server/services/catalogDB/commit.js
@@ -7,13 +7,24 @@
import { withTransaction } from '../../lib/db.js';
import { createIngredient } from './ingredients.js';
-import { linkIngredientToSource } from './refs.js';
+import { linkIngredientToSource, linkIngredientToRef, linkIngredientRelation, universeRefRoleForType } from './refs.js';
+
+// Same-batch `related-to` edges connect a single scrap's extractions into one
+// cluster instead of N isolated nodes (#7615). Bounded: a batch above this
+// size mints none — the schema allows up to 200 accepted rows, which would be
+// 19,900 edges for every unordered pair at the cap.
+const RELATION_BATCH_LIMIT = 25;
/**
* Persist every accepted extraction draft and its source link atomically.
* Embeddings are prepared by the caller before this DB-only transaction starts.
+ *
+ * `universeRef` (+ optional `role`) binds every created ingredient to the
+ * given universe via catalog_ingredient_refs, in the same transaction, so a
+ * mid-batch failure rolls back ingredients, refs, and relations together.
+ * Omitting it reproduces prior behavior exactly (source link only).
*/
-export async function commitScrap({ scrapId, accepted = [], embeds = [] } = {}) {
+export async function commitScrap({ scrapId, accepted = [], embeds = [], universeRef = null, role = null } = {}) {
return withTransaction(async (client) => {
const created = [];
for (let i = 0; i < accepted.length; i++) {
@@ -28,8 +39,34 @@ export async function commitScrap({ scrapId, accepted = [], embeds = [] } = {})
embeddingModel: embedding?.model ?? null,
}, { client, source: 'extract' });
await linkIngredientToSource(ingredient.id, scrapId, draft.span || null, { client });
+ if (universeRef) {
+ await linkIngredientToRef(
+ ingredient.id,
+ 'universe',
+ universeRef,
+ role || universeRefRoleForType(draft.type),
+ { client },
+ );
+ }
created.push(ingredient);
}
+
+ // Mint one `related-to` edge per unordered pair among this batch's
+ // ingredients, so a single source's extractions form a connected cluster.
+ // Deterministic direction: from_id = the lexicographically smaller id —
+ // the PK is (from_id, to_id, kind), so an arbitrary direction would let a
+ // re-commit create a reciprocal duplicate instead of reviving the same row.
+ if (created.length >= 2 && created.length <= RELATION_BATCH_LIMIT) {
+ for (let i = 0; i < created.length; i++) {
+ for (let j = i + 1; j < created.length; j++) {
+ const [fromId, toId] = created[i].id < created[j].id
+ ? [created[i].id, created[j].id]
+ : [created[j].id, created[i].id];
+ await linkIngredientRelation(fromId, toId, 'related-to', { client });
+ }
+ }
+ }
+
return created;
});
}
diff --git a/server/services/catalogDB/refs.js b/server/services/catalogDB/refs.js
index 1d041852b4..e3effb179c 100644
--- a/server/services/catalogDB/refs.js
+++ b/server/services/catalogDB/refs.js
@@ -74,12 +74,16 @@ export async function listSiblingIngredientsBySource(ingredientId, scrapIds) {
return grouped;
}
-export async function linkIngredientToRef(ingredientId, refKind, refId, role) {
+// `{ client }` is optional — see linkIngredientToSource. Passing the same
+// client used to insert the ingredient row keeps the ref link in the same
+// transaction so a mid-batch failure rolls back both halves (#7615).
+export async function linkIngredientToRef(ingredientId, refKind, refId, role, { client } = {}) {
// ON CONFLICT DO UPDATE revives a soft-deleted row instead of leaving it
// tombstoned. The trigger only bumps sync_sequence when `deleted` or
// `deleted_at` actually change, so a link-on-active-row stays a no-op for
// peers (no spurious sync event).
- await query(
+ const exec = client ? client.query.bind(client) : query;
+ await exec(
`INSERT INTO catalog_ingredient_refs (ingredient_id, ref_kind, ref_id, role)
VALUES ($1, $2, $3, $4)
ON CONFLICT (ingredient_id, ref_kind, ref_id, role) DO UPDATE
@@ -125,6 +129,20 @@ const CD_REF_ROLE_BY_TYPE = Object.freeze({
});
export const cdRefRoleForType = (type) => CD_REF_ROLE_BY_TYPE[type] || 'reference';
+// Catalog ingredient `type` → universe ref role (#7615). The `canon-<kind>`
+// convention is what catalogCanonProjection.js and catalogUniverseTags.js
+// already expect for character/place/object; everything else (idea/scene/
+// concept and user-defined types) links as a generic 'reference'. Lives next
+// to seriesRefRoleForType/cdRefRoleForType so every remix target shares one
+// role-vocabulary home.
+const UNIVERSE_REF_ROLE_BY_TYPE = Object.freeze({
+ character: 'canon-character',
+ place: 'canon-place',
+ object: 'canon-object',
+});
+export const universeRefRoleForType = (type) => UNIVERSE_REF_ROLE_BY_TYPE[type] || 'reference';
+
+
// Link a batch of already-resolved catalog ingredients to a Creative Director
// project via catalog_ingredient_refs with ref_kind='creative-director' (#1808)
// — the reserved-but-previously-unwritten ref kind. Mirrors
@@ -208,9 +226,13 @@ export async function listIngredientsForRef(refKind, refId) {
// (the trg_catalog_relation_sync_seq trigger bumps sync_sequence only when
// deleted/deleted_at actually change, so a link-on-active-row stays a no-op).
-export async function linkIngredientRelation(fromId, toId, kind) {
+// `{ client }` is optional — see linkIngredientToSource. Passing the same
+// client used to insert the ingredient rows keeps the relation edge in the
+// same transaction so a mid-batch failure rolls back both halves (#7615).
+export async function linkIngredientRelation(fromId, toId, kind, { client } = {}) {
if (fromId === toId) throw new Error('cannot relate an ingredient to itself');
- await query(
+ const exec = client ? client.query.bind(client) : query;
+ await exec(
`INSERT INTO catalog_ingredient_relations (from_id, to_id, kind)
VALUES ($1, $2, $3)
ON CONFLICT (from_id, to_id, kind) DO UPDATE